From b9dc72fdd063d0f4728d5d420be4b9e50d989307 Mon Sep 17 00:00:00 2001 From: kanym Date: Tue, 6 Oct 2026 13:36:31 +0200 Subject: [PATCH 001/163] localisation(ru): add Russian skeleton from English --- .../Translations/Russian/compendium.json | 206 ++++++++++++++++++ JotunnModStub/Translations/Russian/hover.json | 56 +++++ JotunnModStub/Translations/Russian/items.json | 138 ++++++++++++ .../Translations/Russian/merchants.json | 133 +++++++++++ .../Translations/Russian/messages.json | 205 +++++++++++++++++ JotunnModStub/Translations/Russian/races.json | 38 ++++ .../Translations/Russian/status_effects.json | 62 ++++++ 7 files changed, 838 insertions(+) create mode 100644 JotunnModStub/Translations/Russian/compendium.json create mode 100644 JotunnModStub/Translations/Russian/hover.json create mode 100644 JotunnModStub/Translations/Russian/items.json create mode 100644 JotunnModStub/Translations/Russian/merchants.json create mode 100644 JotunnModStub/Translations/Russian/messages.json create mode 100644 JotunnModStub/Translations/Russian/races.json create mode 100644 JotunnModStub/Translations/Russian/status_effects.json diff --git a/JotunnModStub/Translations/Russian/compendium.json b/JotunnModStub/Translations/Russian/compendium.json new file mode 100644 index 0000000..0b27389 --- /dev/null +++ b/JotunnModStub/Translations/Russian/compendium.json @@ -0,0 +1,206 @@ +{ + "rov_compendium_aswid_always_active_every_form_with": "Always active, in every form, with no key to hold - only the on/off toggle. Drains a $1m radius by day, $2m by night, for magic damage that scales with your Blood Magic skill, healing you for the damage dealt. Enemies at or below $3% health are executed outright. The aura hits for half in human form, full as a Bat, and double as Mist. It cannot tell traders from monsters, so switch it off with [I] before talking to Haldor or Hildir.\n", + "rov_compendium_aswid_asmund_passive": "[Fader Unlock] Asmund (Passive):", + "rov_compendium_aswid_aswid_s_curse": "The Aswid's Curse\n", + "rov_compendium_aswid_bat_form_g_key_night": "[Eikthyr Unlock] Bat Form ('G' Key, night only): Take the shape of a bat.\n", + "rov_compendium_aswid_bat_form_now_answers_by": "[The Elder Unlock] Bat Form now answers by day as well as night.\n", + "rov_compendium_aswid_benedictus_et_afflictus": "[Base Passive] Benedictus et Afflictus:", + "rov_compendium_aswid_claws_beast_s_grows_blackened": "[Base Passive] Claws of the Beast ([K], $1s): Grows blackened claws for a limited time instead of a weapon. Bare-handed blows land at $2% of a full-grown pair's weight, all of it as slash, and they grow with every boss that falls. Draw a sword and they wait, sheathe it and they are back, until the timer runs out and they retract on their own - no slot wasted between casts. They cannot be dropped, traded or stolen while grown - and in bat or mist form you have no hands to hold them with.\n", + "rov_compendium_aswid_dominate_native_interact_key": "[Yagluth Unlock] Dominate (native Interact key):", + "rov_compendium_aswid_eclipse_j_key_day_only": "[Yagluth Unlock] Eclipse ('J' Key, day only):", + "rov_compendium_aswid_freezing_blood_passive": "[Moder Unlock] Freezing Blood (Passive):", + "rov_compendium_aswid_gain_permanent_immunity_freezing_status": "You gain permanent immunity to the Freezing status (mountains/snowstorms) and to Poison damage.\n", + "rov_compendium_aswid_hair_beard_turn_as_dark": "Your hair and beard turn as dark as the abyss. You become 10% taller and gain a flat +$1 Physical Damage.\n", + "rov_compendium_aswid_second_cast_that_forces_night": "A $1-second cast that forces the night to fall around you for $2 seconds, letting you claim your night-doubled bonuses under the sun. Fails silently if it is already night. $3-minute cooldown.\n", + "rov_compendium_aswid_sense_every_untamed_creature_within": "You sense every untamed creature within $1m, marking it with a telltale glow.\n", + "rov_compendium_aswid_superhuman_senses_passive": "[Moder Unlock] Superhuman Senses (Passive):", + "rov_compendium_aswid_take_no_fall_damage_physical": "You take no fall damage, and physical kills automatically devour edible enemies (Vae Victis) for Blood Magic XP. Your physical stats scale with every boss you defeat: +$1 Armor, +$2 Damage, +$3% Speed and Jump, and +$4% Lifesteal on physical hits. All of these bonuses double during the night. You can cast Blood Magic items with infinite Eitr, and your Blood Magic skill rises $5x as fast.\n", + "rov_compendium_aswid_tame_u_key_asksvin_join": "[Fader Unlock] Tame ('U' Key): Asksvin join the huntable list.\n", + "rov_compendium_aswid_tame_u_key_lox_join": "[Yagluth Unlock] Tame ('U' Key): Lox join the huntable list.\n", + "rov_compendium_aswid_tame_u_key_tame_boar": "[Eikthyr Unlock] Tame ('U' Key): Tame a boar under your cursor.\n", + "rov_compendium_aswid_tame_u_key_wolves_join": "[Moder Unlock] Tame ('U' Key): Wolves join the huntable list.\n", + "rov_compendium_aswid_target_non_tameable_non_boss": "Target a non-tameable, non-boss enemy to dominate it for $1 seconds ($2-min cooldown). Dominated thralls fight alongside you and drop standard loot.\n", + "rov_compendium_aswid_title": "Aswid Secrets", + "rov_compendium_aswid_transform_into_elusive_mist_become": "You transform into an elusive mist. You become immune to physical (blunt/slash/pierce) and poison damage, and take no fall damage, but you cannot attack, run, or jump. Your Vampiric Aura deals double damage while mist. Sunrise breaks the transformation.\n", + "rov_compendium_aswid_vampiric_aura_passive_toggle": "Vampiric Aura (Passive, [I] to toggle):", + "rov_compendium_aswid_weight_shadows_h_key_toggle": "[The Queen Unlock] Weight of Shadows ('H' Key, toggle):", + "rov_compendium_draugh_born_dead_buried_alive_take": "[Base Passive] Born Dead, Buried Alive: You take $1% less Physical (blunt/slash/pierce) damage, but Fire and Spirit strike you $2% harder. Skeletons, draugr, ghosts and wraiths no longer see you as prey. Your digestive system adapts to death, allowing you to consume raw and rotten meat (neck tail, raw meat, entrails, blood, etc.) - proper cooked food and berries disgust you and cannot be eaten.\n", + "rov_compendium_draugh_draugh_s_awakening": "The Draugh's Awakening\n", + "rov_compendium_draugh_grave_chill_passive_parry_frost": "[Moder Unlock] Grave Chill (Passive/Parry): Frost can no longer touch you at all. A successful parry now also unleashes a freezing nova, dealing $1 Frost damage and pushing back everything within $2m of you - the nova has its own $3 second cooldown, separate from Rotting Edge's poison splash, which still fires on every parry.\n", + "rov_compendium_draugh_rotting_edge_passive_parry_physical": "[The Elder Unlock] Rotting Edge (Passive/Parry): Your physical attacks are laced with the swamp's decay, adding poison damage worth $1% of the physical harm you deal. A successful parry also splashes $2 poison damage onto whoever you parried.\n", + "rov_compendium_draugh_slowly_we_rot_passive_being": "[Eikthyr Unlock] Slowly We Rot (Passive): Being Wet no longer saps your stamina regeneration, and it heals rather than does nothing for you - your health regenerates $1% faster while wet or swimming.\n", + "rov_compendium_draugh_steal_their_breath_execution_while": "[Fader Unlock] Steal Their Breath (Execution): While surviving in the Zombie Ritual's ghost state, scoring a killing blow on any enemy will instantly restore $1% of your maximum health, stop the Eitr drain, and save your life, bringing you fully back to the world of the living.\n", + "rov_compendium_draugh_swarm_terror_retaliation_whenever_are": "[The Queen Unlock] Swarm of Terror (Retaliation): Whenever you are struck in melee combat, you automatically spawn $1 Seeker Broods to fight for you. They live for $2 seconds, with a $3 second cooldown between spawns.\n", + "rov_compendium_draugh_title": "Draugh Secrets", + "rov_compendium_draugh_undead_fortitude_passive_poison_can": "[Bonemass Unlock] Undead Fortitude (Passive): Poison can no longer touch you at all. Striking a staggered enemy deals $1% more physical damage, and death no longer costs you skill experience. Should any player die within $2m of you, their fall leaves Human Meat behind - flesh only a Draugh can stomach.\n", + "rov_compendium_draugh_zombie_ritual_passive_survival_when": "[Yagluth Unlock] Zombie Ritual (Passive Survival): When you take fatal damage, you do not die. Instead, you enter a ghostly state, immune to all damage, while your Eitr drains at $1 per second. If your Eitr hits zero before you are saved, you truly die. Once triggered, the ritual cannot save you again for $2 minutes.\n", + "rov_compendium_dvergar_dvergar_s_craft": "The Dvergar's Craft\n", + "rov_compendium_dvergar_kin_traders_passive_haldor_hildir": "[Bonemass Unlock] Kin of the Traders (Passive): Haldor and Hildir know their own. Their prices drop by $1% for you, and what they pay for your trophies and hunting rewards rises by $2%.\n", + "rov_compendium_dvergar_mining_affinity_passive_pickaxe_answers": "[Eikthyr Unlock] Mining Affinity (Passive): The pickaxe answers to you. Veins break faster, cost you less stamina to work, and sometimes give up more than they should.\n", + "rov_compendium_dvergar_runic_overcharge_key_spend_eitr": "[Fader Unlock] Runic Overcharge ('$1' Key): Spend $2 eitr to load the runes. Your next blow with a favoured weapon lands with $3x its weight. Hold the charge no longer than $4 seconds or it bleeds away.\n", + "rov_compendium_dvergar_runic_ping_key_spend_eitr": "[Yagluth Unlock] Runic Ping ('$1' Key): Spend $2 eitr to send a pulse through the stone. For $3 seconds every ore vein and every hidden enemy within $4 meters is lit for you alone.\n", + "rov_compendium_dvergar_runic_spark_runes_blood_earth": "[Base Passive] Runic Spark: The runes in your blood earth themselves through whatever you strike. Every blow you land carries +$1 Lightning damage - a bonus that grows as each boss falls.\n", + "rov_compendium_dvergar_small_stubborn_stand_shorter_than": "[Base Passive] Small and Stubborn: You stand $1% shorter than a human and carry $2 less health for it. The dvergr hood never leaves your head - wear whatever helm you please and keep every point of its protection, but the runes will always show you as one of the deep folk.\n", + "rov_compendium_dvergar_smithing_jewelry_passive_waste_nothing": "[Bonemass Unlock] Smithing and Jewelry (Passive): You waste nothing at the anvil. Metal and gems cost you $1% less when crafting and upgrading.\n", + "rov_compendium_dvergar_title": "Dvergar Secrets", + "rov_compendium_dvergar_weapon_affinity_passive_blows_struck": "Weapon Affinity (Passive): $1. Blows struck with these land harder and cost less stamina. The saving never grows - a tier only ever hands you another weapon to feel at home with - and your skill rises no faster than anyone else's.\n", + "rov_compendium_dvergar_weapon_axe": "Axe", + "rov_compendium_dvergar_weapon_bow": "Bow", + "rov_compendium_dvergar_weapon_crossbow": "Crossbow", + "rov_compendium_dvergar_weapon_hammer": "Hammer", + "rov_compendium_fenrir_beast_within_physical_stats_scale": "[Base Passive] The Beast Within: Your physical stats scale with every boss you defeat: +$1 Armor, +$2 Damage, +$3% Speed, +$4% Jump, and -$5% Fall Damage.\n", + "rov_compendium_fenrir_cultist_form_j_key_night": "[Yagluth Unlock] Cultist Form ('J' Key, night only): A robed shape that claws and channels fire. Lasts 1 minute, 10-minute cooldown.\n", + "rov_compendium_fenrir_cultist_form_now_answers_by": "[Fader Unlock] Cultist Form now answers by day as well as night, and may be held as long as you wish.\n", + "rov_compendium_fenrir_cultist_form_s_cooldown_falls": "[The Queen Unlock] Cultist Form's cooldown falls to 5 minutes (still night only, still 1 minute).\n", + "rov_compendium_fenrir_curse_pack": "The Curse of the Pack\n", + "rov_compendium_fenrir_cursed_claws_s_wolf_s": "[Base Passive] Cursed Claws ([K], $1s): The wolf's hands, kept on in the man's shape for a limited time instead of a weapon. Bare-handed blows land at $2% of a full-grown pair's weight, all of it as slash, and they grow with every boss that falls. Draw a sword and they wait, sheathe it and they are back, until the timer runs out and they retract on their own - no slot wasted between casts. They cannot be dropped, traded or stolen while grown - and in beast form the jaws do the work instead.\n", + "rov_compendium_fenrir_fenring_form_h_key_night": "[Moder Unlock] Fenring Form ('H' Key, night only): Stand as a true Fenring - heavy claws and a leaping strike, and the strongest of the four shapes so far.\n", + "rov_compendium_fenrir_fenring_form_now_answers_by": "[The Queen Unlock] Fenring Form now answers by day as well as night.\n", + "rov_compendium_fenrir_g_now_calls_ulv_form": "[Moder Unlock] 'G' now calls Ulv Form instead of Wolf, and answers by day as well as night.\n", + "rov_compendium_fenrir_sunrise_breaks_any_night_bound": "Sunrise breaks any night-bound form early and leaves the beast too tired to change shape again for a short while after.\n", + "rov_compendium_fenrir_title": "Fenrir Secrets", + "rov_compendium_fenrir_ulv_form_h_key_night": "[Bonemass Unlock] Ulv Form ('H' Key, night only): A heavier wolf shape - stronger bite attacks, still bound to the dark.\n", + "rov_compendium_fenrir_wolf_form_g_key_night": "[The Elder Unlock] Wolf Form ('G' Key, night only): Take the shape of a wolf. Faster and lighter on your feet, with three claw attacks of growing weight on Left, Right, and Middle Mouse.\n", + "rov_compendium_fenrir_wolf_form_now_answers_by": "[Bonemass Unlock] Wolf Form now answers by day as well as night.\n", + "rov_compendium_furling_all_weapon_combat_skills_gain": "All weapon and combat skills gain $1x XP permanently. You're short, but very fast - your movement speed is permanently increased by $2%.\n", + "rov_compendium_furling_are_permanently_wreathed_flames_are": "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", + "rov_compendium_furling_blue_foods_those_that_restore": "Blue foods (those that restore Eitr) last twice as long for you compared to normal players.\n", + "rov_compendium_furling_combat_mastery": "[Base Passive] Combat Mastery:", + "rov_compendium_furling_dance_dead_passive": "[Bonemass Unlock] Dance of the Dead (Passive):", + "rov_compendium_furling_every_mead_potion_wine_bomb": "Every mead, potion, wine, bomb, or batch of ammunition you craft comes out doubled - one copy for the recipe, one for free.\n", + "rov_compendium_furling_footsteps_small_movements_no_longer": "Your footsteps and small movements no longer betray you - any noise you make within $1 meters goes unheard.\n", + "rov_compendium_furling_master_shadows_passive": "[Eikthyr Unlock] Master of Shadows (Passive):", + "rov_compendium_furling_passive": "[Moder Unlock] $1 (Passive):", + "rov_compendium_furling_passive_2": "[Yagluth Unlock] $1 (Passive):", + "rov_compendium_furling_passive_3": "[The Queen Unlock] $1 (Passive):", + "rov_compendium_furling_secrets_hoard": "The Secrets of the Hoard\n", + "rov_compendium_furling_take_less_fire_damage_less": "You take $1% less Fire damage and $2% less Poison damage. Your arrows carry at least $3 Fire damage of their own.\n", + "rov_compendium_furling_through_fire_flames_passive": "[Fader Unlock] Through Fire and Flames (Passive):", + "rov_compendium_furling_title": "Furling Secrets", + "rov_compendium_furling_whenever_normal_enemy_dies_within": "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", + "rov_compendium_furling_while_are_plains_biome_x": "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", + "rov_compendium_furling_wickerman_passive": "[The Elder Unlock] The Wickerman (Passive):", + "rov_compendium_skadi_become_great_frost_dragon_herself": "Become the great frost dragon herself for 1 minute, then wait 10 before calling her again. Afoot, Left Mouse bites and claws for no cost at all, while Middle Mouse breathes a stream of ice. On the wing, Left Mouse looses a barrage of shards. Only the breath and the barrage draw upon eitr.\n", + "rov_compendium_skadi_bones_dragon_rise_at_call": "The bones of a dragon rise at your call, wreathed in frost. It rends with bite and claw, sweeps all around it with a spinning tail (Right Mouse), and its breath carries thrice the fury of Moder's.\n", + "rov_compendium_skadi_bound_stonecutter_that_shaped_may": "It is bound to the stonecutter that shaped it and may never leave the $1 meters around it - the same circle the station itself builds in. It cannot be named, cannot be ordered and will not follow you. It guards the stone that cut it, and that is the whole of what it does.\n", + "rov_compendium_skadi_cold_cannot_touch_frost_answers": "The cold cannot touch you, and frost answers to your hand. You are immune to the Cold status, take only half damage from frost, and every blow you land carries +$1 Frost damage - a bonus that grows as each boss falls.\n", + "rov_compendium_skadi_cold_spell_middle_mouse": "[Eikthyr Unlock] Cold Spell (Middle Mouse):", + "rov_compendium_skadi_cold_spell_scatters_into_ten": "Your Cold Spell scatters into ten shards, spreading its bite across all before you. The wider cast needs 4 seconds to gather itself.\n", + "rov_compendium_skadi_crystal_golem": "\n-- THE CRYSTAL GOLEM --\n", + "rov_compendium_skadi_cut_one_at_stonecutter_stone": "Cut one at a stonecutter for a stone golem's trophy, $1 crystal and a dragon tear. The stone answers to no one who is not Skadi, so what you raise is yours and stays yours.\n", + "rov_compendium_skadi_drake_breath_left_mouse": "[Bonemass Unlock] Drake Breath (Left Mouse):", + "rov_compendium_skadi_drake_form_g_key": "[The Elder Unlock] Drake Form ('G' Key):", + "rov_compendium_skadi_drake_form_may_now_spit": "Your drake form may now spit ice at your enemies.\n", + "rov_compendium_skadi_freezing_can_no_longer_reach": "Freezing can no longer reach you at all, and your eitr returns half again as fast.\n", + "rov_compendium_skadi_frost_cannot_wound_at_all": "Frost cannot wound you at all, and a freezing aura bleeds from your skin, gnawing at every untamed creature within 3 meters.\n", + "rov_compendium_skadi_heart_winter_passive": "[Yagluth Unlock] Heart of Winter (Passive):", + "rov_compendium_skadi_hurl_shard_ice_at_whatever": "Hurl a shard of ice at whatever you look upon, for $1 Frost damage. It draws on 20 stamina rather than eitr, so it serves you from your very first winter.\n", + "rov_compendium_skadi_ice_affinity": "[Base Passive] Ice Affinity:", + "rov_compendium_skadi_improved_cold_spell": "[Yagluth Unlock] Improved Cold Spell:", + "rov_compendium_skadi_killing_gales_mountains_soften_mere": "The killing gales of the mountains soften to a mere chill - you suffer Cold where others would freeze.\n", + "rov_compendium_skadi_moder_form_h_key": "[Moder Unlock] Moder Form ('H' Key):", + "rov_compendium_skadi_moder_form_may_now_held": "Moder Form may now be held as long as you wish, with no wait between callings.\n", + "rov_compendium_skadi_moder_form_now_answers_again": "Moder Form now answers you again after only 5 minutes.\n", + "rov_compendium_skadi_one_stonecutter_holds_them_no": "One stonecutter holds $1 of them, and no more than $2 may stand within a day's walk of each other. Break the stonecutter and what it cut goes still $3 seconds later.\n", + "rov_compendium_skadi_secrets_winter": "The Secrets of Winter\n", + "rov_compendium_skadi_skeleton_dragon_form_j_key": "[Fader Unlock] Skeleton Dragon Form ('J' Key):", + "rov_compendium_skadi_take_shape_frost_drake_right": "Take the shape of a frost drake. Right Mouse lifts you into flight: you glide wherever you aim, hold W to climb and gather speed, hold Shift with it to spend stamina on a burst of speed, and press S to beat backwards along your aim while your gaze stays where it was. Release everything and you hold level for five seconds before settling into a slow descent. Water cannot hold you - your wings drag you free of the sea as readily as they lift you from the shore. In this shape you cannot yet strike.\n", + "rov_compendium_skadi_tear_cold_nothing_wakes_stone": "The tear is cold. Nothing wakes in the stone until the mountain's queen has fallen.\n", + "rov_compendium_skadi_title": "Skadi Secrets", + "rov_compendium_skadi_winter_incarnate_passive": "[The Queen Unlock] Winter Incarnate (Passive):", + "rov_compendium_skadi_winter_s_welcome_passive": "[Bonemass Unlock] Winter's Welcome (Passive):", + "rov_compendium_skeleton_blades_points_find_little_cut": "Blades and points find little to cut in you and do half their work, but a hammer's weight finds everything, and hurts you the more for it.\n", + "rov_compendium_skeleton_bones_alight": "[Moder Unlock] Bones Alight:", + "rov_compendium_skeleton_bones_blades": "[Base Passive] Bones and Blades:", + "rov_compendium_skeleton_crypt_answers": "[The Queen Unlock] The Crypt Answers:", + "rov_compendium_skeleton_dead_now_follow_harm_deal": "$1 of the dead now follow you, and $2% of the harm you deal comes back as your own strength.\n", + "rov_compendium_skeleton_every_enemy_put_down_rises": "Every enemy you put down rises to fight for you, up to $1 at your side at once.\n", + "rov_compendium_skeleton_first_blow": "[The Elder Unlock] The First Blow:", + "rov_compendium_skeleton_first_strike_out_dark_staggers": "The first strike out of the dark staggers whatever it lands upon. The dead may do this once every 5 seconds.\n", + "rov_compendium_skeleton_frame_remade_harder_cast_fire": "Your frame is remade in a harder cast, and fire clings to it: everything near enough to feel it is scorched. Your wounds also close faster than bone has any right to.\n", + "rov_compendium_skeleton_green_rot": "[Eikthyr Unlock] The Green Rot:", + "rov_compendium_skeleton_host_own": "[Fader Unlock] A Host of Your Own:", + "rov_compendium_skeleton_killing_blow_no_longer_ends": "A killing blow no longer ends you. You are made whole where you stand - and then the dark magic must gather itself for 5 minutes before it will do so again.\n", + "rov_compendium_skeleton_no_hunger_moves_no_meal": "No hunger moves you and no meal can help you - mortal food is nothing to dry bones. In its place the dead grow strong as their betters fall: you carry +$1 Maximum Health at your present standing. Nor does effort tire you; you have no stamina to spend at all.\n", + "rov_compendium_skeleton_poison_has_nothing_left_poison": "Poison has nothing left to poison - it cannot touch you at all - and your bones take on its sickly cast. Every blow you land returns $1% of what it deals in physical harm to your own frame.\n", + "rov_compendium_skeleton_risen_again": "[Yagluth Unlock] Risen Again:", + "rov_compendium_skeleton_rotten_touch": "[Bonemass Unlock] Rotten Touch:", + "rov_compendium_skeleton_secrets_crypt": "The Secrets of the Crypt\n", + "rov_compendium_skeleton_stand_at_eight_standings_earned": "You stand at the $1 of eight standings, earned by the fall of $2.\n", + "rov_compendium_skeleton_stand_at_first_eight_standings": "You stand at the first of eight standings; no boss has yet fallen to your reckoning.\n", + "rov_compendium_skeleton_title": "Skeleton Secrets", + "rov_compendium_skeleton_undead_diet": "[Base Passive] Undead Diet:", + "rov_compendium_skeleton_what_strike_sicken_every_blow": "What you strike, you sicken - every blow carries 20 Poison damage of its own.\n", + "rov_compendium_sverm_acid_hemolymph_whoever_strikes_melee": "[Bonemass Unlock] Acid Hemolymph: Whoever strikes you in melee takes $1 poison back for the trouble.\n", + "rov_compendium_sverm_annealed_chitin_emberform_eight_tiers": "[Fader Unlock] Annealed Chitin and Emberform: Eight tiers of burning have turned the flaw into armour - fire no longer hurts you, and the chitin goes black with a red heat under it.\n", + "rov_compendium_sverm_beehives_raise_vanilla_hives_inside": "The beehives: raise vanilla hives inside the nest's $1 meters and the colony takes them over after a minute, up to $2 of them per nest - twice the speed, three times the honey, and royal jelly instead once Yagluth is down. Press honey or royal jelly on one of your own insects to heal it: $3 and $4.\n", + "rov_compendium_sverm_blister_tick_buys_slot_forever": "Blister Tick $1: buys a slot forever. It runs at what you are fighting and bursts, and the nest grows another one $2 seconds later, free.\n", + "rov_compendium_sverm_brood_eggs_nest_lays_one": "Brood Eggs: the nest lays one every $1 seconds and holds $2 of them at its first stage, one more at each stage after. Every troop costs an egg as well as biomass - the egg grows back, the biomass does not.\n", + "rov_compendium_sverm_brood_mound_hammer_nest_no": "Brood Mound (Hammer): Your nest, and no more than $1 of them may stand within $2 meters of each other. Press it, or the hive at its foot, to feed it a whole stack out of your pack: any food, any wood, any resin. Honey and royal jelly are medicine now and it will not take them.\n", + "rov_compendium_sverm_carapace_regeneration_knit_yourself_back": "[Fader Unlock] Carapace Regeneration: You knit yourself back together, $1 health a second, always.\n", + "rov_compendium_sverm_chitin_claws_hands_are_weapon": "[Base Passive] Chitin Claws: Your hands are the weapon. Bare-handed blows land at $1% of the claws' full weight, and they cannot be taken from you - draw a sword and they wait, sheathe it and they are back.\n", + "rov_compendium_sverm_chitin_plating_do_not_dress": "[Base Passive] Chitin Plating: You do not dress. Chest, legs and helm are carapace and never come off, and at every tier they are worth the full set of the biome ahead of you - at its best quality, weightless, and without the slowness that armour costs anyone else. Cloak and trinket are the only things you may still wear.\n", + "rov_compendium_sverm_colony": "\n-- THE COLONY --\n", + "rov_compendium_sverm_colony_will_not_wake_until": "The colony will not wake until the Elder falls. Until then you are a body, and the body is enough.\n", + "rov_compendium_sverm_digestion_what_feed_not_yours": "Digestion: what you feed it is not yours to spend yet. It seeps into the nest's bank at $1 a second, and only what has arrived can be spent.\n", + "rov_compendium_sverm_from_at_most": "$1 $2 (from $3, at most $4). ", + "rov_compendium_sverm_grinding_mandibles_seeds_are_food": "[Elder Unlock] Grinding Mandibles: Seeds are food. Raw nourishment and nothing more - the garden's blessings belong to somebody else.\n", + "rov_compendium_sverm_growth_each_one_costs_that": "Growth: $1 $2, $3 $4, $5 $6. Each one costs that stage's whole tankful and opens the next rung of the roster.\n", + "rov_compendium_sverm_hive_market_hammer_counter_raised": "Hive Market (Hammer): a counter raised within $1 meters of a nest. Everything the colony buys is bought here, out of that nest's bank.\n", + "rov_compendium_sverm_hive_pheromones_no_invertebrate_will": "[Base Passive] Hive Pheromones: No invertebrate will attack you - not leeches, not ticks, not deathsquitos, not seekers, not the bees. Bonemass is not an insect and does not care.\n", + "rov_compendium_sverm_insect_metabolism_eat_everything_anyone": "[Base Passive] Insect Metabolism: You eat everything anyone else eats, and honey is worth double to you. Alchemical blood is the one thing you will not swallow.\n", + "rov_compendium_sverm_metabolic_surge_running_jumping_cost": "[Eikthyr Unlock] Metabolic Surge: Running and jumping cost you less, and you jump higher.\n", + "rov_compendium_sverm_ravager_strain_key_become_seeker": "[Yagluth Unlock] Ravager Strain ('$1' Key): Become a Seeker Brute. The claws still fight, the carapace is worth double, and nothing about it flies. It is how you hold a fight, not how you leave one.\n", + "rov_compendium_sverm_seeker_workers_free_always_free": "Seeker Workers: free, and always free - no biomass, no egg, and a new one when an old one dies; $1. While they live the nest feeds itself from the chests at its foot, and they keep the forge the way a Bone Smith does: put $2 in a chest within $3 meters of the nest's edge and they carry ore and fuel from it to the smelters, kilns and mills around, then bring what comes out back to that chest. They are half a Seeker in size, in health and in bite, they take no orders and they never follow - they fight what comes near, mend what you built, and go back to work.\n", + "rov_compendium_sverm_sensory_antennae_feel_what_lives": "[Elder Unlock] Sensory Antennae: You feel what lives around you, through stone and through soil.\n", + "rov_compendium_sverm_surrenal_glands_hyperplasia_everything_hatched": "Surrenal Glands 800 and Hyperplasia 1600: everything hatched after them is born with one star, then two.\n", + "rov_compendium_sverm_surrenal_glands_stand_tenth_larger": "[Queen Unlock] Surrenal Glands: You stand a tenth larger, and the carapace takes its greatest leap.\n", + "rov_compendium_sverm_sverm_s_colony": "The Sverm's Colony\n", + "rov_compendium_sverm_title": "Sverm Secrets", + "rov_compendium_sverm_toxin_immunity_fire": "[Base Passive] Toxin Immunity: Poison cannot touch you. What can is the club and the torch: you take $1% more from blunt blows and $2% more from fire.\n", + "rov_compendium_sverm_toxin_immunity_nofire": "[Base Passive] Toxin Immunity: Poison cannot touch you. What can is the club and the torch: you take $1% more from blunt blows, and fire has stopped being a weakness.\n", + "rov_compendium_sverm_troops_they_follow_when_ask": "Troops: $1They follow when you ask, walk home when you let them go, and mend themselves.\n", + "rov_compendium_sverm_venom_glands_every_blow_land": "[Bonemass Unlock] Venom Glands: Every blow you land carries +$1 poison.\n", + "rov_compendium_sverm_ventral_pouches_carry_more": "[Eikthyr Unlock] Ventral Pouches: You carry $1 more.\n", + "rov_compendium_sverm_vestigial_wings_small_wings_no": "[Moder Unlock] Vestigial Wings: Small wings, and no ground hard enough to hurt you.\n", + "rov_compendium_sverm_workers_none": "none will come out of the nest until Bonemass falls", + "rov_compendium_sverm_workers_up_to": "up to $1 come out of the nest", + "rov_compendium_trenta_awakened_seeds_passive": "[Eikthyr Unlock] Awakened Seeds (Passive):", + "rov_compendium_trenta_closer_come_falling_harder_bark": "The closer you come to falling, the harder your bark grows: your armor rises by up to $1% as your health drops toward zero.\n", + "rov_compendium_trenta_deep_roots_passive": "[Bonemass Unlock] Deep Roots (Passive):", + "rov_compendium_trenta_every_hit_take_returns_its": "Every hit you take returns $1% of its damage to whoever landed it.\n", + "rov_compendium_trenta_every_seed_cone_acorn_self": "Every seed, cone, acorn and self-seeding mushroom you carry has woken up. Eat one on the spot and it consumes itself for the strongest meal its home biome has to offer, health or eitr as the biome favors, instead of sitting idle as planting stock.\n", + "rov_compendium_trenta_heartwood": "[Base Passive] Heartwood:", + "rov_compendium_trenta_homecoming_portal_h_key": "[Yagluth Unlock] Homecoming Portal ('H' Key):", + "rov_compendium_trenta_hornet_s_nest_passive": "[The Queen Unlock] Hornet's Nest (Passive):", + "rov_compendium_trenta_last_stand_passive": "[Moder Unlock] Last Stand (Passive):", + "rov_compendium_trenta_muspell_j_key_toggle": "[Fader Unlock] Muspell ('J' Key, toggle):", + "rov_compendium_trenta_open_linked_pair_portals_one": "Open a linked pair of portals - one where you stand, one at your respawn point - for anyone to walk through, no ore or item carried against them. They fade after $1 seconds. $2-minute cooldown.\n", + "rov_compendium_trenta_photosynthesis": "[Base Passive] Photosynthesis:", + "rov_compendium_trenta_purple_rain_g_key": "[The Elder Unlock] Purple Rain ('G' Key):", + "rov_compendium_trenta_sap_heartwood_conduct_lightning_turn": "Sap and heartwood conduct lightning and turn away the dead: you take half damage from Lightning and Spirit. But kindling burns and the woodsman's axe still bites - you take half again as much from Fire and Slash. Meat, fish, eggs and honey are nothing you can stomach; only what grows from the ground sustains you, and it does so for $1x as long as it would a normal body.\n", + "rov_compendium_trenta_secrets_heartwood": "The Secrets of the Heartwood\n", + "rov_compendium_trenta_spray_toxic_pollen_bursts_out": "A spray of toxic pollen bursts out to $1 meters: every ally caught in it is healed $2, every foe is poisoned for $3. $4-second cooldown, shortened to $5 seconds while transformed into Muspell.\n", + "rov_compendium_trenta_stand_still_daylight_roof_over": "Stand still in daylight, roof over nothing but sky, for $1 unbroken seconds, and roots take hold: $2 ticks of healing follow, $3% of your maximum health apiece, along with a Rested buff lasting $4 minutes - longer with every boss you have felled.\n", + "rov_compendium_trenta_swamp_has_nothing_left_spoil": "The swamp has nothing left to spoil in you. Poison cannot touch you, the Wet effect cannot land on you, and swimming costs no stamina at all.\n", + "rov_compendium_trenta_swarm_hornets_has_made_its": "A swarm of hornets has made its home in your branches and never leaves. Any foe that comes within $1 meters is stung for $2 poison and pierce damage every $3 seconds until it breaks off or falls.\n", + "rov_compendium_trenta_take_shape_young_elder_root": "Take the shape of a young Elder, root and bramble given fury. Left Mouse stomps the ground for $1 damage in a ring around you, Right Mouse looses a root-spike that pierces for $2 - both rising with your Unarmed skill. Purple Rain still answers your call while transformed, on its shorter cooldown.\n", + "rov_compendium_trenta_thorns_passive": "[Moder Unlock] Thorns (Passive):", + "rov_compendium_trenta_title": "Trenta Secrets", + "rov_compendium_trol_base_passive_are_natively_larger": "Base Passive: You are natively 20% larger than a human with immense strength. You have +200 Max Carry Weight, gain +3 Armor per boss defeated, and carry a 4th food slot from your very first meal - no boss required.\n", + "rov_compendium_trol_base_passive_black_forest_kin": "Base Passive: Black Forest kin. Greydwarves, Fulings and Trolls have no quarrel with you and will not open a fight - though hitting one still buys you the answer you asked for.\n", + "rov_compendium_trol_base_weakness_kindling_fire_finds": "Base Weakness - Kindling: Fire finds you where nothing else does. Every burn you take lands for $1% more than it would on anyone else, and no armor or resistance changes that.\n", + "rov_compendium_trol_bonemass_defeated_size_carry_weight": "Bonemass Defeated: +5% Size, +50 Carry Weight, +10 Damage to Clubs/Unarmed/Axes, +10 Rock Throwing Damage.\n", + "rov_compendium_trol_eikthyr_defeated_increased_xp_gain": "Eikthyr Defeated: Increased XP gain for physical labor and blunt combat (Clubs, Unarmed, Axes, Pickaxes, WoodCutting).\n", + "rov_compendium_trol_elder_defeated_unlocked_rock_throwing": "The Elder Defeated: Unlocked Rock Throwing ability. +10% passive health regeneration.\n", + "rov_compendium_trol_fader_defeated_wielded_trees_can": "Fader Defeated: Your wielded trees can now instantly smash through the toughest materials in the Ashlands. True Form no longer runs out and has no cooldown - press the key again to return to your normal size.\n", + "rov_compendium_trol_moder_defeated_unlocked_true_form": "Moder Defeated: Unlocked True Form (Transformation ability).\n", + "rov_compendium_trol_queen_defeated_unlocked_log_weapon": "The Queen Defeated: Unlocked Log Weapon (in True Form, interact with trees to wield them as weapons). True Form size is massively increased.\n", + "rov_compendium_trol_title": "Trol Secrets", + "rov_compendium_trol_trol_s_heritage": "The Trol's Heritage\n", + "rov_compendium_trol_yagluth_defeated_size_carry_weight": "Yagluth Defeated: +5% Size, +50 Carry Weight, +5 Damage to Clubs/Unarmed/Axes, +5 Rock Throwing Damage. Unlocked 5th Food Slot.\n", + "rov_compendium_warvulture_goes_where_look_goes_as": "It goes where you look, and it goes as long as you care to stay up: $1 meters a second costs it nothing at all. Hold your run key and it gives you $2 for $3 seconds and not a moment longer - there is only so much haste in a bird. Let go and the wind comes back into it in $4 seconds, in the air. You never have to land for it.\n", + "rov_compendium_warvulture_vulture_s_head_kept_stick": "A vulture's head kept on a stick, and the bird answers to it. Raise it and the vulture comes back under you. Raise it again and it carries you down, deaf to you until the ground arrives - and a third time lets go of it where you are.\n", + "rov_compendium_warvulture_war_vulture": "\n-- THE WAR VULTURE --\n", + "rov_compendium_warvulture_what_bird_has_left_bar": "What the bird has left is the bar under your own.\n" +} diff --git a/JotunnModStub/Translations/Russian/hover.json b/JotunnModStub/Translations/Russian/hover.json new file mode 100644 index 0000000..968461e --- /dev/null +++ b/JotunnModStub/Translations/Russian/hover.json @@ -0,0 +1,56 @@ +{ + "rov_hover_aswid_dominate": "[$KEY_Use] Dominate", + "rov_hover_aswid_dominate_cooldown_m": "[$KEY_Use] Dominate (Cooldown: $1m)", + "rov_hover_aswid_follow": "[$KEY_Use] Follow", + "rov_hover_aswid_stay": "[$KEY_Use] Stay", + "rov_hover_aswid_tame": "\n[$1] Tame", + "rov_hover_butler_no_servant_stands_here_raise": "$1\nNo servant stands here.\n[$KEY_Use] Raise one", + "rov_hover_butler_waiting": "Waiting.", + "rov_hover_draugh_feed_flesh_or_draugr_s": "\n[$KEY_Use] Feed it flesh, or a draugr's head", + "rov_hover_draugh_flesh_risen_waiting": "flesh $1/$2, risen $3/$4, waiting $5/$6", + "rov_hover_draugh_next_rises_s": "\nnext rises in $1s", + "rov_hover_draugh_officers_waiting": "\nofficers $1/$2, waiting $3/$4", + "rov_hover_dvergar_at_barrel_pour_round": "$1 $2/$3\n$4 at the barrel\n[$KEY_Use] Pour a round", + "rov_hover_dvergar_contracts": "contracts $1/$2", + "rov_hover_dvergar_empty_pour_brew": "empty\n[$KEY_Use] Pour a brew in", + "rov_hover_dvergar_read_ledger": "\n[$KEY_Use] Read the ledger", + "rov_hover_dvergar_seal_worth_off": "\nyour seal is worth $1% off", + "rov_hover_dvergar_what_queen_left_behind_buys": "\n(what the Queen left behind buys two more crews)", + "rov_hover_fenrir_blood_thin_here_raises_no": "\nthe blood is thin here - it raises no fenrir yet", + "rov_hover_fenrir_fenrir": ", fenrir $1/$2", + "rov_hover_fenrir_fill_with_meat": "\n[$KEY_Use] Fill it with meat", + "rov_hover_fenrir_meat_wolves_ulv": "meat $1/$2\nwolves $3/$4, ulv $5/$6", + "rov_hover_fenrir_next_s": "\nnext in $1s", + "rov_hover_fenrir_not_enough_meat_next_one": "\nnot enough meat for the next one ($1 needed)", + "rov_hover_fenrir_pack_whole": "\nthe pack is whole", + "rov_hover_skeleton_bone_hand_buy_place_empty": "\n[$KEY_Use] Bone in hand to buy a place, empty hands to move the line", + "rov_hover_skeleton_bone_toward_next_places": "\nbone $1/$2 toward the next of $3 places", + "rov_hover_skeleton_every_place_bought": "\nevery place is bought", + "rov_hover_skeleton_melee_archers_rotten": "\nmelee $1/$2 of $3\narchers $4/$5 of $6\nrotten $7/$8 of $9", + "rov_hover_skeleton_needs_greater_cursed_skull": " (needs a Greater Cursed Skull)", + "rov_hover_skeleton_next_rises_s": "\nnext rises in $1s", + "rov_hover_sverm_beehives_taken_allowed_range_feed": "$1\n$2Beehives $3 taken of $4 allowed, $5 in range\n$6[$KEY_Use] Feed it a stack", + "rov_hover_sverm_market_no_hive": "$1\nNo hive within $2 metres.", + "rov_hover_sverm_msg": "$1\n$2[$KEY_Use] $3", + "rov_hover_sverm_stomach_prompt": "Feed it a stack", + "rov_hover_sverm_stomach_title": "Hive Stomach", + "rov_hover_sverm_tank": "Biomass $1 / $2\nDigesting $3\nBrood eggs $4 / $5\n", + "rov_hover_sverm_trade_with_hive": "$1\n$2[$KEY_Use] Trade with the hive", + "rov_hover_trenta_flesh_feed_raw_flesh": "flesh $1/$2\n[$KEY_Use] Feed it raw flesh", + "rov_hover_trenta_grove_growing": "$1 (growing, $2 minutes left)", + "rov_hover_trenta_grove_grown": "$1 ($2 $3/$4, honey $5)\n[$KEY_Use] Feed it Fertilizer", + "rov_hover_trenta_honey_full": "$1, full", + "rov_hover_trenta_honey_next": "$1, next in $2 min", + "rov_hover_trenta_honey_none": "none (no honey item found)", + "rov_hover_trenta_ready_empty": "ready: $1 $2\n[$KEY_Use] Empty it", + "rov_hover_trenta_rotting_minutes_left": "rotting, $1 minutes left", + "rov_hover_trol_call_warbands": "\n[$KEY_Use] Call the warbands", + "rov_hover_trol_grab_log": "\n[$1] Grab Log", + "rov_hover_trol_warbands": "warbands $1/$2", + "rov_hover_trol_yagluth_drop_hand_buys_king": "\n(a Yagluth drop in hand buys a king's head, and two more bands)", + "rov_hover_ward_personal": "Personal", + "rov_hover_ward_race_menu_ward_progression_open": "$rov_piece_racemenuward_name\n$1 progression - $2 ($3/$4)\n[$KEY_Use] Open\n[Use item] Offer a boss relic", + "rov_hover_ward_world": "World", + "rov_hover_boneship_roster": "\nmelee $1/$2 of $3\narchers $4/$5 of $6\naboard $7", + "rov_hover_boneship_bone_hand": "\nbone in hand to buy a place" +} diff --git a/JotunnModStub/Translations/Russian/items.json b/JotunnModStub/Translations/Russian/items.json new file mode 100644 index 0000000..a58cd84 --- /dev/null +++ b/JotunnModStub/Translations/Russian/items.json @@ -0,0 +1,138 @@ +{ + "rov_creature_bonecook_name": "Bone Cook", + "rov_creature_bonesmith_name": "Bone Smith", + "rov_creature_draugh_thrall_name": "Draugr Thrall", + "rov_creature_draugh_thrallelite_name": "Draugr Elite Thrall", + "rov_creature_fenrir_pack_desc": "It answers to the blood of the wolf, not to you.", + "rov_creature_fenrir_packfenrir_desc": "Only the blood of the wolf commands this one.", + "rov_creature_fenrir_packfenrir_name": "Fenrir", + "rov_creature_fenrir_packulv_name": "Ulv", + "rov_creature_fenrir_packwolf_name": "Pack Wolf", + "rov_creature_skadi_crystalgolem_name": "Crystal Golem", + "rov_creature_skeleton_sentry_name": "Bound Sentry", + "rov_creature_skeleton_thrallmelee_name": "Bound Skeleton", + "rov_creature_skeleton_thrallrancid_name": "Bound Rancid Remains", + "rov_creature_skeleton_thrallranged_name": "Bound Archer", + "rov_creature_sverm_blistertick_name": "Blister Tick", + "rov_creature_sverm_worker_name": "Seeker Worker", + "rov_item_aswid_bloodcore_desc": "A knot of clotted blood kept beating by something that is not a heart. The dead trade them; only the dead know how they are made.", + "rov_item_aswid_bloodcore_name": "Blood Core", + "rov_item_aswid_bloodessence_desc": "Blood rendered down to what it actually is. The only real food an Aswid can still chew, and the base of every draught worth brewing.", + "rov_item_aswid_bloodessence_name": "Blood Essence", + "rov_item_aswid_bloodpotion_desc": "Drink and the hunger stops mattering for a while. Fills every stomach with blood essence, full or not, and knits the flesh back together.", + "rov_item_aswid_bloodpotion_name": "Blood Potion", + "rov_item_aswid_bloodpotionbase_desc": "Blood, berries and crypt light, waiting on a barrel.", + "rov_item_aswid_bloodpotionbase_name": "Blood Potion Mead Base", + "rov_item_aswid_claws_desc": "Grown in the dark, and darker for it. They do not come off.", + "rov_item_aswid_claws_name": "Claws of the Beast", + "rov_item_aswid_food_desc": "The life force of the conquered.", + "rov_item_aswid_food_name": "Aswid Food:", + "rov_item_aswid_spectralclaw_desc": "A claw of pure shadow, bound to your rage rather than your grip.", + "rov_item_aswid_spectralclaw_name": "Spectral Claw", + "rov_item_aswid_superiorbloodessence_desc": "The same blood, rendered twice. Darker, thicker, and worth five of the first pass.", + "rov_item_aswid_superiorbloodessence_name": "Superior Blood Essence", + "rov_item_aswid_superiorbloodpotion_desc": "The same mercy, twice as deep.", + "rov_item_aswid_superiorbloodpotion_name": "Superior Blood Potion", + "rov_item_aswid_superiorbloodpotionbase_desc": "The twice-rendered draught, still raw.", + "rov_item_aswid_superiorbloodpotionbase_name": "Superior Blood Potion Mead Base", + "rov_item_draugh_cursedbone_desc": "A bone that will not stay quiet. The dead sell them; the dead do not say why.", + "rov_item_draugh_cursedbone_name": "Cursed Bone", + "rov_item_draugh_greatercursedbone_desc": "The same bone, older, and louder. A pile fed one of these starts keeping officers.", + "rov_item_draugh_greatercursedbone_name": "Greater Cursed Bone", + "rov_item_draugh_humanmeat_desc": "A piece of somebody. The living gag on it; you do not.", + "rov_item_draugh_humanmeat_name": "Human Meat", + "rov_item_fenrir_claws_desc": "The wolf's hands, kept on in the man's shape. They do not come off.", + "rov_item_fenrir_claws_name": "Cursed Claws", + "rov_item_fenrir_greaterulvsblod_desc": "Older blood, and further down the line. A trough given one of these starts raising something worse than ulv.", + "rov_item_fenrir_greaterulvsblod_name": "Greater Ulvsblod", + "rov_item_fenrir_ulvsblod_desc": "Wolf blood, kept warm by something that should not be able to keep anything warm. The Fenring sell it and do not explain it.", + "rov_item_fenrir_ulvsblod_name": "Ulvsblod", + "rov_item_furling_copperdust_desc": "A sack of copper ground fine. A furnace cannot tell it from ore, and it will not go through a portal either.", + "rov_item_furling_copperdust_name": "Copper Dust", + "rov_item_furling_copperflax_desc": "Flax grown in copper-poisoned soil, and it took. Useless as cloth. Grind it and see.", + "rov_item_furling_copperflax_name": "Copper Flax", + "rov_item_furling_flintberry_desc": "Not a berry, whatever it looks like. Bury one and a flint-bearing bush comes up.", + "rov_item_furling_flintberry_name": "Flintberry", + "rov_item_furling_irondust_desc": "A sack of iron ground fine. A furnace cannot tell it from ore, and it will not go through a portal either.", + "rov_item_furling_irondust_name": "Iron Dust", + "rov_item_furling_ironflax_desc": "Flax grown in iron-poisoned soil, and it took. Useless as cloth. Grind it and see.", + "rov_item_furling_ironflax_name": "Iron Flax", + "rov_item_furling_stoneberry_desc": "Not a berry, whatever it looks like. Bury one and a stone-bearing bush comes up.", + "rov_item_furling_stoneberry_name": "Stoneberry", + "rov_item_furling_tindust_desc": "A sack of tin ground fine. A furnace cannot tell it from ore, and it will not go through a portal either.", + "rov_item_furling_tindust_name": "Tin Dust", + "rov_item_furling_tinflax_desc": "Flax grown in tin-poisoned soil, and it took. Useless as cloth. Grind it and see.", + "rov_item_furling_tinflax_name": "Tin Flax", + "rov_item_skadi_greaterfrostheart_desc": "Older cold than the mountain's. The cultists sell it and will not say where they dig.", + "rov_item_skadi_greaterfrostheart_name": "Greater Frost Heart", + "rov_item_skeleton_cursedskull_desc": "A skull that keeps counting. Set it down and the ground starts answering.", + "rov_item_skeleton_cursedskull_name": "Cursed Skull", + "rov_item_skeleton_greatercursedskull_desc": "Older, and it counts higher. A pile given one of these raises the rotten too.", + "rov_item_skeleton_greatercursedskull_name": "Greater Cursed Skull", + "rov_item_skeleton_soulstone_desc": "Something is still in there, and it is still angry. Bind it to a skull and it will stand watch as long as the bones hold.", + "rov_item_skeleton_soulstone_name": "Soul Stone", + "rov_item_sverm_claws_desc": "Grown, not forged. They do not come off.", + "rov_item_sverm_claws_name": "Chitin Claws", + "rov_item_trenta_fertilizer_desc": "Everything that was meat, a month later. Press it into the soil and whatever is rooted there stops waiting.", + "rov_item_trenta_fertilizer_name": "Fertilizer", + "rov_item_trenta_heartwoodseed_desc": "A seed fed on a whole barrel of rot. Plant it and go away for a while.", + "rov_item_trenta_heartwoodseed_name": "Heartwood Seed", + "rov_item_trenta_rotseed_desc": "A seed that died before it could sprout, and did not stop. The forest folk sell them; only the forest knows what grows from one.", + "rov_item_trenta_rotseed_name": "Rot Seed", + "rov_item_trol_giantslog_desc": "A massive tree log wielded as a weapon.", + "rov_item_trol_giantslog_name": "Giant's Log", + "rov_item_trolshammer_desc": "A hammer swung by something that never had to duck through a doorway. It builds everything the ordinary one builds, out of the same materials, and simply builds it bigger.", + "rov_item_trolshammer_name": "Trol's Hammer", + "rov_item_warvulture_desc": "A vulture's head, kept. Raise it and the bird comes back under you, and it will carry you as long as you care to stay up - though it only has so much haste in it before it settles into a glide.", + "rov_item_warvulture_name": "War Vulture", + "rov_piece_aswid_bloodrefinery_desc": "Flesh goes in, bone goes in, and what is left of both comes out red.", + "rov_piece_aswid_bloodrefinery_name": "Blood Refinery", + "rov_piece_cooktable_desc": "A slab of bone and slate, worn smooth. Something patient waits by the hearth.", + "rov_piece_cooktable_name": "Cook's Table", + "rov_piece_draugh_bodypile_desc": "Feed it and it answers. The dead here are yours, if you are dead enough to ask.", + "rov_piece_draugh_bodypile_name": "Cursed Body Pile", + "rov_piece_dvergar_contractbank_desc": "A ledger, a seal and a heap of coin. Sign here and someone else does the dying.", + "rov_piece_dvergar_contractbank_name": "Contract Bank", + "rov_piece_dvergar_runebarrel_desc": "Pour a brew in and the crew drinks. What it does to them is whatever it would have done to you - if they have the parts for it.", + "rov_piece_dvergar_runebarrel_name": "Rune Barrel", + "rov_piece_fenrir_packtrough_desc": "Fill it with meat and the pack comes. One at a time, and it remembers its dead.", + "rov_piece_fenrir_packtrough_name": "Pack Trough", + "rov_piece_furling_copperflaxsapling_desc": "Plant it and it grows more Copper Flax.", + "rov_piece_furling_copperflaxsapling_name": "Copper Flax", + "rov_piece_furling_flintberrybush_desc": "Yields flint, and keeps yielding it.", + "rov_piece_furling_flintberrybush_name": "Flintberry Bush", + "rov_piece_furling_ironflaxsapling_desc": "Plant it and it grows more Iron Flax.", + "rov_piece_furling_ironflaxsapling_name": "Iron Flax", + "rov_piece_furling_stoneberrybush_desc": "Yields stone, and keeps yielding it.", + "rov_piece_furling_stoneberrybush_name": "Stoneberry Bush", + "rov_piece_furling_tinflaxsapling_desc": "Plant it and it grows more Tin Flax.", + "rov_piece_furling_tinflaxsapling_name": "Tin Flax", + "rov_piece_racemenuward_desc": "Commune with your heritage. Offer a fallen boss's relic to claim its power.", + "rov_piece_racemenuward_name": "Race Menu Ward", + "rov_piece_skadi_crystalgolem_desc": "Cut at the stone and woken with a tear. It will not follow you, and it will not leave the stonecutter that shaped it.", + "rov_piece_skeleton_bonepile_desc": "Twenty fragments buy a place in the line. The one who fills it will keep standing up.", + "rov_piece_skeleton_bonepile_name": "Bound Bone Pile", + "rov_piece_skeleton_sentry_desc": "A skull on a soul stone. It will not walk, and it will not stop watching.", + "rov_piece_smithtable_desc": "A slab of bone and slate, dusted with ore. Something patient waits by the fires.", + "rov_piece_smithtable_name": "Smith's Table", + "rov_piece_sverm_broodmound_desc": "The colony begins here. Everything else grows out of it.", + "rov_piece_sverm_broodmound_name": "Brood Mound", + "rov_piece_sverm_hivemarket_desc": "Where the colony trades. It spends the tank of the nest it stands in.", + "rov_piece_sverm_hivemarket_name": "Hive Market", + "rov_piece_trenta_composter_desc": "What rots is not lost. It feeds.", + "rov_piece_trenta_composter_name": "Composter", + "rov_piece_trenta_elderroot_desc": "What the Elder left behind, still growing. Mends itself, and everything a player built close enough to it.", + "rov_piece_trenta_elderroot_name": "Root of the Elder", + "rov_piece_trenta_heartwoodgrove_desc": "A crate of rot with something growing out of it. Give it time.", + "rov_piece_trenta_heartwoodgrove_name": "Heartwood Grove", + "rov_piece_trenta_heartwoodsapling_name": "Heartwood Sapling", + "rov_piece_trol_wartotem_desc": "A head that still remembers how to shout. Coin goes in, a warband walks out.", + "rov_piece_trol_wartotem_name": "War Totem", + "rov_piece_boneship_altar_name": "Offering Chest", + "rov_piece_boneship_ashlands_desc": "A warship that burned and kept going, ribbed with bone. The oarsmen do not tire.", + "rov_piece_boneship_ashlands_name": "Ashen Bone Longship", + "rov_piece_boneship_karve_desc": "A Karve gone to rot, ribbed with bone. It was not built to sail on wind.", + "rov_piece_boneship_karve_name": "Bone Karve", + "rov_piece_boneship_longship_desc": "A longship gone to rot, ribbed with bone. It sails against any wind.", + "rov_piece_boneship_longship_name": "Bone Longship" +} diff --git a/JotunnModStub/Translations/Russian/merchants.json b/JotunnModStub/Translations/Russian/merchants.json new file mode 100644 index 0000000..3b40204 --- /dev/null +++ b/JotunnModStub/Translations/Russian/merchants.json @@ -0,0 +1,133 @@ +{ + "rov_joke_fantasma_01": "Why was the ghost lonely? It had no-body.", + "rov_joke_fantasma_02": "What's the most useless room in a house for a ghost? A living room.", + "rov_joke_fantasma_03": "What's a ghost's favourite cheese? Ghoul-da cheese.", + "rov_joke_fantasma_04": "What's a ghost's favourite food? Boo-rritos.", + "rov_joke_fantasma_05": "What's a ghost's favourite dessert? I-scream.", + "rov_joke_fantasma_06": "What's a ghost's favourite game? Hide and Shriek.", + "rov_joke_fantasma_07": "What do you call a ghost with a broken leg? A hoblin goblin.", + "rov_joke_fantasma_08": "What happens when a ghost gets lost in the fog? He is mist.", + "rov_joke_fantasma_09": "Ghosts love elevators because it lifts their spirits.", + "rov_joke_fantasma_10": "Why did the ghost cross the road? Because it was a poultry-geist.", + "rov_joke_goblin_01": "Those goblin fingers are dexter-gnome-us.", + "rov_joke_goblin_02": "Why did the goblin break the vase? He wanted to smash expectations.", + "rov_joke_goblin_03": "That goblin really gnome-napped my sandwich.", + "rov_joke_goblin_04": "Just goblin around.", + "rov_joke_goblin_05": "They love orc-strating trouble.", + "rov_joke_goblin_06": "If a goblin smiles at you, check your pockets.", + "rov_joke_goblin_07": "Why don't goblins shower? They prefer natural grime.", + "rov_joke_goblin_08": "What's a goblin's favorite sport? Lootball.", + "rov_joke_goblin_09": "How do goblins shop? Five-finger discount only.", + "rov_joke_goblin_10": "What's a goblin's password? 'MineMineMine!'", + "rov_joke_legnofalegname_01": "Carpenters nail it every time: that's their true calling.", + "rov_joke_legnofalegname_02": "I told my saw a joke: it couldn't handle the cut.", + "rov_joke_legnofalegname_03": "I dated a carpenter once: it was a solid relationship.", + "rov_joke_legnofalegname_04": "Carpenters have great timing: they always measure up.", + "rov_joke_legnofalegname_05": "My friend builds furniture: he really wood make you laugh.", + "rov_joke_legnofalegname_06": "A good carpenter never quits: he just saws what he started.", + "rov_joke_legnofalegname_07": "I asked the wood if it was okay: it said, 'I'm board.'", + "rov_joke_legnofalegname_08": "I made a joke about a piece of wood, but it was too plane.", + "rov_joke_legnofalegname_09": "How do trees access the internet? They just log on!", + "rov_joke_legnofalegname_10": "Why did the plank cross the road? To get to the other siding!", + "rov_joke_lupolicantropo_01": "Why did the werewolf laugh while chewing on the skeleton? He got to the funny bone.", + "rov_joke_lupolicantropo_02": "Why did the werewolf need to talk with the skeleton? He had a bone to pick with him.", + "rov_joke_lupolicantropo_03": "A what-to-wear-wolf.", + "rov_joke_lupolicantropo_04": "My werewolf skills are claw-some.", + "rov_joke_lupolicantropo_05": "'Howl'-oween, hands down - a werewolf's favorite holiday.", + "rov_joke_lupolicantropo_06": "Why don't werewolves use cell phones? Because they prefer to roam.", + "rov_joke_lupolicantropo_07": "Why did the werewolf sit in the corner? He didn't want to be spotted.", + "rov_joke_lupolicantropo_08": "Why don't werewolves gossip? They can't keep a straight paw.", + "rov_joke_lupolicantropo_09": "You're fur-ociously awesome.", + "rov_joke_lupolicantropo_10": "Howl you doin' tonight?", + "rov_joke_nano_01": "A dwarf who loved gardening had a real green thumbelina.", + "rov_joke_nano_02": "Dwarves make excellent bakers; their scone courses are always the shortest.", + "rov_joke_nano_03": "Why do dwarfs make great secret agents? They can really keep things low-key.", + "rov_joke_nano_04": "A dwarf walks into a bar and hits his head - the bar was set too low.", + "rov_joke_nano_05": "Why are dwarfs so good at math? Because it's the little things that count.", + "rov_joke_nano_06": "I saw a dwarf climbing down a prison wall - it was a little condescending.", + "rov_joke_nano_07": "What do dwarfs use to fight trolls? Short swords.", + "rov_joke_nano_08": "What's a dwarf warrior's motto? Small but deadly.", + "rov_joke_nano_09": "A dwarf opened a bakery because he kneaded dough at his level.", + "rov_joke_nano_10": "What do you call a dwarf who can be invisible? A short circuit!", + "rov_joke_nonmortozombie_01": "When do zombies go to sleep? When they are dead tired.", + "rov_joke_nonmortozombie_02": "What streets do zombies live on? Dead ends.", + "rov_joke_nonmortozombie_03": "Where do zombies go sailing? Lake Eerie.", + "rov_joke_nonmortozombie_04": "What do you call a zombie in pajamas? The sleepwalking dead.", + "rov_joke_nonmortozombie_05": "How are zombies like computers? They use mega-bites!", + "rov_joke_nonmortozombie_06": "Why did the zombie lose his lawsuit? He had no leg to stand on!", + "rov_joke_nonmortozombie_07": "Why did the zombie eat a light bulb? Because he wanted a light snack.", + "rov_joke_nonmortozombie_08": "Why don't zombies eat clowns? Because they taste funny!", + "rov_joke_nonmortozombie_09": "Why did the zombie go to school? To improve his brainpower.", + "rov_joke_nonmortozombie_10": "Zombies are hopeless romantics, seeking their ghoul-mate.", + "rov_joke_scheletro_01": "What do you call a skeleton who never does his chores? Lazy bones.", + "rov_joke_scheletro_02": "Why did the skeleton quit his job? His heart wasn't in it.", + "rov_joke_scheletro_03": "What skeleton was the first emperor of France? Napoleon Bone-aparte.", + "rov_joke_scheletro_04": "Who is the world's most famous skeleton detective? Sherlock Bones.", + "rov_joke_scheletro_05": "What did the French skeletons say before eating their dinner? Bone appetit!", + "rov_joke_scheletro_06": "What do skeletons always order when they go to a restaurant? Spare ribs.", + "rov_joke_scheletro_07": "How do skeletons call each other? On their tele-bone.", + "rov_joke_scheletro_08": "What's a skeleton's favorite fruit? Bone-ana!", + "rov_joke_scheletro_09": "Why are skeletons bad at lying? You can see right through them!", + "rov_joke_scheletro_10": "Why don't skeletons fight each other? They don't have the guts.", + "rov_joke_strega_01": "Resting witch face.", + "rov_joke_strega_02": "Hag a nice day.", + "rov_joke_strega_03": "What do you call a mage in the desert? A sand-witch.", + "rov_joke_strega_04": "What happens to witches who break the rules at school? They get ex-spelled.", + "rov_joke_strega_05": "What do witches put in their hair? Scare spray.", + "rov_joke_strega_06": "Why did three witches call in the plumber? Hubble, bubble, toilet trouble.", + "rov_joke_strega_07": "Why couldn't the little witch read her spellbook? It was written in curse-ive.", + "rov_joke_strega_08": "Why did the witch become a lawyer? She wanted to practice witchcraft.", + "rov_joke_strega_09": "Witches don't fart. They cast smells.", + "rov_joke_strega_10": "A witch tells the time by looking at her witch watch.", + "rov_joke_troll_01": "Why do trolls love bridges? They're always crossing into new territory.", + "rov_joke_troll_02": "Why did the troll get a bad grade? He was always under the bridge of understanding.", + "rov_joke_troll_03": "Trolls don't watch TV - they stream mischief.", + "rov_joke_troll_04": "Trolls love parties - they bring the bridge snacks.", + "rov_joke_troll_05": "Trolls hate Mondays - they bridge the gap to Friday.", + "rov_joke_troll_06": "Where do trolls keep their money? Under the bridge, of course.", + "rov_joke_troll_07": "What's a troll's favorite candy? Bridge bars.", + "rov_joke_troll_08": "Why did the troll go to school? To bridge the knowledge gap.", + "rov_joke_troll_09": "What's a troll's favorite movie? The Bridge Runner.", + "rov_joke_troll_10": "What makes a troll laugh? Someone taking it seriously.", + "rov_merchant_buy": "Deal.", + "rov_merchant_dverg_name": "Dverg", + "rov_merchant_sell": "Thanks.", + "rov_merchant_start_trade": "What do you need?", + "rov_sverm_good_glands_desc": "Every troop hatched from now on is born with one star.\n\nIt does nothing for the ones already walking around: what is born is born.", + "rov_sverm_good_glands_name": "Surrenal Glands", + "rov_sverm_good_hyperplasia_desc": "Every troop hatched from now on is born with two stars.\n\nThe colony has to have grown the glands first.", + "rov_sverm_good_hyperplasia_name": "Hyperplasia", + "rov_sverm_good_stage_desc": "Grows the nest into a $1: it holds $2 biomass instead of $3, and stands half again as tall.\n\nIt costs this stage's whole tankful, so it leaves the hive all but empty. Grow or field an army - never both in the same breath.", + "rov_sverm_good_tick_desc": "Buys a PERMANENT slot in the colony. What stands in it runs at whatever the colony is fighting and bursts, and thirty seconds later the nest grows another one - no egg, no biomass, forever.\n\nThe blast spares you, your tames and the rest of the colony.", + "rov_sverm_good_troop_desc": "Hatches a $1, bound to this nest: it follows when you ask, walks home when you let it go, and mends itself.\n\nCosts one brood egg as well as the biomass. At most $2 of them alive at once.", + "rov_sverm_refusal_already_breeds": "The colony already breeds like this.", + "rov_sverm_refusal_grown_past": "Already grown past this.", + "rov_sverm_refusal_keeping": "The colony is already keeping $1 of them.", + "rov_sverm_refusal_keeps": "The colony already keeps $1 of them.", + "rov_sverm_refusal_no_egg": "No brood egg ready.", + "rov_sverm_refusal_no_hive": "No hive.", + "rov_sverm_refusal_one_star": "One star at a time.", + "rov_sverm_refusal_stage_first": "The nest has to be a $1 first.", + "rov_sverm_refusal_working_m": "The hive is still working on the last one ($1m).", + "rov_sverm_refusal_working_s": "The hive is still working on the last one ($1s).", + "rov_sverm_stage_gorgedhive": "Gorged Hive", + "rov_sverm_stage_hivecitadel": "Hive Citadel", + "rov_sverm_stage_nestingspire": "Nesting Spire", + "rov_troop_dvergar_ash_guard": "Ash Guard", + "rov_troop_dvergar_escort": "Escort", + "rov_troop_dvergar_fire_crew": "Fire Crew", + "rov_troop_dvergar_runic_crew": "Runic Crew", + "rov_troop_dvergar_seal_price": "List price $1 - your seal takes it to $2.", + "rov_troop_dvergar_terms": "They answer the follow command, knit their own wounds shut, keep your truce with the mountain's dvergr, drop nothing, and do not come back. A dead crew is money spent.", + "rov_troop_dvergar_yard_patrol": "Yard Patrol", + "rov_troop_sverm_brood": "Brood", + "rov_troop_sverm_gjall": "Gjall", + "rov_troop_sverm_seeker": "Seeker", + "rov_troop_sverm_soldier": "Soldier", + "rov_troop_trol_goblin_band": "Fuling War Band", + "rov_troop_trol_goblin_patrol": "Fuling Patrol", + "rov_troop_trol_greydwarf_patrol": "Greydwarf Patrol", + "rov_troop_trol_terms": "They answer the follow command, knit their own wounds shut, drop nothing, and do not come back. A dead warband is money spent.", + "rov_troop_trol_troll": "Troll", + "rov_troop_trol_troll_summoned": "Staff Troll" +} diff --git a/JotunnModStub/Translations/Russian/messages.json b/JotunnModStub/Translations/Russian/messages.json new file mode 100644 index 0000000..6e6ee1e --- /dev/null +++ b/JotunnModStub/Translations/Russian/messages.json @@ -0,0 +1,205 @@ +{ + "rov_msg_aswid_aura_disabled": "Vampiric Aura: DISABLED", + "rov_msg_aswid_aura_enabled": "Vampiric Aura: ENABLED", + "rov_msg_aswid_dominate_cooldown_m_s": "Dominate on cooldown ($1m $2s)", + "rov_msg_aswid_dominated": "$1 dominated!", + "rov_msg_aswid_eclipse_cooldown_remaining_s": "Eclipse is on cooldown. Remaining: $1s", + "rov_msg_aswid_eclipse_descends": "An Eclipse descends...", + "rov_msg_aswid_eclipse_has_ended": "The Eclipse has ended.", + "rov_msg_aswid_following": "$1 is following.", + "rov_msg_aswid_living_blood_curdles_living_throat": "Living blood curdles in a living throat.", + "rov_msg_aswid_morning_sun_drives_bat_back": "The morning sun drives the bat back into your body", + "rov_msg_aswid_morning_sun_has_vanquished_horrible": "The morning sun has vanquished the horrible night", + "rov_msg_aswid_no_bone_grind": "No bone to grind.", + "rov_msg_aswid_no_raw_flesh_render": "No raw flesh to render.", + "rov_msg_aswid_staying": "$1 is staying.", + "rov_msg_aswid_sun_burns_can_only_take": "The sun burns. You can only take bat form at night.", + "rov_msg_aswid_tamed": "Tamed!", + "rov_msg_aswid_vae_victis": "Vae Victis", + "rov_msg_aswid_what_horrible_night_have_curse": "what a horrible night to have a curse", + "rov_msg_build_limit_cooktable": "Another cook's table stands within forty paces. One cook to a yard.", + "rov_msg_build_limit_draugh_bodypile": "The ground here already carries $1 of these. Find another country.", + "rov_msg_build_limit_dvergar_contractbank": "There is already $1 contract bank within a day's walk. One ledger per valley.", + "rov_msg_build_limit_fenrir_packtrough": "There is already $1 of these within a day's walk. A pack needs room.", + "rov_msg_build_limit_skeleton_bonepile": "There are already $1 of these listening nearby. Take it further out.", + "rov_msg_build_limit_smithtable": "Another smith's table stands within forty paces. One smith to a yard.", + "rov_msg_build_limit_sverm_hive": "There is already a hive holding this ground.", + "rov_msg_build_limit_sverm_market": "This hive already has a market.", + "rov_msg_build_limit_trenta_grove": "This country already answers to $1 of these. Plant it somewhere else.", + "rov_msg_build_this_cave_will_hold_what": "This cave will hold what you build in it.", + "rov_msg_butler_already_at_work": "It is already at work.", + "rov_msg_butler_bones_are_not_ready_s": "The bones are not ready. $1s.", + "rov_msg_butler_bones_do_not_answer_blood": "The bones do not answer to your blood.", + "rov_msg_butler_nothing_answers": "Nothing answers.", + "rov_msg_butler_only_skadi_s_hearth_kept": "Only Skadi's hearth is kept by the dead.", + "rov_msg_butler_servant_rises": "The servant rises.", + "rov_msg_claws_they_are_part_hands": "They are part of your hands.", + "rov_msg_core_chose_path_aswid": "You chose the path of the Aswid.", + "rov_msg_core_chose_path_draugh": "You chose the path of the Draugh.", + "rov_msg_core_chose_path_dvergar": "You chose the path of the Dvergar.", + "rov_msg_core_chose_path_fenrir": "You chose the path of the Fenrir.", + "rov_msg_core_chose_path_furling": "You chose the path of the Furling.", + "rov_msg_core_chose_path_skadi": "You chose the path of Skadi.", + "rov_msg_core_chose_path_skeleton": "You chose the path of the Skeleton.", + "rov_msg_core_chose_path_sverm": "You chose the path of the Sverm.", + "rov_msg_core_chose_path_trenta": "You chose the path of the Trenta.", + "rov_msg_core_chose_path_trol": "You chose the path of the Trol.", + "rov_msg_core_chose_remain_human": "You chose to remain Human.", + "rov_msg_core_debug_override_cleared": "Debug override cleared.", + "rov_msg_core_nothing_reset_personal": "Nothing to reset - you have claimed no relics yet ($1/$2).", + "rov_msg_core_nothing_reset_world": "Nothing to reset - you follow the world's progression: $1 ($2/$3).", + "rov_msg_core_progression_reset": "Personal progression reset to $1 ($2/$3). Claim your relics again.", + "rov_msg_core_progression_state": "Progression State: $1", + "rov_msg_core_world_progression_state": "World Progression State: $1", + "rov_msg_draugh_bone_will_not_wake_something": "The bone will not wake. Something older has to fall first.", + "rov_msg_draugh_draugr_consume_only_raw_flesh": "Draugr consume only raw flesh, eyes, entrails or blood.", + "rov_msg_draugh_has_already_had_one": "It has already had one.", + "rov_msg_draugh_northern_wind_blows": "The northern wind blows", + "rov_msg_draugh_pile_broken_will_not_outlast": "The pile is broken. $1 will not outlast it by more than a minute.", + "rov_msg_draugh_pile_stirs_will_keep_officers": "The pile stirs. It will keep officers now.", + "rov_msg_draugh_steal_their_breath_death_denied": "Steal Their Breath! Death is denied.", + "rov_msg_draugh_swarm_terror": "Swarm of Terror!", + "rov_msg_draugh_this_pile_keeps_no_officers": "This pile keeps no officers yet.", + "rov_msg_draugh_this_rotting_flesh_fatal_living": "This rotting flesh is fatal to the living.", + "rov_msg_draugh_wants_flesh_or_head_one": "It wants flesh, or the head of one of its own.", + "rov_msg_draugh_zombie_ritual_activated_borrowed_time": "Zombie Ritual Activated! Your borrowed time is fading...", + "rov_msg_dvergar_contract_runic_do_not_sign": "The contract is in runic. You do not sign it.", + "rov_msg_dvergar_do_not_know_what_goes": "You do not know what goes in it.", + "rov_msg_dvergar_drink": "$1 drink $2.", + "rov_msg_dvergar_drink_barrel_runs_dry": "$1 drink $2. The barrel runs dry.", + "rov_msg_dvergar_empty_so_are": "It is empty, and so are you.", + "rov_msg_dvergar_five_contracts_all_ledger_holds": "Five contracts is all the ledger holds.", + "rov_msg_dvergar_has_already_had_one": "It has already had one.", + "rov_msg_dvergar_ledger_not_written": "The ledger is not written for you.", + "rov_msg_dvergar_ledger_rewritten_better_names_sign": "The ledger is rewritten. Better names sign it now.", + "rov_msg_dvergar_ledger_shut": "The ledger is shut.", + "rov_msg_dvergar_nobody_at_barrel": "Nobody is at the barrel.", + "rov_msg_dvergar_not_drop_went_down": "Not a drop went down.", + "rov_msg_dvergar_not_enough_eitr": "Not enough eitr", + "rov_msg_dvergar_not_while_she_still_sits": "Not while she still sits under the mist.", + "rov_msg_dvergar_runic_overcharge_discharges": "Runic Overcharge discharges", + "rov_msg_dvergar_runic_overcharge_next_blow_loaded": "Runic Overcharge: your next blow is loaded", + "rov_msg_dvergar_runic_ping_echoes_answer": "Runic Ping: $1 echoes answer", + "rov_msg_dvergar_runic_ping_stone_silent": "Runic Ping: the stone is silent", + "rov_msg_dvergar_signs": "$1 signs on.", + "rov_msg_dvergar_there_still": "There is still $1 in it.", + "rov_msg_dvergar_whatever_does_nothing_anyone": "Whatever is in it does nothing to anyone.", + "rov_msg_fenrir_are_cultist": "You are a Cultist!", + "rov_msg_fenrir_are_fenring": "You are a Fenring!", + "rov_msg_fenrir_are_ulv": "You are an Ulv!", + "rov_msg_fenrir_are_wolf": "You are a Wolf!", + "rov_msg_fenrir_beast_rests_can_only_transform": "The beast rests. You can only transform at night.", + "rov_msg_fenrir_beast_tired": "The beast is tired", + "rov_msg_fenrir_blood_will_not_take_something": "The blood will not take. Something in the plains has to fall first.", + "rov_msg_fenrir_form_cooldown": "$1 form is on cooldown ($2:$3).", + "rov_msg_fenrir_formname_cultist": "Cultist", + "rov_msg_fenrir_formname_fenrir": "Fenrir", + "rov_msg_fenrir_formname_ulv": "Ulv", + "rov_msg_fenrir_formname_wolf": "Wolf", + "rov_msg_fenrir_has_already_had_one": "It has already had one.", + "rov_msg_fenrir_only_breath_comes_out_fire": "Only breath comes out. The fire wants eitr.", + "rov_msg_fenrir_ready": "$1 is Ready!", + "rov_msg_fenrir_returned_human_form": "You returned to human form.", + "rov_msg_fenrir_sun_takes_form": "The sun takes the beast back. This form only answers at night.", + "rov_msg_fenrir_sun_takes_form_day_key": "The sun takes the beast back. This form only answers at night; by day, press $2 for the $1 form.", + "rov_msg_fenrir_trough_broken_will_not_outlast": "The trough is broken. $1 will not outlast it by long.", + "rov_msg_fenrir_trough_takes_line_runs_deeper": "The trough takes it. The line runs deeper now.", + "rov_msg_fenrir_wants_meat_any_meat": "It wants meat. Any meat.", + "rov_msg_fenrir_wants_what_yagluth_left_behind": "It wants what Yagluth left behind.", + "rov_msg_skadi_are_drake": "You are a Drake!", + "rov_msg_skadi_are_fader": "You are Fader!", + "rov_msg_skadi_are_moder": "You are Moder!", + "rov_msg_skadi_dragon_form_cooldown": "Dragon Form is on cooldown ($1:$2).", + "rov_msg_skadi_dragon_form_fades": "Your dragon form fades.", + "rov_msg_skadi_dumped_dragon_drake_fader_debug": "Dumped Dragon/Drake/Fader debug info to console!", + "rov_msg_skadi_needs_stonecutter_cut_at": "It needs a stonecutter to be cut at.", + "rov_msg_skadi_not_enough_stamina": "Not enough stamina", + "rov_msg_skadi_returned_human_form": "You returned to human form.", + "rov_msg_skadi_stone_does_not_answer": "The stone does not answer to you.", + "rov_msg_skadi_stonecutter_gone_what_cut_will": "The stonecutter is gone. What it cut will not outlast it by long.", + "rov_msg_skadi_tear_cold_nothing_wakes_stone": "The tear is cold. Nothing wakes in the stone until the mountain's queen has fallen.", + "rov_msg_skadi_that_stonecutter_already_holds_will": "That stonecutter already holds $1. It will not hold more.", + "rov_msg_skadi_there_are_already_these_within": "There are already $1 of these within a day's walk. The stone is spent.", + "rov_msg_skeleton_has_already_had_one": "It has already had one.", + "rov_msg_skeleton_have_been_resurrected_by_dark": "You have been resurrected by dark magic!", + "rov_msg_skeleton_look_normal": "Look: normal bones", + "rov_msg_skeleton_look_green": "Look: green bones", + "rov_msg_skeleton_look_flames": "Look: burning bones", + "rov_msg_skeleton_mortal_food_disgusts": "Mortal food disgusts you.", + "rov_msg_skeleton_nothing_standing_yet_wants_bone": "Nothing is standing yet. It wants bone.", + "rov_msg_skeleton_pile_broken_fall_where_they": "The pile is broken. $1 fall where they stand.", + "rov_msg_skeleton_pile_deepens_rotten_will_stand": "The pile deepens. The rotten will stand here too.", + "rov_msg_skeleton_return_pile": "$1 return to the pile.", + "rov_msg_skeleton_rise_follow": "$1 rise and follow.", + "rov_msg_skeleton_skeletons_do_not_need_eat": "Skeletons do not need to eat.", + "rov_msg_skeleton_skull_will_not_wake_something": "The skull will not wake. Something older has to fall first.", + "rov_msg_skeleton_these_bones_answer_only_their": "These bones answer only to their own kind.", + "rov_msg_skeleton_this_pile_cannot_hold_rotten": "This pile cannot hold the rotten yet.", + "rov_msg_sverm_alchemical_blood_not_food": "Alchemical blood is not food.", + "rov_msg_sverm_carapace_has_no_room_that": "Your carapace has no room for that.", + "rov_msg_sverm_colony_will_not_wake_until": "The colony will not wake until the Elder falls.", + "rov_msg_sverm_hive_does_not_know": "The hive does not know you.", + "rov_msg_sverm_hive_full_give_time_digest": "The hive is full. Give it time to digest.", + "rov_msg_sverm_market_has_stand_within_metres": "A market has to stand within $1 metres of a hive.", + "rov_msg_sverm_no_hive_within_metres_this": "No hive within $1 metres. This counter is dead.", + "rov_msg_sverm_not_enough_biomass_bank": "Not enough biomass in the bank.", + "rov_msg_sverm_not_hurt": "$1 is not hurt.", + "rov_msg_sverm_nothing_here_will_eat_food": "Nothing here it will eat. Food, wood and resin - honey and royal jelly are medicine.", + "rov_msg_sverm_only_sverm_can_raise_hive": "Only the Sverm can raise a hive.", + "rov_msg_sverm_only_sverm_can_raise_market": "Only the Sverm can raise a market.", + "rov_msg_sverm_ravager_strain_takes_hold": "The Ravager Strain takes hold.", + "rov_msg_sverm_shell_recedes": "The shell recedes.", + "rov_msg_sverm_strain_has_not_taken_yet": "The strain has not taken yet.", + "rov_msg_sverm_strain_spent": "The strain is spent.", + "rov_msg_sverm_they_are_part_hands": "They are part of your hands.", + "rov_msg_sverm_x_biomass_digesting": "$1 x$2 -> +$3 biomass, digesting", + "rov_msg_thrall_answer_call": "$1 answer the call.", + "rov_msg_thrall_answer_wait": "$1 stand and wait.", + "rov_msg_thrall_answer_home": "$1 head home.", + "rov_msg_thrall_waits": "$1 waits here.", + "rov_msg_thrall_follows": "$1 follows.", + "rov_msg_thrall_no_more_may_walk_with": "No more may walk with you.", + "rov_msg_thrall_only_may_walk_with": "Only $1 may walk with you.", + "rov_msg_thrall_refusal_default": "It does not answer to you.", + "rov_msg_thrall_refusal_draugh": "The dead do not take orders from the living.", + "rov_msg_thrall_refusal_dvergar": "Your name is not on the contract.", + "rov_msg_thrall_refusal_skeleton": "These bones answer only to their own kind.", + "rov_msg_thrall_refusal_sverm": "It does not smell your colony on you.", + "rov_msg_thrall_refusal_trol": "They were not paid by you.", + "rov_msg_thrall_returns": "$1 returns.", + "rov_msg_thrall_rises_with": "$1 rises with $2.", + "rov_msg_thrall_stands_down_with": "$1 stands down with $2.", + "rov_msg_trenta_are_muspell_ash_ember_given": "You are Muspell, ash and ember given shape.", + "rov_msg_trenta_elder_has_not_fallen_yet": "The Elder has not fallen yet.", + "rov_msg_trenta_grows": "It grows.", + "rov_msg_trenta_no_raw_flesh_rot": "No raw flesh to rot.", + "rov_msg_trenta_nothing_feed_wants_fertilizer": "Nothing to feed it. It wants Fertilizer.", + "rov_msg_trenta_nothing_there_feed": "Nothing there to feed.", + "rov_msg_trenta_return_rooted_form": "You return to your rooted form.", + "rov_msg_trenta_ripe_already": "It is ripe already.", + "rov_msg_trenta_root_will_not_take_hold": "The root will not take hold for you.", + "rov_msg_trenta_still_growing_minutes": "Still growing. $1 minutes.", + "rov_msg_trenta_still_rotting_minutes": "Still rotting. $1 minutes.", + "rov_msg_trenta_this_one_not_well_nothing": "This one is not well. Nothing will hurry it.", + "rov_msg_trenta_trenta_eat_only_what_grows": "The Trenta eat only what grows from root and leaf - no meat, fish, egg or honey.", + "rov_msg_trol_answers": "$1 answers.", + "rov_msg_trol_are_already_holding_log": "You are already holding a log!", + "rov_msg_trol_five_warbands_all_can_shout": "Five warbands is all it can shout for.", + "rov_msg_trol_has_already_had_one": "It has already had one.", + "rov_msg_trol_head_has_nothing_say": "The head has nothing to say.", + "rov_msg_trol_head_will_not_shout": "The head will not shout for you.", + "rov_msg_trol_must_true_form_lift_this": "You must be in True Form to lift this!", + "rov_msg_trol_no_room_lift": "No room to lift it!", + "rov_msg_trol_not_until_one_belonged_has": "Not until the one it belonged to has fallen.", + "rov_msg_trol_totem_wears_king_now": "The totem wears a king now.", + "rov_msg_ward_already_carry_s_power": "You already carry $1's power.", + "rov_msg_ward_s_power_yours": "$1's power is yours.", + "rov_msg_ward_switch_personal_progression_first": "Switch to personal progression first.", + "rov_msg_ward_ward_has_no_use_that": "The ward has no use for that.", + "rov_msg_warvulture_bird_does_not_know": "The bird does not know you.", + "rov_msg_warvulture_vulture_does_not_answer": "The vulture does not answer.", + "rov_msg_warvulture_vulture_settles_into_glide": "The vulture settles into a glide.", + "rov_msg_warvulture_vulture_spirals_down": "The vulture spirals down.", + "rov_msg_boneship_no_shore": "No shore in reach. They stay at the oars.", + "rov_msg_boneship_sunk": "The ship goes down, and $1 go with it." +} diff --git a/JotunnModStub/Translations/Russian/races.json b/JotunnModStub/Translations/Russian/races.json new file mode 100644 index 0000000..8d930c3 --- /dev/null +++ b/JotunnModStub/Translations/Russian/races.json @@ -0,0 +1,38 @@ +{ + "rov_menu_choose_race": "Choose your Race", + "rov_menu_ok": "OK", + "rov_menu_back": "Back", + + "rov_race_human_name": "Human", + "rov_race_human_desc": "The versatile founders of Midgard. Balanced stats with no specific weaknesses.", + + "rov_race_fenrir_name": "Fenrir", + "rov_race_fenrir_desc": "Cursed by the blood of the wolf. Fast and deadly, but vulnerable to silver.", + + "rov_race_skadi_name": "Skadi", + "rov_race_skadi_desc": "Children of the mountains. Resistant to frost, at home in the freezing cold.", + + "rov_race_skeleton_name": "Skeleton", + "rov_race_skeleton_desc": "Undead warriors. Immune to poison, but brittle against blunt trauma.", + + "rov_race_aswid_name": "Aswid", + "rov_race_aswid_desc": "Fierce night stalker. Strong and resilient, transforms into a bat.", + + "rov_race_furling_name": "Furling", + "rov_race_furling_desc": "Cunning goblin-like creatures. Agile and resourceful.", + + "rov_race_trol_name": "Trol", + "rov_race_trol_desc": "Massive brute strength. Towering over others, at peace with the Black Forest - but fire burns a Trol $1% harder than anyone else.", + + "rov_race_draugh_name": "Draugh", + "rov_race_draugh_desc": "A decaying undead warrior fueled by dark magic and extreme metal.", + + "rov_race_dvergar_name": "Dvergar", + "rov_race_dvergar_desc": "Small, stubborn smiths of the deep. Frail of frame, but masters of metal, mine and market.", + + "rov_race_trenta_name": "Trenta", + "rov_race_trenta_desc": "Tree-born folk, kin to root and leaf. Patient and hard to fell.", + + "rov_race_sverm_name": "Sverm", + "rov_race_sverm_desc": "Chitin-born swarm kin. Armoured from birth and never slowed, venomous, at peace with every crawling thing - but blunt trauma and fire find the seams." +} diff --git a/JotunnModStub/Translations/Russian/status_effects.json b/JotunnModStub/Translations/Russian/status_effects.json new file mode 100644 index 0000000..ba0b959 --- /dev/null +++ b/JotunnModStub/Translations/Russian/status_effects.json @@ -0,0 +1,62 @@ +{ + "rov_se_aswid_auspex_name": "Auspex", + "rov_se_aswid_auspex_tooltip": "Sensing life force of nearby creatures.", + "rov_se_aswid_batform_name": "Like a Bat out of Hell", + "rov_se_aswid_batform_tooltip": "You have taken the form of a Bat. You can fly, but cannot attack.", + "rov_se_aswid_bloodpotion_tooltip": "Stomachs filled with blood. Healing $1% over $2 seconds.", + "rov_se_aswid_mistform_name": "Weight of Shadows", + "rov_se_aswid_mistform_tooltip": "You are mist. Immune to physical damage and poison. Cannot attack or run.", + "rov_se_aswid_nightaura_name": "Night Aura", + "rov_se_aswid_nightaura_tooltip": "The cold strengthens your beastly senses.", + "rov_se_aswid_sensed_name": "Sensed", + "rov_se_aswid_stats_name": "Benedictus et Afflictus", + "rov_se_aswid_stats_tooltip": "Vampiric senses and life drain.", + "rov_se_claws_tooltip": "Your claws are out. They retract when this runs out.", + "rov_se_draugh_wet_tooltip": "The water restores your rotten flesh. Health regeneration increased.", + "rov_se_dvergar_overcharge_name": "Runic Overcharge", + "rov_se_dvergar_overcharge_tooltip": "Your next blow with a favoured weapon carries the whole of the charge.", + "rov_se_dvergar_overchargecd_name": "Overcharge Cooldown", + "rov_se_dvergar_overchargecd_tooltip": "The runes are spent.", + "rov_se_dvergar_pingcd_name": "Runic Ping", + "rov_se_dvergar_pingcd_tooltip": "The runes must settle before you may call on them again.", + "rov_se_dvergar_stats_name": "Stone and Forge", + "rov_se_dvergar_stats_tooltip": "Small, sturdy, and born to the anvil.", + "rov_se_fenrir_cultistcd_name": "Cultist Form Cooldown", + "rov_se_fenrir_cultistform_name": "Cultist Fury", + "rov_se_fenrir_curse_name": "Fenrir's Blood", + "rov_se_fenrir_curse_tooltip": "You are of the Fenrir race.", + "rov_se_fenrir_form_name": "Bestial Fury", + "rov_se_fenrir_formcd_name": "Fenrir Form Cooldown", + "rov_se_fenrir_wolfform_name": "Wolf Senses", + "rov_se_skadi_aura_name": "Skadi's Aura", + "rov_se_skadi_aura_tooltip": "Empowered by the frost.", + "rov_se_skadi_coldspellcd_name": "Cold Spell", + "rov_se_skadi_coldspellcd_tooltip": "The frost must gather again before you may cast.", + "rov_se_skadi_dragonattackcd_name": "Dragon Attack", + "rov_se_skadi_dragonattackcd_tooltip": "Your dragon shape must ready itself to strike again.", + "rov_se_skadi_form_name": "Dragon Form", + "rov_se_skadi_form_tooltip": "Your dragon shape holds for a while longer.", + "rov_se_skadi_formcd_name": "Dragon Form Cooldown", + "rov_se_skadi_stats_name": "Skadi's Blessing", + "rov_se_skeleton_resurrectcd_name": "Resurrection Cooldown", + "rov_se_skeleton_resurrectcd_tooltip": "Your skeletal body is too weak to resurrect again right now.", + "rov_se_skeleton_stats_name": "Undead Fortitude", + "rov_se_sverm_ravager_name": "Ravager Strain", + "rov_se_sverm_ravager_tooltip": "The shell doubles, and nothing that hits it lands the same again.", + "rov_se_sverm_ravagercd_name": "Ravager Strain Cooldown", + "rov_se_sverm_ravagercd_tooltip": "The strain is spent. It will take again soon.", + "rov_se_sverm_stats_name": "Chitin Plating", + "rov_se_sverm_stats_tooltip": "Armoured, venomous, and never alone.", + "rov_se_trenta_portalcd_name": "Homecoming Portal", + "rov_se_trenta_portalcd_tooltip": "The way home has not yet settled enough to open again.", + "rov_se_trenta_purpleraincd_name": "Purple Rain", + "rov_se_trenta_purpleraincd_tooltip": "The pollen must settle before you may call the rain again.", + "rov_se_trenta_stats_name": "Heartwood", + "rov_se_trenta_stats_tooltip": "Rooted, patient, and hard to fell.", + "rov_se_trol_throwcd_name": "Throw Rock Cooldown", + "rov_se_trol_throwcd_tooltip": "You must wait before throwing another rock.", + "rov_se_trol_trueform_name": "True Form", + "rov_se_trol_trueform_tooltip": "You have unleashed your inner troll!", + "rov_se_trol_trueformcd_name": "True Form Cooldown", + "rov_se_trol_trueformcd_tooltip": "You are exhausted from your True Form." +} From c5eef16dc2796adbbc0c4a786972335c94b44ec5 Mon Sep 17 00:00:00 2001 From: kanym Date: Tue, 6 Oct 2026 13:46:00 +0200 Subject: [PATCH 002/163] docs: add translator guide --- TRANSLATING.md | 55 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 TRANSLATING.md diff --git a/TRANSLATING.md b/TRANSLATING.md new file mode 100644 index 0000000..77e734d --- /dev/null +++ b/TRANSLATING.md @@ -0,0 +1,55 @@ +# Translating Races of Valheim + +Thanks for helping. This page covers the rules for translations. + +## Where to work + +- Each language has its own branch, `localisation-` (for example `localisation-russian`). Work only on that branch. +- When you're done, open a pull request into `localisation`. Never open one into `main`. +- Edit only the files under `JotunnModStub/Translations//`. Leave every other file alone. + +If your language has no branch yet, ask for one. + +## The files + +Each file is a JSON list of key/value pairs: + +```json +"rov_race_furling_desc": "Cunning goblin-like creatures. Agile and resourceful." +``` + +- **Never change a key.** Keys look like `rov_
_`. Translate only the value on the right. +- **Keep placeholders exactly as they are.** `$1`, `$2` and any other `$word` inside a value get replaced by numbers or names in game. You can move them around in the sentence, but don't rename, translate or delete them. +- Keep `\n` line breaks where they are. + +## What not to translate + +- **Race IDs.** These are the internal race names the code uses, and they never change. Race display names, such as the value of `rov_race_furling_name`, are translated. +- **Ability names that are quotes or song titles.** These stay in the original language: + - Purple Rain + - Weight of Shadows + - Like a Bat out of Hell + - Vae Victis + - Swarm of Terror + - The Furling passives: Master of Shadows, Dance of the Dead, Through Fire and Flames, The Wickerman + + If one of these names appears inside a longer sentence, translate the sentence and leave the name as it is. +- Translate every other, purely functional, ability name (for example "Combat Mastery"). + +## Keep the JSON valid + +- Save files as UTF-8 **without** a BOM. +- No trailing comma after the last entry. +- Escape double quotes inside values as `\"`. + +Check each file before you push: + +``` +python -m json.tool JotunnModStub/Translations//races.json +``` + +If it prints the file back, it's fine. If it prints an error, it shows the line to fix. + +## Partial translations are fine + +Any key missing from your files, or still in English, falls back to the English text in game. You can translate a file at a time and push as you go. From 0159f1e8c41a0a19e65fefb6397fbbb21699509f Mon Sep 17 00:00:00 2001 From: Ferdinando Date: Wed, 7 Oct 2026 17:31:29 +0200 Subject: [PATCH 003/163] bugfix 07/10/26 + evil laugh --- JotunnModStub/Aswid/AswidPatches.cs | 27 ++ JotunnModStub/Fenrir/FenrirPatches.cs | 26 ++ JotunnModStub/Furling/FurlingPatches.cs | 6 +- JotunnModStub/Package/manifest.json | 2 +- JotunnModStub/RacesOfValheim.cs | 3 +- JotunnModStub/Skadi/SkadiPatches.cs | 26 ++ JotunnModStub/Skeleton/SkeletonEvilLaugh.cs | 294 ++++++++++++++++++++ JotunnModStub/Skeleton/SkeletonPatches.cs | 6 + JotunnModStub/Sverm/SvermRavagerForm.cs | 24 ++ README.md | 9 +- manifest.json | 2 +- 11 files changed, 417 insertions(+), 8 deletions(-) create mode 100644 JotunnModStub/Skeleton/SkeletonEvilLaugh.cs diff --git a/JotunnModStub/Aswid/AswidPatches.cs b/JotunnModStub/Aswid/AswidPatches.cs index e2bb353..6931d80 100644 --- a/JotunnModStub/Aswid/AswidPatches.cs +++ b/JotunnModStub/Aswid/AswidPatches.cs @@ -239,6 +239,33 @@ namespace RacesOfValheim } } + /// + /// Bat and mist form shut the rest of the human's attack loop as well as StartAttack: crossbow + /// reload and draw live in PlayerAttackInput, and the form's Animator fires the held attack + /// through OnAttackTrigger. See Fenrir's BlockPlayerAttackInputPatch. + /// + public static class AswidFormAttackLoop + { + public static bool InForm(Humanoid player) + { + if (player != Player.m_localPlayer) return false; + return player.GetComponentInChildren() != null + || player.GetSEMan().HaveStatusEffect("SE_MistForm".GetStableHashCode()); + } + } + + [HarmonyPatch(typeof(Player), "PlayerAttackInput")] + public static class Aswid_BlockAttackInput_Patch + { + public static bool Prefix(Player __instance) => !AswidFormAttackLoop.InForm(__instance); + } + + [HarmonyPatch(typeof(Humanoid), nameof(Humanoid.OnAttackTrigger))] + public static class Aswid_BlockAttackTrigger_Patch + { + public static bool Prefix(Humanoid __instance) => !AswidFormAttackLoop.InForm(__instance); + } + [HarmonyPatch(typeof(Character), "SetRun")] public static class Aswid_Run_Patch { diff --git a/JotunnModStub/Fenrir/FenrirPatches.cs b/JotunnModStub/Fenrir/FenrirPatches.cs index ccb2fdf..4b91b46 100644 --- a/JotunnModStub/Fenrir/FenrirPatches.cs +++ b/JotunnModStub/Fenrir/FenrirPatches.cs @@ -34,6 +34,32 @@ namespace RacesOfValheim } } + /// + /// The rest of the human's attack loop, shut while a form is up. StartAttack is the only door an + /// attack starts through and it is blocked above, but a crossbow also lives in the loop around it: + /// PlayerAttackInput reloads it and holds its draw, and the form's own Animator carries + /// CharacterAnimEvent, whose OnAttackTrigger event resolves to the PLAYER (its Character is the first + /// one up the hierarchy) and fires whatever attack the human still has in hand. A tester's crossbow + /// shot on all three form attacks, reloaded for free, like a semi-automatic. + /// + [HarmonyPatch(typeof(Player), "PlayerAttackInput")] + public static class BlockPlayerAttackInputPatch + { + public static bool Prefix(Player __instance) + { + return !FenrirForms.LocalInForm(__instance); + } + } + + [HarmonyPatch(typeof(Humanoid), nameof(Humanoid.OnAttackTrigger))] + public static class BlockPlayerAttackTriggerPatch + { + public static bool Prefix(Humanoid __instance) + { + return !FenrirForms.LocalInForm(__instance); + } + } + // --- PATCH 2: BLOCCO ANIMAZIONI ED EFFETTI SONORI NATIVI --- // Every form now, not the Fenring alone: see BlockPlayerLogicAttackPatch. [HarmonyPatch(typeof(ZSyncAnimation), nameof(ZSyncAnimation.SetTrigger))] diff --git a/JotunnModStub/Furling/FurlingPatches.cs b/JotunnModStub/Furling/FurlingPatches.cs index ce998f9..01bb0d3 100644 --- a/JotunnModStub/Furling/FurlingPatches.cs +++ b/JotunnModStub/Furling/FurlingPatches.cs @@ -402,9 +402,9 @@ namespace RacesOfValheim { 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)) + // Check if it's an arrow or a bolt (either by skill or by checking if a bow/crossbow/ammo was used) + if ((hitData != null && (hitData.m_skill == Skills.SkillType.Bows || hitData.m_skill == Skills.SkillType.Crossbows)) || + (ammo != null && (ammo.m_shared.m_skillType == Skills.SkillType.Bows || ammo.m_shared.m_skillType == Skills.SkillType.Crossbows))) { // If the arrow doesn't already have significant fire damage, add it if (hitData != null && hitData.m_damage.m_fire < 22f) diff --git a/JotunnModStub/Package/manifest.json b/JotunnModStub/Package/manifest.json index 4c2b199..8b25e6f 100644 --- a/JotunnModStub/Package/manifest.json +++ b/JotunnModStub/Package/manifest.json @@ -1,7 +1,7 @@ { "name": "RacesOfValheim", "description": "A Valheim mod that adds ten custom playable races (Aswid, Draugh, Dvergar, Fenrir, Furling, Skadi, Skeleton, Sverm, Trenta, Trol) each with unique abilities, traits, race stations and a deep boss-driven progression system.", - "version_number": "1.5.8", + "version_number": "1.5.9", "website_url": "", "dependencies": [ "denikson-BepInExPack_Valheim-5.4.2333", diff --git a/JotunnModStub/RacesOfValheim.cs b/JotunnModStub/RacesOfValheim.cs index 4e14cc4..fe1cebb 100644 --- a/JotunnModStub/RacesOfValheim.cs +++ b/JotunnModStub/RacesOfValheim.cs @@ -15,7 +15,7 @@ namespace RacesOfValheim { public const string PluginGUID = "com.nandor.racesofvalheim"; public const string PluginName = "Races Of Valheim"; - public const string PluginVersion = "1.5.8"; + public const string PluginVersion = "1.5.9"; private readonly Harmony harmony = new Harmony(PluginGUID); @@ -80,6 +80,7 @@ namespace RacesOfValheim CommandManager.Instance.AddConsoleCommand(new DumpPotionsCommand()); CommandManager.Instance.AddConsoleCommand(new ListPrefabsCommand()); CommandManager.Instance.AddConsoleCommand(new DumpAnimCommand()); + CommandManager.Instance.AddConsoleCommand(new EvilLaughCommand()); } /// diff --git a/JotunnModStub/Skadi/SkadiPatches.cs b/JotunnModStub/Skadi/SkadiPatches.cs index 2979b84..a2aecb0 100644 --- a/JotunnModStub/Skadi/SkadiPatches.cs +++ b/JotunnModStub/Skadi/SkadiPatches.cs @@ -601,4 +601,30 @@ namespace RacesOfValheim return true; } } + + /// + /// The rest of the human's attack loop, shut while a dragon form is up: crossbow reload and draw + /// live in PlayerAttackInput, and the form's Animator fires the held attack through + /// OnAttackTrigger. Without these a crossbow in hand shot on every form attack. See Fenrir's + /// BlockPlayerAttackInputPatch. + /// + [HarmonyPatch(typeof(Player), "PlayerAttackInput")] + public static class SkadiBlockAttackInputPatch + { + public static bool Prefix(Player __instance) + { + if (__instance != Player.m_localPlayer) return true; + return __instance.GetComponentInChildren() == null; + } + } + + [HarmonyPatch(typeof(Humanoid), nameof(Humanoid.OnAttackTrigger))] + public static class SkadiBlockAttackTriggerPatch + { + public static bool Prefix(Humanoid __instance) + { + if (__instance != Player.m_localPlayer) return true; + return __instance.GetComponentInChildren() == null; + } + } } diff --git a/JotunnModStub/Skeleton/SkeletonEvilLaugh.cs b/JotunnModStub/Skeleton/SkeletonEvilLaugh.cs new file mode 100644 index 0000000..e981c81 --- /dev/null +++ b/JotunnModStub/Skeleton/SkeletonEvilLaugh.cs @@ -0,0 +1,294 @@ +using System; +using System.Collections.Generic; +using Jotunn.Entities; +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// The Skeleton's villain laugh: /evillaugh. Head thrown back, jaw clacking, shoulders + /// shaking, both fists punched up into the air. + /// + /// It is not an animation clip and it is not the vanilla 'laugh' emote. It is a pose written + /// over the rig in LateUpdate, the way SkeletonJawFix does for the mandible, so it needs no + /// asset bundle and no Animator parameter. + /// + /// The start time goes on the player's ZDO, so every client that can see the Skeleton plays + /// the same laugh - the command only has to run on the laughing player's own machine. + /// + /// Two kinds of bone, two rules (see SkeletonJawFix for why it matters): + /// - Bones the Animator rewrites every frame (head, chest, arms) get the pose multiplied on + /// top of whatever the animation left, so it can never accumulate. + /// - Bones nothing animates (the jaw, the fingers) are written ABSOLUTELY from the rest + /// pose captured once, so the pose is the same however many frames it has been applied. + /// + /// Every direction is worked out in the player's own frame (right / up / forward) rather than + /// in a bone's local axes, which the rig does not make guessable. The angles below are first + /// guesses to be tuned in game. + /// + public class SkeletonEvilLaugh : MonoBehaviour + { + public const string ZdoKey = "RoV_skelEvilLaughAt"; + + private const float DurationSeconds = 4f; + private const float BlendSeconds = 0.3f; + + // The laugh itself: how fast the shoulders shake and the jaw clacks, per second. + private const float ShakeHz = 8f; + + private const float HeadBackDegrees = 28f; + private const float NeckBackDegrees = 8f; + private const float ChestBackDegrees = 10f; + private const float ChestShakeDegrees = 3.5f; + private const float HeadNodDegrees = 4f; + private const float JawOpenDegrees = 24f; + + // Fingers curl about the bone's own Z, the usual axis of a humanoid finger. If the fists + // open instead of closing in game, flip the sign. + private const float FingerCurlDegrees = 70f; + + // Where the fists go, in the player's frame: outward, up, a little forward. + private static readonly Vector3 UpperArmAim = new Vector3(0.5f, 0.8f, 0.25f); + private static readonly Vector3 ForearmAim = new Vector3(0.15f, 1f, 0.1f); + + private struct Side + { + public Transform upper, lower, hand; + public float sign; + public List fingers; + public List fingerRest; + } + + private Player m_player; + private VisEquipment m_vis; + private ZNetView m_nview; + + private bool m_resolved; + private Transform m_head, m_neck, m_chest, m_jaw; + private Quaternion m_jawRest; + private Side m_left, m_right; + + private float m_weight; + private bool m_wroteHands; + + // ── Starting it ────────────────────────────────────────────────────── + + /// Starts the laugh for the local player; everyone else picks it up from the ZDO. + public static bool Begin(Player player) + { + if (player == null || ZNet.instance == null) return false; + if (!SkeletonVisuals.IsSkeletonPlayer(player)) return false; + + ZNetView nview = player.GetComponent(); + if (nview == null || !nview.IsValid()) return false; + + nview.GetZDO().Set(ZdoKey, ZNet.instance.GetTime().Ticks); + return true; + } + + private void Awake() + { + m_player = GetComponent(); + m_vis = GetComponent(); + m_nview = GetComponent(); + } + + // ── The pose ───────────────────────────────────────────────────────── + + private void LateUpdate() + { + if (m_player == null || m_nview == null || !m_nview.IsValid() || ZNet.instance == null) return; + + float elapsed = ElapsedSinceStart(); + bool laughing = elapsed >= 0f && elapsed < DurationSeconds + && SkeletonVisuals.IsSkeletonPlayer(m_player) + && !m_player.IsDead(); + + // Fade in over the first moments, out over the last, so the pose never pops. + float target = 0f; + if (laughing) target = Mathf.Clamp01(Mathf.Min(elapsed, DurationSeconds - elapsed) / BlendSeconds); + + m_weight = Mathf.MoveTowards(m_weight, target, Time.deltaTime / BlendSeconds); + + if (m_weight <= 0f) + { + if (m_wroteHands) RestoreHands(); + return; + } + + if (!m_resolved) Resolve(); + + float t = Time.time; + float wave = Mathf.Sin(t * ShakeHz * Mathf.PI * 2f); + float open = 0.5f + 0.5f * Mathf.Sin(t * ShakeHz * Mathf.PI * 2f + 0.6f); + + Vector3 right = m_player.transform.right; + + // Back and up, the whole spine in on it: chest first, then neck, then head. + Pitch(m_chest, -(ChestBackDegrees + ChestShakeDegrees * wave) * m_weight, right); + Pitch(m_neck, -NeckBackDegrees * m_weight, right); + Pitch(m_head, -(HeadBackDegrees + HeadNodDegrees * wave) * m_weight, right); + + if (m_jaw != null && m_jaw.parent != null) + { + m_jaw.localRotation = m_jawRest; + m_jaw.rotation = Quaternion.AngleAxis(JawOpenDegrees * open * m_weight, right) * m_jaw.rotation; + } + + Fists(m_left, wave); + Fists(m_right, wave); + m_wroteHands = true; + } + + /// Seconds since the laugh began, by the same clock on every client; -1 if there is none. + private float ElapsedSinceStart() + { + long ticks = m_nview.GetZDO().GetLong(ZdoKey, 0L); + if (ticks == 0L) return -1f; + + double age = (ZNet.instance.GetTime() - new DateTime(ticks)).TotalSeconds; + return age < 0 ? -1f : (float)age; + } + + private static void Pitch(Transform bone, float degrees, Vector3 axis) + { + if (bone == null) return; + bone.rotation = Quaternion.AngleAxis(degrees, axis) * bone.rotation; + } + + private void Fists(Side side, float wave) + { + if (side.upper == null || side.lower == null || side.hand == null) return; + + Vector3 right = m_player.transform.right; + Vector3 up = Vector3.up; + Vector3 fwd = m_player.transform.forward; + + // Each fist punches up and down a little with the laugh. + Vector3 pump = up * (0.12f * wave); + + Aim(side.upper, side.lower, Frame(UpperArmAim, side.sign, right, up, fwd) + pump); + Aim(side.lower, side.hand, Frame(ForearmAim, -side.sign, right, up, fwd) + pump); + + if (side.fingers == null) return; + + for (int i = 0; i < side.fingers.Count; i++) + { + Transform finger = side.fingers[i]; + if (finger == null) continue; + finger.localRotation = side.fingerRest[i] + * Quaternion.Euler(0f, 0f, FingerCurlDegrees * m_weight); + } + } + + private static Vector3 Frame(Vector3 aim, float sideSign, Vector3 right, Vector3 up, Vector3 fwd) + => (right * (aim.x * sideSign) + up * aim.y + fwd * aim.z).normalized; + + /// + /// Turns a bone so the line from it to its child points along 'desired', by as much as the + /// weight allows. The child follows the parent, so the forearm is aimed after the upper arm. + /// + private void Aim(Transform bone, Transform child, Vector3 desired) + { + Vector3 current = child.position - bone.position; + if (current.sqrMagnitude < 1e-8f) return; + + Quaternion full = Quaternion.FromToRotation(current.normalized, desired.normalized); + bone.rotation = Quaternion.Slerp(Quaternion.identity, full, m_weight) * bone.rotation; + } + + private void RestoreHands() + { + foreach (Side side in new[] { m_left, m_right }) + { + if (side.fingers == null) continue; + for (int i = 0; i < side.fingers.Count; i++) + if (side.fingers[i] != null) side.fingers[i].localRotation = side.fingerRest[i]; + } + + if (m_jaw != null) m_jaw.localRotation = m_jawRest; + m_wroteHands = false; + } + + // ── Finding the bones ──────────────────────────────────────────────── + + private void Resolve() + { + Animator anim = m_player.GetComponentInChildren(); + + m_head = Find(anim, HumanBodyBones.Head, "head"); + m_neck = Find(anim, HumanBodyBones.Neck, "neck"); + m_chest = Find(anim, HumanBodyBones.UpperChest, "spine2") ?? Find(anim, HumanBodyBones.Chest, "spine1"); + + m_jaw = FindByName("jaw"); + if (m_jaw != null) m_jawRest = m_jaw.localRotation; + + m_left = BuildSide(anim, true); + m_right = BuildSide(anim, false); + + m_resolved = true; + } + + private Side BuildSide(Animator anim, bool left) + { + string prefix = left ? "left" : "right"; + Side side = new Side + { + sign = left ? -1f : 1f, + upper = Find(anim, left ? HumanBodyBones.LeftUpperArm : HumanBodyBones.RightUpperArm, prefix + "arm"), + lower = Find(anim, left ? HumanBodyBones.LeftLowerArm : HumanBodyBones.RightLowerArm, prefix + "forearm"), + hand = Find(anim, left ? HumanBodyBones.LeftHand : HumanBodyBones.RightHand, prefix + "hand"), + fingers = new List(), + fingerRest = new List() + }; + + // Every bone below the hand is a finger or a thumb; a hand with none just opens and + // closes nothing, and the arms still go up. + if (side.hand != null) + { + foreach (Transform child in side.hand.GetComponentsInChildren()) + { + if (child == side.hand) continue; + side.fingers.Add(child); + side.fingerRest.Add(child.localRotation); + } + } + + return side; + } + + private Transform Find(Animator anim, HumanBodyBones bone, string fallbackName) + { + Transform t = anim != null ? anim.GetBoneTransform(bone) : null; + return t != null ? t : FindByName(fallbackName); + } + + private Transform FindByName(string part) + { + if (m_vis == null || m_vis.m_bodyModel == null || m_vis.m_bodyModel.bones == null) return null; + + foreach (Transform bone in m_vis.m_bodyModel.bones) + if (bone != null && bone.name.ToLower().Contains(part)) return bone; + + return null; + } + } + + public class EvilLaughCommand : ConsoleCommand + { + public override string Name => "evillaugh"; + public override string Help => "The Skeleton's villain laugh"; + + public override void Run(string[] args) + { + if (Player.m_localPlayer == null) + { + Console.instance.Print("You must be in-game to laugh."); + return; + } + + if (!SkeletonEvilLaugh.Begin(Player.m_localPlayer)) + Console.instance.Print("Only a Skeleton laughs like that."); + } + } +} diff --git a/JotunnModStub/Skeleton/SkeletonPatches.cs b/JotunnModStub/Skeleton/SkeletonPatches.cs index b977f35..0937e37 100644 --- a/JotunnModStub/Skeleton/SkeletonPatches.cs +++ b/JotunnModStub/Skeleton/SkeletonPatches.cs @@ -359,6 +359,12 @@ namespace RacesOfValheim p.gameObject.AddComponent(); } + // The /evillaugh pose; same reasoning as the jaw, so remote players laugh too. + if (p.GetComponent() == null) + { + p.gameObject.AddComponent(); + } + // The lights in the eye sockets, cloned out of this tier's own creature so // that each one arrives its own colour. Outside the build block above on // purpose: they hang off the player's rig bones rather than off the body diff --git a/JotunnModStub/Sverm/SvermRavagerForm.cs b/JotunnModStub/Sverm/SvermRavagerForm.cs index 91055b1..b0e6497 100644 --- a/JotunnModStub/Sverm/SvermRavagerForm.cs +++ b/JotunnModStub/Sverm/SvermRavagerForm.cs @@ -452,6 +452,30 @@ namespace RacesOfValheim } } + /// + /// The rest of the human's attack loop - crossbow reload and draw, and the animation event that + /// fires a held attack - shut for the form too. See Fenrir's BlockPlayerAttackInputPatch. + /// + [HarmonyPatch(typeof(Player), "PlayerAttackInput")] + public static class Sverm_RavagerBlockAttackInput_Patch + { + public static bool Prefix(Player __instance) + { + if (__instance != Player.m_localPlayer) return true; + return !IsActive; + } + } + + [HarmonyPatch(typeof(Humanoid), nameof(Humanoid.OnAttackTrigger))] + public static class Sverm_RavagerBlockAttackTrigger_Patch + { + public static bool Prefix(Humanoid __instance) + { + if (__instance != Player.m_localPlayer) return true; + return !IsActive; + } + } + /// No food, no mead, no potions. The form is meant to be survived, not sustained. [HarmonyPatch(typeof(Humanoid), "UseItem")] public static class Sverm_RavagerUseItem_Patch diff --git a/README.md b/README.md index cc27003..39865d8 100644 --- a/README.md +++ b/README.md @@ -15,9 +15,9 @@ Support the mod: [Patreon — NandorTheModder](https://www.patreon.com/c/NandorT --- -## New in v1.5.8 +## New in v1.5.9 -Three Skeleton fixes. The Yagluth auto-resurrect now plays the crypt rise, so you climb out of the ground instead of staying on your feet. Wild creatures of your faction no longer attack your bound skeletons. The Bound Bone Pile and the Bound Sentry can be built on floors and foundations, not only on the ground. Full details in the [changelog](#v158). +Skeletons can laugh: type /evillaugh. The Furling's fire bonus now covers crossbow bolts, and a crossbow in hand no longer fires on every attack while you are transformed. Full details in the [changelog](#v159). --- @@ -447,6 +447,11 @@ Both halves have an off switch under `Factions` in Configuration Manager: **Fact ## Changelog +### v1.5.9 +- **New - /evillaugh (Skeleton):** the Skeleton throws its head back, clacks its jaw, shakes its shoulders and punches both fists into the air for four seconds. Everyone nearby sees it. +- **Change - Furling fire bolts:** the Wickerman's fire damage now also applies to crossbow bolts, not only to arrows. +- **Fix - crossbow fired on every attack while transformed:** with a crossbow equipped, every attack of a form (left, right and middle mouse) shot the crossbow and reloaded it for free, like a semi-automatic. The human's attack loop is now shut while the form is up. Applies to the Fenrir forms, the Sverm Ravager, the Skadi dragon forms and the Aswid bat and mist forms. Thanks to the player who reported it. + ### v1.5.8 - **Fix - Skeleton auto-resurrect played no rise:** coming back from a lethal hit, the Skeleton stayed on its feet. It now climbs out of the ground like a crypt skeleton, and every player nearby sees it. You take no damage and cannot move or attack until you are out. - **Fix - wild faction creatures attacked bound troops:** the faction truce covered the player but not the player's troops, so a wild Rancid Remains left a Skeleton alone and tore into the garrison of its bone pile. Wild creatures of a race's faction now leave that race's troops alone too, for every race that has them. Hit one of those creatures and the truce ends: it fights you, and your troops fight it. diff --git a/manifest.json b/manifest.json index 4c2b199..8b25e6f 100644 --- a/manifest.json +++ b/manifest.json @@ -1,7 +1,7 @@ { "name": "RacesOfValheim", "description": "A Valheim mod that adds ten custom playable races (Aswid, Draugh, Dvergar, Fenrir, Furling, Skadi, Skeleton, Sverm, Trenta, Trol) each with unique abilities, traits, race stations and a deep boss-driven progression system.", - "version_number": "1.5.8", + "version_number": "1.5.9", "website_url": "", "dependencies": [ "denikson-BepInExPack_Valheim-5.4.2333", From 8bad4092bedd94ad6ebb462fa8dfed2b930d266e Mon Sep 17 00:00:00 2001 From: Axibed Date: Thu, 8 Oct 2026 07:45:13 +0200 Subject: [PATCH 004/163] =?UTF-8?q?=D0=9E=D0=B1=D0=BD=D0=BE=D0=B2=D0=B8?= =?UTF-8?q?=D1=82=D1=8C=20JotunnModStub/Translations/Russian/races.json?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit по канону Valheim Драуг - Драугр --- JotunnModStub/Translations/Russian/races.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/JotunnModStub/Translations/Russian/races.json b/JotunnModStub/Translations/Russian/races.json index eaf2ab2..e09b7f9 100644 --- a/JotunnModStub/Translations/Russian/races.json +++ b/JotunnModStub/Translations/Russian/races.json @@ -16,7 +16,7 @@ "rov_race_furling_desc": "Коварные гоблиноподобные создания. Невероятно ловкие и запасливые.", "rov_race_trol_name": "Тролль", "rov_race_trol_desc": "Обладает сокрушительной физической силой и возвышается над всеми. В ладах с обитателями Черного леса, однако огонь наносит Троллю на $1% больше урона, чем остальным.", - "rov_race_draugh_name": "Драуг", + "rov_race_draugh_name": "Драугр", "rov_race_draugh_desc": "Гниющий неупокоенный воин, движимый темной магией и яростью первобытной стали.", "rov_race_dvergar_name": "Дверг", "rov_race_dvergar_desc": "Низкорослые, упрямые кузнецы из подземных глубин. Физически хрупки, но не знают равных в металлургии, горном деле и торговле.", From c45ca80d99cfe9638d6f72a85b50aba6ff4fc040 Mon Sep 17 00:00:00 2001 From: Axibed Date: Thu, 8 Oct 2026 07:52:10 +0200 Subject: [PATCH 005/163] =?UTF-8?q?=D0=9E=D0=B1=D0=BD=D0=BE=D0=B2=D0=B8?= =?UTF-8?q?=D1=82=D1=8C=20JotunnModStub/Translations/Russian/compendium.js?= =?UTF-8?q?on?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Translations/Russian/compendium.json | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/JotunnModStub/Translations/Russian/compendium.json b/JotunnModStub/Translations/Russian/compendium.json index ac6eb7b..bc64748 100644 --- a/JotunnModStub/Translations/Russian/compendium.json +++ b/JotunnModStub/Translations/Russian/compendium.json @@ -5,7 +5,7 @@ "rov_compendium_aswid_bat_form_g_key_night": "[Награда: Эйктюр] Облик мыши (клавиша «G», только ночью): Примите облик летучей мыши.\n", "rov_compendium_aswid_bat_form_now_answers_by": "[Награда: Древний] Облик мыши теперь доступен как ночью, так и днем.\n", "rov_compendium_aswid_benedictus_et_afflictus": "[Базовое пассивное] Benedictus et Afflictus:", - "rov_compendium_aswid_claws_beast_s_grows_blackened": "[Базовое пассивное] Когти зверя ([K], $1 с): На ограниченное время отращивает черные когти вместо оружия. Удары кулаками наносят $2% от урона зрелых когтей (полностью режущий урон), и их сила растет с каждым поверженным боссом. Если достать меч — когти спрячутся, убрать его — вернутся, пока не истечет таймер. Не занимают ячейку экипировки. Их нельзя выбросить, передать или украсть, пока они активны. В облике мыши или тумана когти недоступны, так как у вас нет рук.\n", + "rov_compendium_aswid_claws_beast_s_grows_blackened": "[Базовое пассивное] Когти зверя ([K], $1 с): На ограниченное время отращивает черные когти вместо оружия. Удары кулаками наносят $2% от урона зрелых когтей (полностью рубящий урон), и их сила растет с каждым поверженным боссом. Если достать меч — когти спрячутся, убрать его — вернутся, пока не истечет таймер. Не занимают ячейку экипировки. Их нельзя выбросить, передать или украсть, пока они активны. В облике мыши или тумана когти недоступны, так как у вас нет рук.\n", "rov_compendium_aswid_dominate_native_interact_key": "[Награда: Яглут] Порабощение (клавиша взаимодействия):", "rov_compendium_aswid_eclipse_j_key_day_only": "[Награда: Яглут] Затмение (клавиша «J», только днем):", "rov_compendium_aswid_freezing_blood_passive": "[Награда: Матерь] Ледяная кровь (Пассивное):", @@ -24,15 +24,15 @@ "rov_compendium_aswid_transform_into_elusive_mist_become": "Вы превращаетесь в бесплотный туман. Вы получаете иммунитет к физическому (дробящий/рубящий/колющий) урону и яду, а также не получаете урона от падения, но не можете атаковать, бегать или прыгать. Вампирическая аура наносит удвоенный урон в этой форме. Восход солнца развеивает превращение.\n", "rov_compendium_aswid_vampiric_aura_passive_toggle": "Вампирическая аура (Пассивное, переключение на [I]):", "rov_compendium_aswid_weight_shadows_h_key_toggle": "[Награда: Королева] Weight of Shadows (клавиша «H», переключение):", - "rov_compendium_draugh_born_dead_buried_alive_take": "[Базовое пассивное] Born Dead, Buried Alive: Вы получаете на $1% меньше физического (дробящий/рубящий/колющий) урона, но урон от огня и духа бьет по вам на $2% больнее. Скелеты, драугры, призраки и духи больше не считают вас добычей. Ваше пищеварение адаптировалось к смерти, позволяя есть сырое и гнилое мясо (хвосты шеек, сырое мясо, потроха, кровь и т. д.) — обычная приготовленная еда и ягоды вызывают отвращение и не могут быть съедены.\n", - "rov_compendium_draugh_draugh_s_awakening": "Пробуждение Драуга\n", + "rov_compendium_draugh_born_dead_buried_alive_take": "[Базовое пассивное] Born Dead, Buried Alive: Вы получаете на $1% меньше физического (дробящий/рубящий/колющий) урона, но урон от огня и духа бьет по вам на $2% больнее. Скелеты, драугры, призраки и духи больше не считают вас добычей. Ваше пищеварение адаптировалось к смерти, позволяя есть сырое и гнилое мясо (хвосты никсов, сырое мясо, потроха, кровь и т. д.) — обычная приготовленная еда и ягоды вызывают отвращение и не могут быть съедены.\n", + "rov_compendium_draugh_draugh_s_awakening": "Пробуждение Драугра\n", "rov_compendium_draugh_grave_chill_passive_parry_frost": "[Награда: Матерь] Могильный холод (Пассивное/Парирование): Мороз больше не может навредить вам. Успешное парирование также высвобождает волну холода, наносящую $1 урона от мороза и отталкивающую всё в радиусе $2 м от вас. У волны отдельная перезарядка в $3 с, независимая от всплеска яда «Гниющего клинка», который срабатывает при каждом парировании.\n", "rov_compendium_draugh_rotting_edge_passive_parry_physical": "[Награда: Древний] Гниющий клинок (Пассивное/Парирование): Ваши физические атаки пропитаны болотным тленом, добавляя урон ядом в размере $1% от нанесенного физ. урона. Успешное парирование также окатывает парированного врага $2 ед. урона ядом.\n", "rov_compendium_draugh_slowly_we_rot_passive_being": "[Награда: Эйктюр] Slowly We Rot (Пассивное): Статус «Сырость» больше не снижает восстановление выносливости, а вместо этого исцеляет вас — здоровье восстанавливается на $1% быстрее, пока вы мокрые или плывете.\n", "rov_compendium_draugh_steal_their_breath_execution_while": "[Награда: Прародитель] Steal Their Breath (Казнь): Находясь в призрачном состоянии выживания «Обряда зомби», нанесение смертельного удара любому врагу мгновенно восстановит $1% вашего максимального здоровья, остановит утечку эйтра и вернет вас к полноценной жизни.\n", "rov_compendium_draugh_swarm_terror_retaliation_whenever_are": "[Награда: Королева] Swarm of Terror (Возмездие): Каждый раз при получении удара в ближнем бою вы автоматически призываете $1 выводков искателя для защиты. Они живут $2 с. Перезарядка между призывами: $3 с.\n", - "rov_compendium_draugh_title": "Тайны Драуга", - "rov_compendium_draugh_undead_fortitude_passive_poison_can": "[Награда: Масса костей] Стойкость нежити (Пассивное): Яд больше совершенно не действует на вас. Удары по ошеломленным врагам наносят на $1% больше физ. урона, а смерть больше не отнимает опыт навыков. Если любой игрок погибнет в пределах $2 м от вас, на месте его гибели останется Человечина — пища, которую может переварить только Драуг.\n", + "rov_compendium_draugh_title": "Тайны Драугра", + "rov_compendium_draugh_undead_fortitude_passive_poison_can": "[Награда: Масса костей] Стойкость нежити (Пассивное): Яд больше совершенно не действует на вас. Удары по ошеломленным врагам наносят на $1% больше физ. урона, а смерть больше не отнимает опыт навыков. Если любой игрок погибнет в пределах $2 м от вас, на месте его гибели останется Человечина — пища, которую может переварить только Драугр.\n", "rov_compendium_draugh_zombie_ritual_passive_survival_when": "[Награда: Яглут] Обряд зомби (Пассивное выживание): При получении смертельного урона вы не погибаете. Вместо этого вы переходите в призрачное состояние с неуязвимостью ко всему урону, пока ваш эйтр сгорает со скоростью $1 ед./с. Если эйтр иссякнет до вашего спасения, наступит истинная смерть. Ритуал срабатывает не чаще одного раза в $2 мин.\n", "rov_compendium_dvergar_dvergar_s_craft": "Ремесло Дверга\n", "rov_compendium_dvergar_kin_traders_passive_haldor_hildir": "[Награда: Масса костей] Родня торговцев (Пассивное): Хальдор и Хильдир узнают сородича. Их цены для вас снижены на $1%, а выплата за ваши трофеи и охотничьи награды увеличена на $2%.\n", @@ -53,7 +53,7 @@ "rov_compendium_fenrir_cultist_form_now_answers_by": "[Награда: Прародитель] Облик культиста теперь подчиняется как днем, так и ночью, и его можно удерживать сколько угодно.\n", "rov_compendium_fenrir_cultist_form_s_cooldown_falls": "[Награда: Королева] Перезарядка облика культиста снижена до 5 минут (все еще только ночью, длительность 1 минута).\n", "rov_compendium_fenrir_curse_pack": "Проклятие Стаи\n", - "rov_compendium_fenrir_cursed_claws_s_wolf_s": "[Базовое пассивное] Проклятые когти ([K], $1 с): Волчьи лапы, сохраняющиеся в человеческом теле на ограниченное время вместо оружия. Удары голыми руками наносят $2% от урона зрелых когтей (полностью режущий урон), и их сила растет с каждым павшим боссом. Достаньте меч — они исчезнут, вложите в ножны — вернутся, пока не истечет время. Не тратят место в инвентаре. Их нельзя выбросить, передать или украсть, пока они активны — а в зверином облике вместо них работают челюсти.\n", + "rov_compendium_fenrir_cursed_claws_s_wolf_s": "[Базовое пассивное] Проклятые когти ([K], $1 с): Волчьи лапы, сохраняющиеся в человеческом теле на ограниченное время вместо оружия. Удары голыми руками наносят $2% от урона зрелых когтей (полностью рубящий урон), и их сила растет с каждым павшим боссом. Достаньте меч — они исчезнут, вложите в ножны — вернутся, пока не истечет время. Не тратят место в инвентаре. Их нельзя выбросить, передать или украсть, пока они активны — а в зверином облике вместо них работают челюсти.\n", "rov_compendium_fenrir_fenring_form_h_key_night": "[Награда: Матерь] Облик фенринга (клавиша «H», только ночью): Станьте истинным Фенрингом — тяжелые когти, сокрушительный удар в прыжке и мощнейшая из четырех форм на данный момент.\n", "rov_compendium_fenrir_fenring_form_now_answers_by": "[Награда: Королева] Облик фенринга теперь доступен как днем, так и ночью.\n", "rov_compendium_fenrir_g_now_calls_ulv_form": "[Награда: Матерь] Клавиша «G» теперь призывает облик Ульва вместо Волка и доступна и днем, и ночью.\n", @@ -147,7 +147,7 @@ "rov_compendium_sverm_grinding_mandibles_seeds_are_food": "[Награда: Древний] Жерновные жвалы: Семена становятся пищей. Чистые питательные вещества — благословения культурных садов оставьте другим.\n", "rov_compendium_sverm_growth_each_one_costs_that": "Рост: $1 $2, $3 $4, $5 $6. Каждое улучшение требует полного запаса биомассы текущей стадии и открывает следующий ранг существ.\n", "rov_compendium_sverm_hive_market_hammer_counter_raised": "Рынок улья (Молот): торговый прилавок, возводимый в пределах $1 м от гнезда. Все улучшения и войска колонии приобретаются здесь за счет биомассы этого гнезда.\n", - "rov_compendium_sverm_hive_pheromones_no_invertebrate_will": "[Базовое пассивное] Феромоны улья: Ни одно беспозвоночное не нападет на вас: ни пиявки, ни клещи, ни комары смерти, ни искатели, ни пчелы. Массе костей чужды насекомые, и феромоны на нее не действуют.\n", + "rov_compendium_sverm_hive_pheromones_no_invertebrate_will": "[Базовое пассивное] Феромоны улья: Ни одно беспозвоночное не нападет на вас: ни пиявки, ни клещи, ни смертожалы, ни искатели, ни пчелы. Массе костей чужды насекомые, и феромоны на нее не действуют.\n", "rov_compendium_sverm_insect_metabolism_eat_everything_anyone": "[Базовое пассивное] Метаболизм насекомого: Вы можете есть всё, что едят остальные, а мед дает вам вдвое больше пользы. Алхимическая кровь — единственное, к чему вы не притронетесь.\n", "rov_compendium_sverm_metabolic_surge_running_jumping_cost": "[Награда: Эйктюр] Метаболический всплеск: Бег и прыжки расходуют меньше сил, а прыгаете вы гораздо выше.\n", "rov_compendium_sverm_ravager_strain_key_become_seeker": "[Награда: Яглут] Штамм опустошителя (клавиша «$1»): Обернитесь в свирепого искателя-солдата. Когти разят беспощадно, прочность панциря удваивается, но полет исключен. Эта форма рождена для битвы, а не для бегства.\n", @@ -181,7 +181,7 @@ "rov_compendium_trenta_sap_heartwood_conduct_lightning_turn": "Смола и сердцевина древесины проводят молнию и отваживают нежить: вы получаете половинный урон от молнии и духа. Но сухие ветви быстро разгораются, а топор дровосека безжалостен — урон от огня и рубящих атак увеличен в полтора раза. Мясо, рыба, яйца и мед противны вашей натуре; лишь то, что произрастает из земли, дает вам силы, и действует в $1 раз дольше, чем на обычного человека.\n", "rov_compendium_trenta_secrets_heartwood": "Тайны Сердцевины\n", "rov_compendium_trenta_spray_toxic_pollen_bursts_out": "Выброс токсичной пыльцы в радиусе $1 м: каждый союзник внутри исцеляется на $2 ед., а каждый враг отравляется на $3 ед. урона. Перезарядка: $4 с (сокращается до $5 с в облике Муспелля).\n", - "rov_compendium_trenta_stand_still_daylight_roof_over": "Постойте неподвижно под чистым небом при дневном свете в течение $1 с, и корни войдут в почву: последуют $2 тактов исцеления по $3% от макс. здоровья каждый, а также эффект «Отдых» на $4 минут — время действия растет с каждым павшим боссом.\n", + "rov_compendium_trenta_stand_still_daylight_roof_over": "Постойте неподвижно под чистым небом при дневном свете в течение $1 с, и корни войдут в почву: последуют $2 тактов исцеления по $3% от макс. здоровья каждый, а также эффект «Бодрость» на $4 минут — время действия растет с каждым павшим боссом.\n", "rov_compendium_trenta_swamp_has_nothing_left_spoil": "Болотам нечего осквернять в вашем теле. Яд не может навредить вам, эффект сырости не накладывается, а плавание вовсе не расходует выносливость.\n", "rov_compendium_trenta_swarm_hornets_has_made_its": "Рой шершней свил гнездо в вашей кроне. Любой враг, приблизившийся на расстояние ближе $1 м, получает $2 ед. урона ядом и колющими ударами каждые $3 с, пока не отступит или не погибнет.\n", "rov_compendium_trenta_take_shape_young_elder_root": "Примите облик юного Древнего, воплотив ярость корней и терновника. ЛКМ сотрясает землю, нанося $1 ед. урона в круге вокруг вас, а ПКМ выпускает пронзающий корень на $2 ед. урона — мощь обоих приемов зависит от навыка «Без оружия». В этой форме вы по-прежнему можете призывать Purple Rain с уменьшенным временем перезарядки.\n", From 9f11cab70d221f12146518d1726b01ff25451fe2 Mon Sep 17 00:00:00 2001 From: Axibed Date: Thu, 8 Oct 2026 07:57:09 +0200 Subject: [PATCH 006/163] =?UTF-8?q?=D0=9E=D0=B1=D0=BD=D0=BE=D0=B2=D0=B8?= =?UTF-8?q?=D1=82=D1=8C=20JotunnModStub/Translations/Russian/hover.json?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- JotunnModStub/Translations/Russian/hover.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/JotunnModStub/Translations/Russian/hover.json b/JotunnModStub/Translations/Russian/hover.json index b5fc367..bb109f8 100644 --- a/JotunnModStub/Translations/Russian/hover.json +++ b/JotunnModStub/Translations/Russian/hover.json @@ -16,7 +16,7 @@ "rov_hover_dvergar_read_ledger": "\n[$KEY_Use] Прочесть гроссбух", "rov_hover_dvergar_seal_worth_off": "\nваша печать дает скидку $1%", "rov_hover_dvergar_what_queen_left_behind_buys": "\n(оставленное Королевой позволит нанять еще два отряда)", - "rov_hover_fenrir_blood_thin_here_raises_no": "\nкровь здесь жидка - пока она не поднимет фенрира", + "rov_hover_fenrir_blood_thin_here_raises_no": "\nсила крови здесь слаба — фенрира ей пока не пробудить", "rov_hover_fenrir_fenrir": ", фенрир $1/$2", "rov_hover_fenrir_fill_with_meat": "\n[$KEY_Use] Заполнить мясом", "rov_hover_fenrir_meat_wolves_ulv": "мясо $1/$2\nволки $3/$4, ульвы $5/$6", @@ -26,7 +26,7 @@ "rov_hover_skeleton_bone_hand_buy_place_empty": "\n[$KEY_Use] Кость в руке — купить место, пустые руки — двинуть строй", "rov_hover_skeleton_bone_toward_next_places": "\nкостей $1/$2 для следующего из $3 мест", "rov_hover_skeleton_every_place_bought": "\nвсе места заняты", - "rov_hover_skeleton_melee_archers_rotten": "\nближний бой $1/$2 из $3\nлучники $4/$5 из $6\nгнилые $7/$8 из $9", + "rov_hover_skeleton_melee_archers_rotten": "\nближний бой $1/$2 из $3\nлучники $4/$5 из $6\nсгнившие $7/$8 из $9", "rov_hover_skeleton_needs_greater_cursed_skull": " (требуется большой проклятый череп)", "rov_hover_skeleton_next_rises_s": "\nследующий восстанет через $1 с", "rov_hover_sverm_beehives_taken_allowed_range_feed": "$1\n$2Ульев занято $3 из $4 доступных, $5 поблизости\n$6[$KEY_Use] Скормить стопку", From 3c86d48aad9d4434e393d333debaaa6fbe13f7bc Mon Sep 17 00:00:00 2001 From: Axibed Date: Thu, 8 Oct 2026 07:57:46 +0200 Subject: [PATCH 007/163] =?UTF-8?q?=D0=9E=D0=B1=D0=BD=D0=BE=D0=B2=D0=B8?= =?UTF-8?q?=D1=82=D1=8C=20JotunnModStub/Translations/Russian/merchants.jso?= =?UTF-8?q?n?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- JotunnModStub/Translations/Russian/merchants.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/JotunnModStub/Translations/Russian/merchants.json b/JotunnModStub/Translations/Russian/merchants.json index f554511..53129dd 100644 --- a/JotunnModStub/Translations/Russian/merchants.json +++ b/JotunnModStub/Translations/Russian/merchants.json @@ -110,7 +110,7 @@ "rov_sverm_refusal_stage_first": "Сначала гнездо должно развиться до стадии: $1.", "rov_sverm_refusal_working_m": "Улей все еще переваривает предыдущую порцию ($1 мин).", "rov_sverm_refusal_working_s": "Улей все еще переваривает предыдущую порцию ($1 с).", - "rov_sverm_stage_gorgedhive": "Обожравшийся улей", + "rov_sverm_stage_gorgedhive": "Насыщенный улей", "rov_sverm_stage_hivecitadel": "Цитадель улья", "rov_sverm_stage_nestingspire": "Гнездовой шпиль", "rov_troop_dvergar_ash_guard": "Пепельный страж", From 875024e649eca553c95a68905205e67395cbd6e8 Mon Sep 17 00:00:00 2001 From: Axibed Date: Thu, 8 Oct 2026 07:58:42 +0200 Subject: [PATCH 008/163] =?UTF-8?q?=D0=9E=D0=B1=D0=BD=D0=BE=D0=B2=D0=B8?= =?UTF-8?q?=D1=82=D1=8C=20JotunnModStub/Translations/Russian/messages.json?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- JotunnModStub/Translations/Russian/messages.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/JotunnModStub/Translations/Russian/messages.json b/JotunnModStub/Translations/Russian/messages.json index aaf65ef..001e5fe 100644 --- a/JotunnModStub/Translations/Russian/messages.json +++ b/JotunnModStub/Translations/Russian/messages.json @@ -180,7 +180,7 @@ "rov_msg_trenta_root_will_not_take_hold": "Корень не приживется для вас.", "rov_msg_trenta_still_growing_minutes": "Все еще растет. Осталось $1 мин.", "rov_msg_trenta_still_rotting_minutes": "Все еще перегнивает. Осталось $1 мин.", - "rov_msg_trenta_this_one_not_well_nothing": "Этому нездоровится. Ничто не ускорит это.", + "rov_msg_trenta_this_one_not_well_nothing": "Этому ростку нездоровится. Ничто не ускорит его рост.", "rov_msg_trenta_trenta_eat_only_what_grows": "Трента питается лишь тем, что рождено корнями и листвой: никакого мяса, рыбы, яиц или меда.", "rov_msg_trol_answers": "$1 откликается.", "rov_msg_trol_are_already_holding_log": "Вы уже держите бревно!", From a75655d3e5e5231c064416dd2a53bf8f1ddc6c1d Mon Sep 17 00:00:00 2001 From: Axibed Date: Thu, 8 Oct 2026 08:05:10 +0200 Subject: [PATCH 009/163] =?UTF-8?q?=D0=9E=D0=B1=D0=BD=D0=BE=D0=B2=D0=B8?= =?UTF-8?q?=D1=82=D1=8C=20JotunnModStub/Translations/Russian/messages.json?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- JotunnModStub/Translations/Russian/messages.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/JotunnModStub/Translations/Russian/messages.json b/JotunnModStub/Translations/Russian/messages.json index 001e5fe..2e70a33 100644 --- a/JotunnModStub/Translations/Russian/messages.json +++ b/JotunnModStub/Translations/Russian/messages.json @@ -35,7 +35,7 @@ "rov_msg_butler_servant_rises": "Слуга восстает.", "rov_msg_claws_they_are_part_hands": "Они — часть ваших рук.", "rov_msg_core_chose_path_aswid": "Вы избрали путь Асвида.", - "rov_msg_core_chose_path_draugh": "Вы избрали путь Драуга.", + "rov_msg_core_chose_path_draugh": "Вы избрали путь Драугра.", "rov_msg_core_chose_path_dvergar": "Вы избрали путь Дверга.", "rov_msg_core_chose_path_fenrir": "Вы избрали путь Фенрира.", "rov_msg_core_chose_path_furling": "Вы избрали путь Фурлинга.", From a1261af0f1fbbe598926ef1ff0713d5f9d7862b8 Mon Sep 17 00:00:00 2001 From: Axibed Date: Thu, 8 Oct 2026 08:12:25 +0200 Subject: [PATCH 010/163] =?UTF-8?q?=D0=9E=D0=B1=D0=BD=D0=BE=D0=B2=D0=B8?= =?UTF-8?q?=D1=82=D1=8C=20JotunnModStub/Translations/Russian/compendium.js?= =?UTF-8?q?on?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- JotunnModStub/Translations/Russian/compendium.json | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/JotunnModStub/Translations/Russian/compendium.json b/JotunnModStub/Translations/Russian/compendium.json index bc64748..6464233 100644 --- a/JotunnModStub/Translations/Russian/compendium.json +++ b/JotunnModStub/Translations/Russian/compendium.json @@ -2,19 +2,19 @@ "rov_compendium_aswid_always_active_every_form_with": "Активна всегда и в любом облике, не требует зажатия клавиши — только переключение вкл/выкл. Высасывает жизнь в радиусе $1 м днем и $2 м ночью, нанося магический урон, зависящий от навыка «Магия крови», и исцеляя вас на величину нанесенного урона. Враги с запасом здоровья $3% и ниже погибают мгновенно. В человеческом облике аура наносит половинный урон, в облике летучей мыши — полный, а в облике тумана — удвоенный. Аура не отличает торговцев от монстров, поэтому отключайте ее клавишей [I] перед разговором с Хальдором или Хильдир.\n", "rov_compendium_aswid_asmund_passive": "[Награда: Прародитель] Асмунд (Пассивное):", "rov_compendium_aswid_aswid_s_curse": "Проклятие Асвида\n", - "rov_compendium_aswid_bat_form_g_key_night": "[Награда: Эйктюр] Облик мыши (клавиша «G», только ночью): Примите облик летучей мыши.\n", - "rov_compendium_aswid_bat_form_now_answers_by": "[Награда: Древний] Облик мыши теперь доступен как ночью, так и днем.\n", + "rov_compendium_aswid_bat_form_g_key_night": "[Награда: Эйктюр] Облик летучей мыши (клавиша «G», только ночью): Примите облик летучей мыши.\n", + "rov_compendium_aswid_bat_form_now_answers_by": "[Награда: Древний] Облик летучей мыши теперь доступен как ночью, так и днем.\n", "rov_compendium_aswid_benedictus_et_afflictus": "[Базовое пассивное] Benedictus et Afflictus:", - "rov_compendium_aswid_claws_beast_s_grows_blackened": "[Базовое пассивное] Когти зверя ([K], $1 с): На ограниченное время отращивает черные когти вместо оружия. Удары кулаками наносят $2% от урона зрелых когтей (полностью рубящий урон), и их сила растет с каждым поверженным боссом. Если достать меч — когти спрячутся, убрать его — вернутся, пока не истечет таймер. Не занимают ячейку экипировки. Их нельзя выбросить, передать или украсть, пока они активны. В облике мыши или тумана когти недоступны, так как у вас нет рук.\n", + "rov_compendium_aswid_claws_beast_s_grows_blackened": "[Базовое пассивное] Когти зверя ([K], $1 с): На ограниченное время отращивает черные когти вместо оружия. Удары кулаками наносят $2% от урона зрелых когтей (полностью рубящий урон), и их сила растет с каждым поверженным боссом. Если достать меч — когти спрячутся, убрать его — вернутся, пока не истечет таймер. Не занимают ячейку экипировки. Их нельзя выбросить, передать или украсть, пока они активны. В облике летучей мыши или тумана когти недоступны, так как у вас нет рук.\n", "rov_compendium_aswid_dominate_native_interact_key": "[Награда: Яглут] Порабощение (клавиша взаимодействия):", "rov_compendium_aswid_eclipse_j_key_day_only": "[Награда: Яглут] Затмение (клавиша «J», только днем):", "rov_compendium_aswid_freezing_blood_passive": "[Награда: Матерь] Ледяная кровь (Пассивное):", - "rov_compendium_aswid_gain_permanent_immunity_freezing_status": "Вы получаете постоянный иммунитет к эффекту переохлаждения/замерзания (горы/снежные бури) и к урону от яда.\n", + "rov_compendium_aswid_gain_permanent_immunity_freezing_status": "Вы получаете постоянный иммунитет к эффекту «Замерзание» (горы/снежные бури) и к урону от яда.\n", "rov_compendium_aswid_hair_beard_turn_as_dark": "Ваши волосы и борода становятся черными, как бездна. Вы становитесь выше на 10% и получаете фиксированную прибавку +$1 к физическому урону.\n", "rov_compendium_aswid_second_cast_that_forces_night": "Сотворение в течение $1 с опускает ночную тьму вокруг вас на $2 с, позволяя получать ночные бонусы прямо под солнцем. Если уже наступила ночь, способность просто уйдет на перезарядку. Перезарядка: $3 мин.\n", "rov_compendium_aswid_sense_every_untamed_creature_within": "Вы чувствуете любое неприрученное существо в радиусе $1 м, подсвечивая его характерным свечением.\n", "rov_compendium_aswid_superhuman_senses_passive": "[Награда: Матерь] Сверхчеловеческие чувства (Пассивное):", - "rov_compendium_aswid_take_no_fall_damage_physical": "Вы не получаете урона от падения, а убийства в ближнем бою автоматически пожирают съедобных врагов (Vae Victis), принося опыт магии крови. Ваши физические характеристики растут с каждым убитым боссом: +$1 к броне, +$2 к урону, +$3% к скорости и прыжку, и +$4% вампиризма при физ. атаках. Все эти бонусы удваиваются ночью. Вы можете использовать предметы магии крови с бесконечным эйтром, а навык «Магия крови» качается в $5 раз быстрее.\n", + "rov_compendium_aswid_take_no_fall_damage_physical": "Вы не получаете урона от падения, а убийства в ближнем бою автоматически пожирают съедобных врагов (Vae Victis), принося опыт магии крови. Ваши физические характеристики растут с каждым убитым боссом: +$1 к броне, +$2 к урону, +$3% к скорости и прыжку, и +$4% вампиризма при физ. атаках. Все эти бонусы удваиваются ночью. Вы можете использовать предметы магии крови с бесконечным эйтром, а навык «Магия крови» растет в $5 раз быстрее.\n", "rov_compendium_aswid_tame_u_key_asksvin_join": "[Награда: Прародитель] Приручение (клавиша «U»): Пеплозавры добавляются в список доступных для приручения.\n", "rov_compendium_aswid_tame_u_key_lox_join": "[Награда: Яглут] Приручение (клавиша «U»): Быкоящеры добавляются в список доступных для приручения.\n", "rov_compendium_aswid_tame_u_key_tame_boar": "[Награда: Эйктюр] Приручение (клавиша «U»): Мгновенно приручает кабана под прицелом.\n", @@ -28,7 +28,7 @@ "rov_compendium_draugh_draugh_s_awakening": "Пробуждение Драугра\n", "rov_compendium_draugh_grave_chill_passive_parry_frost": "[Награда: Матерь] Могильный холод (Пассивное/Парирование): Мороз больше не может навредить вам. Успешное парирование также высвобождает волну холода, наносящую $1 урона от мороза и отталкивающую всё в радиусе $2 м от вас. У волны отдельная перезарядка в $3 с, независимая от всплеска яда «Гниющего клинка», который срабатывает при каждом парировании.\n", "rov_compendium_draugh_rotting_edge_passive_parry_physical": "[Награда: Древний] Гниющий клинок (Пассивное/Парирование): Ваши физические атаки пропитаны болотным тленом, добавляя урон ядом в размере $1% от нанесенного физ. урона. Успешное парирование также окатывает парированного врага $2 ед. урона ядом.\n", - "rov_compendium_draugh_slowly_we_rot_passive_being": "[Награда: Эйктюр] Slowly We Rot (Пассивное): Статус «Сырость» больше не снижает восстановление выносливости, а вместо этого исцеляет вас — здоровье восстанавливается на $1% быстрее, пока вы мокрые или плывете.\n", + "rov_compendium_draugh_slowly_we_rot_passive_being": "[Награда: Эйктюр] Slowly We Rot (Пассивное): Статус «Сырость» больше не снижает восстановление выносливости, а вместо этого исцеляет вас — здоровье восстанавливается на $1% быстрее, пока вы мокры или плывете.\n", "rov_compendium_draugh_steal_their_breath_execution_while": "[Награда: Прародитель] Steal Their Breath (Казнь): Находясь в призрачном состоянии выживания «Обряда зомби», нанесение смертельного удара любому врагу мгновенно восстановит $1% вашего максимального здоровья, остановит утечку эйтра и вернет вас к полноценной жизни.\n", "rov_compendium_draugh_swarm_terror_retaliation_whenever_are": "[Награда: Королева] Swarm of Terror (Возмездие): Каждый раз при получении удара в ближнем бою вы автоматически призываете $1 выводков искателя для защиты. Они живут $2 с. Перезарядка между призывами: $3 с.\n", "rov_compendium_draugh_title": "Тайны Драугра", @@ -37,7 +37,7 @@ "rov_compendium_dvergar_dvergar_s_craft": "Ремесло Дверга\n", "rov_compendium_dvergar_kin_traders_passive_haldor_hildir": "[Награда: Масса костей] Родня торговцев (Пассивное): Хальдор и Хильдир узнают сородича. Их цены для вас снижены на $1%, а выплата за ваши трофеи и охотничьи награды увеличена на $2%.\n", "rov_compendium_dvergar_mining_affinity_passive_pickaxe_answers": "[Награда: Эйктюр] Сродство с киркой (Пассивное): Кирка подчиняется вам беспрекословно. Рудные жилы поддаются быстрее, требуют меньше выносливости и порой дают больше руды, чем должны.\n", - "rov_compendium_dvergar_runic_overcharge_key_spend_eitr": "[Награда: Прародитель] Руническая перегрузка (клавиша «$1»): Потратьте $2 эйтра, чтобы зарядить руны. Ваш следующий удар излюбленным оружием нанесет урон с силой в $3x. Удерживайте заряд не дольше $4 с, иначе руны рассеются впустую.\n", + "rov_compendium_dvergar_runic_overcharge_key_spend_eitr": "[Награда: Прародитель] Руническая перегрузка (клавиша «$1»): Потратьте $2 эйтра, чтобы зарядить руны. Ваш следующий удар излюбленным оружием нанесет урон с $3-кратной силой. Удерживайте заряд не дольше $4 с, иначе руны рассеются впустую.\n", "rov_compendium_dvergar_runic_ping_key_spend_eitr": "[Награда: Яглут] Рунический эхолокатор (клавиша «$1»): Потратьте $2 эйтра, чтобы послать импульс сквозь толщу камня. На $3 с каждая рудная жила и каждый скрытый враг в радиусе $4 метров подсветятся только для вас.\n", "rov_compendium_dvergar_runic_spark_runes_blood_earth": "[Базовое пассивное] Руническая искра: Руны в вашей крови заземляются через каждую цель, по которой вы бьете. Каждый нанесенный удар несет +$1 урона молнией — этот бонус растет по мере гибели боссов.\n", "rov_compendium_dvergar_small_stubborn_stand_shorter_than": "[Базовое пассивное] Мал да удал: Вы на $1% ниже человека и обладаете базовым запасом здоровья на $2 ед. меньше. Капюшон дверга сросся с вами навечно — надевайте любой шлем и сохраняйте все его показатели защиты, но руны всегда будут выдавать в вас дитя глубин.\n", From d86609acef0a1c05df5ba808dc922207faad6598 Mon Sep 17 00:00:00 2001 From: Axibed Date: Thu, 8 Oct 2026 08:13:43 +0200 Subject: [PATCH 011/163] =?UTF-8?q?=D0=9E=D0=B1=D0=BD=D0=BE=D0=B2=D0=B8?= =?UTF-8?q?=D1=82=D1=8C=20JotunnModStub/Translations/Russian/hover.json?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- JotunnModStub/Translations/Russian/hover.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/JotunnModStub/Translations/Russian/hover.json b/JotunnModStub/Translations/Russian/hover.json index bb109f8..3ebe66d 100644 --- a/JotunnModStub/Translations/Russian/hover.json +++ b/JotunnModStub/Translations/Russian/hover.json @@ -26,7 +26,7 @@ "rov_hover_skeleton_bone_hand_buy_place_empty": "\n[$KEY_Use] Кость в руке — купить место, пустые руки — двинуть строй", "rov_hover_skeleton_bone_toward_next_places": "\nкостей $1/$2 для следующего из $3 мест", "rov_hover_skeleton_every_place_bought": "\nвсе места заняты", - "rov_hover_skeleton_melee_archers_rotten": "\nближний бой $1/$2 из $3\nлучники $4/$5 из $6\nсгнившие $7/$8 из $9", + "rov_hover_skeleton_melee_archers_rotten": "\nближний бой $1/$2 из $3\nлучники $4/$5 из $6\nсгнившие $7/$8 из $9", "rov_hover_skeleton_needs_greater_cursed_skull": " (требуется большой проклятый череп)", "rov_hover_skeleton_next_rises_s": "\nследующий восстанет через $1 с", "rov_hover_sverm_beehives_taken_allowed_range_feed": "$1\n$2Ульев занято $3 из $4 доступных, $5 поблизости\n$6[$KEY_Use] Скормить стопку", From f1fbebb8c7f7088079586bc45293a49235ce96ab Mon Sep 17 00:00:00 2001 From: Axibed Date: Thu, 8 Oct 2026 08:14:18 +0200 Subject: [PATCH 012/163] =?UTF-8?q?=D0=9E=D0=B1=D0=BD=D0=BE=D0=B2=D0=B8?= =?UTF-8?q?=D1=82=D1=8C=20JotunnModStub/Translations/Russian/items.json?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- JotunnModStub/Translations/Russian/items.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/JotunnModStub/Translations/Russian/items.json b/JotunnModStub/Translations/Russian/items.json index 7181215..c94f563 100644 --- a/JotunnModStub/Translations/Russian/items.json +++ b/JotunnModStub/Translations/Russian/items.json @@ -64,7 +64,7 @@ "rov_item_furling_tinflax_desc": "Лен, выросший на отравленной оловом почве и впитавший ее суть. Для ткани непригоден — измельчите и увидите сами.", "rov_item_furling_tinflax_name": "Оловянный лен", "rov_item_skadi_greaterfrostheart_desc": "Холод куда более древний, чем дыхание ледяных пиков. Культисты торгуют им, но не скажут, где ведут раскопки.", - "rov_item_skadi_greaterfrostheart_name": "Большое сердце холода", + "rov_item_skadi_greaterfrostheart_name": "Большое сердце мороза", "rov_item_skeleton_cursedskull_desc": "Череп, ведущий неустанный счет. Опустите его на землю, и мертвые отзовутся на зов.", "rov_item_skeleton_cursedskull_name": "Проклятый череп", "rov_item_skeleton_greatercursedskull_desc": "Старше прочих, и его счет куда длиннее. Куча останков с таким черепом поднимает и гниющих мертвецов.", From bb1ca579247ab86cd1f8a7287518777bf0c40b0a Mon Sep 17 00:00:00 2001 From: kanym Date: Tue, 13 Oct 2026 20:00:03 +0200 Subject: [PATCH 013/163] chore(release): v1.5.10 - Skeleton body switch for player model mods New client-side option Skeleton - Visuals -> Body Model Enabled. Off, a Skeleton takes the human branch of the VisEquipment postfix: vanilla body on, no bone meshes, eye glow, jaw correction or skull flame, and the helmet is left alone. Requested by players using EnhancedValheimVRM, where the bones floated around the replacement model. README: New in block for v1.5.10, changelog entry (also the Russian fixes since 1.5.9), and a line under the Skeleton features. --- JotunnModStub/Package/manifest.json | 2 +- JotunnModStub/RacesOfValheim.cs | 2 +- JotunnModStub/Skeleton/SkeletonConfig.cs | 3 +++ JotunnModStub/Skeleton/SkeletonJawFix.cs | 5 +++-- JotunnModStub/Skeleton/SkeletonPatches.cs | 4 +++- JotunnModStub/Skeleton/SkeletonRace.cs | 12 ++++++++---- JotunnModStub/Skeleton/SkeletonVisuals.cs | 10 ++++++++++ JotunnModStub/ZdoVisualSync.cs | 9 ++++++--- README.md | 9 +++++++-- manifest.json | 2 +- 10 files changed, 43 insertions(+), 15 deletions(-) diff --git a/JotunnModStub/Package/manifest.json b/JotunnModStub/Package/manifest.json index 8b25e6f..47424f1 100644 --- a/JotunnModStub/Package/manifest.json +++ b/JotunnModStub/Package/manifest.json @@ -1,7 +1,7 @@ { "name": "RacesOfValheim", "description": "A Valheim mod that adds ten custom playable races (Aswid, Draugh, Dvergar, Fenrir, Furling, Skadi, Skeleton, Sverm, Trenta, Trol) each with unique abilities, traits, race stations and a deep boss-driven progression system.", - "version_number": "1.5.9", + "version_number": "1.5.10", "website_url": "", "dependencies": [ "denikson-BepInExPack_Valheim-5.4.2333", diff --git a/JotunnModStub/RacesOfValheim.cs b/JotunnModStub/RacesOfValheim.cs index fe1cebb..6e826c6 100644 --- a/JotunnModStub/RacesOfValheim.cs +++ b/JotunnModStub/RacesOfValheim.cs @@ -15,7 +15,7 @@ namespace RacesOfValheim { public const string PluginGUID = "com.nandor.racesofvalheim"; public const string PluginName = "Races Of Valheim"; - public const string PluginVersion = "1.5.9"; + public const string PluginVersion = "1.5.10"; private readonly Harmony harmony = new Harmony(PluginGUID); diff --git a/JotunnModStub/Skeleton/SkeletonConfig.cs b/JotunnModStub/Skeleton/SkeletonConfig.cs index a31f1a9..c6b8ba6 100644 --- a/JotunnModStub/Skeleton/SkeletonConfig.cs +++ b/JotunnModStub/Skeleton/SkeletonConfig.cs @@ -41,6 +41,7 @@ namespace RacesOfValheim // ─── Visuals ─────────────────────────────────────────────────────────── public static ConfigEntry HeadFireVFXEnabled; + public static ConfigEntry BodyModelEnabled; public static void Bind(ConfigFile config) { @@ -71,6 +72,8 @@ namespace RacesOfValheim const string visuals = "Skeleton - Visuals"; HeadFireVFXEnabled = config.Bind(visuals, "Head Fire VFX Enabled", true, new ConfigDescription("Whether the burning-skull effect (worn from tier 5+) renders at all. A client-side preference: disabling it stops you from seeing it on yourself and on every other skeleton you look at, but does not change what other players see.")); + BodyModelEnabled = config.Bind(visuals, "Body Model Enabled", true, + new ConfigDescription("Whether Skeleton players wear the skeleton body. Turn it off if you use a player model mod (EnhancedValheimVRM and the like): Skeletons then keep the vanilla viking body, so the replacement model shows without bones clipping through it. Abilities are unchanged. Client-side, like the option above: it applies to every Skeleton you see, yourself included, and changes nothing for other players.")); } } } diff --git a/JotunnModStub/Skeleton/SkeletonJawFix.cs b/JotunnModStub/Skeleton/SkeletonJawFix.cs index 8f9860d..d96c8c5 100644 --- a/JotunnModStub/Skeleton/SkeletonJawFix.cs +++ b/JotunnModStub/Skeleton/SkeletonJawFix.cs @@ -62,10 +62,11 @@ namespace RacesOfValheim Transform jaw = ResolveJaw(); if (jaw == null || jaw.parent == null) return; - if (!SkeletonVisuals.IsSkeletonPlayer(m_player)) + if (!SkeletonVisuals.ShowsSkeletonBody(m_player)) { // Nothing rewrites this bone on its own, so a player who stops being a Skeleton - // would otherwise keep wearing the correction on their human face. + // (or switches the skeleton body off) would otherwise keep wearing the correction + // on their human face. if (m_applied) { jaw.localPosition = m_baseLocalPosition; diff --git a/JotunnModStub/Skeleton/SkeletonPatches.cs b/JotunnModStub/Skeleton/SkeletonPatches.cs index 0937e37..461fa75 100644 --- a/JotunnModStub/Skeleton/SkeletonPatches.cs +++ b/JotunnModStub/Skeleton/SkeletonPatches.cs @@ -254,7 +254,9 @@ namespace RacesOfValheim // before it could find out it was looking at a Skeleton. string race = SkeletonVisuals.GetPlayerRace(p); - if (race == SkeletonVisuals.RaceId) + // With "Body Model Enabled" off a Skeleton takes the human branch below, the same + // as any other race, so the toggle also works live: the next refresh swaps back. + if (race == SkeletonVisuals.RaceId && SkeletonConfig.BodyModelEnabled.Value) { if (__instance.m_bodyModel != null) { diff --git a/JotunnModStub/Skeleton/SkeletonRace.cs b/JotunnModStub/Skeleton/SkeletonRace.cs index 78aebe6..1895ed5 100644 --- a/JotunnModStub/Skeleton/SkeletonRace.cs +++ b/JotunnModStub/Skeleton/SkeletonRace.cs @@ -323,9 +323,13 @@ namespace RacesOfValheim VisEquipment currentVis = Player.m_localPlayer.GetComponent(); if (currentVis != null) { - // Hide Helmets (Valheim uses singular GameObject for helmet) - var helmetObj = HarmonyLib.Traverse.Create(currentVis).Field("m_helmetItemInstance").Value; - SkeletonVisuals.SetEquipmentPieceHidden(helmetObj, true); + // Hide Helmets (Valheim uses singular GameObject for helmet). Only over a skull: + // a viking body wears its helmet, and the VisEquipment postfix puts it back. + if (SkeletonConfig.BodyModelEnabled.Value) + { + var helmetObj = HarmonyLib.Traverse.Create(currentVis).Field("m_helmetItemInstance").Value; + SkeletonVisuals.SetEquipmentPieceHidden(helmetObj, true); + } // Scale Body Armor (Chest, Legs, Shoulder) by 5% string[] armorFields = { "m_chestItemInstances", "m_legItemInstances", "m_shoulderItemInstances" }; @@ -440,7 +444,7 @@ namespace RacesOfValheim } // Flames on the skull, worn with the fire-tier model and nothing else. - headFlame.Apply(Player.m_localPlayer, SkeletonConfig.HeadFireVFXEnabled.Value && SkeletonVisuals.GetModel(Player.m_localPlayer, state) == SkeletonProgression.FireModel); + headFlame.Apply(Player.m_localPlayer, SkeletonConfig.HeadFireVFXEnabled.Value && SkeletonConfig.BodyModelEnabled.Value && SkeletonVisuals.GetModel(Player.m_localPlayer, state) == SkeletonProgression.FireModel); if (rules.FireAura) { diff --git a/JotunnModStub/Skeleton/SkeletonVisuals.cs b/JotunnModStub/Skeleton/SkeletonVisuals.cs index 18ada8b..e91963c 100644 --- a/JotunnModStub/Skeleton/SkeletonVisuals.cs +++ b/JotunnModStub/Skeleton/SkeletonVisuals.cs @@ -49,6 +49,16 @@ namespace RacesOfValheim public static bool IsSkeletonPlayer(Player player) => GetPlayerRace(player) == RaceId; + /// + /// Whether this client draws the skeleton's bones on this player. False for every + /// non-Skeleton, and for every Skeleton when "Body Model Enabled" is off: model-replacement + /// mods (EnhancedValheimVRM and the like) hide the vanilla body and draw their own, so the + /// borrowed bones ended up floating around the replacement model. With the option off the + /// Skeleton keeps every ability and only looks like a plain viking. + /// + public static bool ShowsSkeletonBody(Player player) => + SkeletonConfig.BodyModelEnabled.Value && IsSkeletonPlayer(player); + /// /// Fully hides (or restores) one equipped item instance - a helmet, typically. /// diff --git a/JotunnModStub/ZdoVisualSync.cs b/JotunnModStub/ZdoVisualSync.cs index 0df6988..4f1326f 100644 --- a/JotunnModStub/ZdoVisualSync.cs +++ b/JotunnModStub/ZdoVisualSync.cs @@ -128,8 +128,11 @@ namespace RacesOfValheim vis.SetBeardItem(0); // Hide Helmet - var helmetObj = HarmonyLib.Traverse.Create(vis).Field("m_helmetItemInstance").Value; - SkeletonVisuals.SetEquipmentPieceHidden(helmetObj, true); + if (SkeletonConfig.BodyModelEnabled.Value) + { + var helmetObj = HarmonyLib.Traverse.Create(vis).Field("m_helmetItemInstance").Value; + SkeletonVisuals.SetEquipmentPieceHidden(helmetObj, true); + } // Scale Body Armor string[] armorFields = { "m_chestItemInstances", "m_legItemInstances", "m_shoulderItemInstances" }; @@ -165,7 +168,7 @@ namespace RacesOfValheim // The burning skull, grown locally for whoever we are looking at. The tier is on the // ZDO, so this client can work out for itself whether they should be alight. - m_skeletonHeadFlame.Apply(m_player, SkeletonConfig.HeadFireVFXEnabled.Value && SkeletonVisuals.GetModel(m_player, state) == SkeletonProgression.FireModel); + m_skeletonHeadFlame.Apply(m_player, SkeletonConfig.HeadFireVFXEnabled.Value && SkeletonConfig.BodyModelEnabled.Value && SkeletonVisuals.GetModel(m_player, state) == SkeletonProgression.FireModel); // Apply Scale Vector3 targetScale = rules.ScaleMultiplier; diff --git a/README.md b/README.md index 39865d8..741c132 100644 --- a/README.md +++ b/README.md @@ -15,9 +15,9 @@ Support the mod: [Patreon — NandorTheModder](https://www.patreon.com/c/NandorT --- -## New in v1.5.9 +## New in v1.5.10 -Skeletons can laugh: type /evillaugh. The Furling's fire bonus now covers crossbow bolts, and a crossbow in hand no longer fires on every attack while you are transformed. Full details in the [changelog](#v159). +Using a player model mod such as EnhancedValheimVRM? Turn off `Skeleton - Visuals` → `Body Model Enabled` and Skeletons keep the vanilla body, so no bones clip through your model. Full details in the [changelog](#v1510). --- @@ -30,6 +30,7 @@ Skeletons can laugh: type /evillaugh. The Furling's fire bonus now covers crossb - **Stamina-less Combat:** Skeletons use no stamina and do not have a stamina bar. - **Undead Diet:** Cannot eat normal food. Max health increases automatically as you defeat bosses to make up for lack of food buffs. - **Lit Sockets:** Your skull carries the eye lights of the creature your tier is built from, in that creature's own colour — so they change as the body does. +- **Body Model switch:** with a player model mod (EnhancedValheimVRM and the like), set `Skeleton - Visuals` → `Body Model Enabled` to off and Skeletons keep the vanilla body. Abilities stay the same. ### 2. Skadi ![Skadi1](https://wiki.aledanidev.ovh/assets/images/skadi1.gif) @@ -447,6 +448,10 @@ Both halves have an off switch under `Factions` in Configuration Manager: **Fact ## Changelog +### v1.5.10 +- **New - Skeleton body switch for player model mods:** with EnhancedValheimVRM or another model replacer, the skeleton's bones stayed on screen and floated around the new model. Set `Skeleton - Visuals` → `Body Model Enabled` to off and Skeletons keep the vanilla body: no bones, eye lights or skull flames, and the helmet shows. Abilities don't change. The setting is client-side, so it applies to every Skeleton you see and changes nothing for other players. The race strips hair and beard, so the vanilla body is bald, and the auto-resurrection still shows the skeleton for the few seconds it climbs out of the ground. Thanks to the players who reported it and tested the fix. +- **Fix - Russian translation:** corrections to several Russian texts, by Axibed. + ### v1.5.9 - **New - /evillaugh (Skeleton):** the Skeleton throws its head back, clacks its jaw, shakes its shoulders and punches both fists into the air for four seconds. Everyone nearby sees it. - **Change - Furling fire bolts:** the Wickerman's fire damage now also applies to crossbow bolts, not only to arrows. diff --git a/manifest.json b/manifest.json index 8b25e6f..47424f1 100644 --- a/manifest.json +++ b/manifest.json @@ -1,7 +1,7 @@ { "name": "RacesOfValheim", "description": "A Valheim mod that adds ten custom playable races (Aswid, Draugh, Dvergar, Fenrir, Furling, Skadi, Skeleton, Sverm, Trenta, Trol) each with unique abilities, traits, race stations and a deep boss-driven progression system.", - "version_number": "1.5.9", + "version_number": "1.5.10", "website_url": "", "dependencies": [ "denikson-BepInExPack_Valheim-5.4.2333", From 65b488b5dc841592dc75bbecd8a4dea62587d80f Mon Sep 17 00:00:00 2001 From: kanym Date: Wed, 14 Oct 2026 14:12:50 +0200 Subject: [PATCH 014/163] feat(trol): skin and hair colour pickers in Trol - Appearance Two Color entries, Skin Color and Hair Color (hair and beard), defaulting to the old peacock blue and golden blonde so no Trol changes on update. Each Trol publishes its choice on its own ZDO and every client paints that player with it; a Trol on an older build publishes nothing and shows the defaults. The menu preview, with no ZDO, reads the local config. The section is kept local by ConfigSync. README: New in block, Trol features line and a 1.5.10 changelog entry. --- JotunnModStub/ConfigSync.cs | 1 + JotunnModStub/Trol/TrolConfig.cs | 15 +++++++++++ JotunnModStub/Trol/TrolPatches.cs | 45 +++++++++++++++++++++++++------ README.md | 4 ++- 4 files changed, 56 insertions(+), 9 deletions(-) diff --git a/JotunnModStub/ConfigSync.cs b/JotunnModStub/ConfigSync.cs index fb38b9c..996168a 100644 --- a/JotunnModStub/ConfigSync.cs +++ b/JotunnModStub/ConfigSync.cs @@ -31,6 +31,7 @@ namespace RacesOfValheim "Skeleton - Visuals", "Sverm - Dorsal Spines", "Sverm - Emberform", + "Trol - Appearance", "War Vulture - Model", "War Vulture - Interface", }; diff --git a/JotunnModStub/Trol/TrolConfig.cs b/JotunnModStub/Trol/TrolConfig.cs index ffca8af..2a152ae 100644 --- a/JotunnModStub/Trol/TrolConfig.cs +++ b/JotunnModStub/Trol/TrolConfig.cs @@ -59,8 +59,23 @@ namespace RacesOfValheim // ─── Farming ─────────────────────────────────────────────────────────── public static ConfigEntry UnarmedFarmingDamageBonusPerState; + // ─── Appearance ──────────────────────────────────────────────────────── + public static ConfigEntry SkinColor; + public static ConfigEntry HairColor; + + // The colours every Trol wore before these became settings. Also what a Trol on an older + // build of the mod shows as, since that build publishes no colour of its own. + public static readonly Color DefaultSkinColor = new Color(0.1f, 0.6f, 0.7f, 1f); + public static readonly Color DefaultHairColor = new Color(0.9f, 0.8f, 0.4f, 1f); + public static void Bind(ConfigFile config) { + const string appearance = "Trol - Appearance"; + SkinColor = config.Bind(appearance, "Skin Color", DefaultSkinColor, + new ConfigDescription("Your Trol's skin. Other players see it too. The game multiplies it with the skin texture, so it comes out a little darker than the swatch. For the look of Valheim's own trolls try 7FA8C9.")); + HairColor = config.Bind(appearance, "Hair Color", DefaultHairColor, + new ConfigDescription("Your Trol's hair and beard. Other players see it too.")); + const string keybinds = "Trol - Keybinds"; ThrowRockKey = config.Bind(keybinds, "Throw Rock", new KeyboardShortcut(KeyCode.G), new ConfigDescription("Throws a rock (or the log you're holding), tier 3+.")); diff --git a/JotunnModStub/Trol/TrolPatches.cs b/JotunnModStub/Trol/TrolPatches.cs index 68007df..0d9f5c2 100644 --- a/JotunnModStub/Trol/TrolPatches.cs +++ b/JotunnModStub/Trol/TrolPatches.cs @@ -6,8 +6,23 @@ namespace RacesOfValheim [HarmonyPatch(typeof(VisEquipment), "UpdateColors")] public static class TrolSkinColorPatch { - // Golden blonde hair - private static readonly Color HairColor = new Color(0.9f, 0.8f, 0.4f, 1f); + // Each Trol picks their own colours in Trol - Appearance and publishes them here (see + // Trol_PlayerUpdate_Patch), so everyone sees the colours that player chose. Stored without + // alpha: _SkinColor ignores it. + public const string SkinColorKey = "RacesOfValheim_TrolSkinColor"; + public const string HairColorKey = "RacesOfValheim_TrolHairColor"; + + private static Vector3 ToVec3(Color c) => new Vector3(c.r, c.g, c.b); + private static Color ToColor(Vector3 v) => new Color(v.x, v.y, v.z, 1f); + + /// Puts the local player's chosen colours on their ZDO. Only the owner writes. + public static void Publish(ZDO zdo) + { + Vector3 skin = ToVec3(TrolConfig.SkinColor.Value); + Vector3 hair = ToVec3(TrolConfig.HairColor.Value); + if (zdo.GetVec3(SkinColorKey, Vector3.negativeInfinity) != skin) zdo.Set(SkinColorKey, skin); + if (zdo.GetVec3(HairColorKey, Vector3.negativeInfinity) != hair) zdo.Set(HairColorKey, hair); + } public static void Postfix(VisEquipment __instance) { @@ -28,25 +43,38 @@ namespace RacesOfValheim if (race != "Trol") return; - // Apply skin, hair, beard colors here... + // The colours this Trol published. A Trol on an older build publishes none and keeps the + // defaults; with no ZDO at all (the main-menu preview) it is the local player's own + // character, so the local settings are the right answer. + Color skinColor, hairColor; + if (nview != null && nview.IsValid()) + { + ZDO zdo = nview.GetZDO(); + skinColor = ToColor(zdo.GetVec3(SkinColorKey, ToVec3(TrolConfig.DefaultSkinColor))); + hairColor = ToColor(zdo.GetVec3(HairColorKey, ToVec3(TrolConfig.DefaultHairColor))); + } + else + { + skinColor = TrolConfig.SkinColor.Value; + hairColor = TrolConfig.HairColor.Value; + } + if (__instance.m_bodyModel != null && __instance.m_bodyModel.material != null) { - // Peacock blue (deep greenish-blue) - Color trolColor = new Color(0.1f, 0.6f, 0.7f, 1f); - __instance.m_bodyModel.material.SetColor("_SkinColor", trolColor); + __instance.m_bodyModel.material.SetColor("_SkinColor", skinColor); } // Hair 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", HairColor); + if (r.material != null) r.material.SetColor("_SkinColor", hairColor); // Beard 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", HairColor); + if (r.material != null) r.material.SetColor("_SkinColor", hairColor); } } @@ -128,6 +156,7 @@ namespace RacesOfValheim { nview.GetZDO().Set(StateKey, state); nview.GetZDO().Set(TrueFormKey, isTrueFormActive); + if (race == "Trol") TrolSkinColorPatch.Publish(nview.GetZDO()); } } else diff --git a/README.md b/README.md index 741c132..68d1e8d 100644 --- a/README.md +++ b/README.md @@ -17,7 +17,7 @@ Support the mod: [Patreon — NandorTheModder](https://www.patreon.com/c/NandorT ## New in v1.5.10 -Using a player model mod such as EnhancedValheimVRM? Turn off `Skeleton - Visuals` → `Body Model Enabled` and Skeletons keep the vanilla body, so no bones clip through your model. Full details in the [changelog](#v1510). +Using a player model mod such as EnhancedValheimVRM? Turn off `Skeleton - Visuals` → `Body Model Enabled` and Skeletons keep the vanilla body, so no bones clip through your model. Trols can pick their own skin and hair colour under `Trol - Appearance`. Full details in the [changelog](#v1510). --- @@ -72,6 +72,7 @@ Using a player model mod such as EnhancedValheimVRM? Turn off `Skeleton - Visual - **Immense Strength:** Increased carry weight; armor scales up as you defeat bosses. - **Rock Throwing:** Hurl huge boulders at enemies. - **Tree Weaponry:** At higher tiers, True Form lets you rip logs and wield them as weapons or throw them. +- **Your Own Colours:** pick your skin and hair colour under `Trol - Appearance`. Other players see them too. ### 7. Draugh - **Born Dead, Buried Alive:** Undead warrior: resistant to physical/poison, weak to fire/spirit. @@ -450,6 +451,7 @@ Both halves have an off switch under `Factions` in Configuration Manager: **Fact ### v1.5.10 - **New - Skeleton body switch for player model mods:** with EnhancedValheimVRM or another model replacer, the skeleton's bones stayed on screen and floated around the new model. Set `Skeleton - Visuals` → `Body Model Enabled` to off and Skeletons keep the vanilla body: no bones, eye lights or skull flames, and the helmet shows. Abilities don't change. The setting is client-side, so it applies to every Skeleton you see and changes nothing for other players. The race strips hair and beard, so the vanilla body is bald, and the auto-resurrection still shows the skeleton for the few seconds it climbs out of the ground. Thanks to the players who reported it and tested the fix. +- **New - Trol skin and hair colour:** `Trol - Appearance` has a colour picker for the skin and one for the hair and beard. Each Trol picks their own and every player sees them. The defaults are the old peacock blue and golden blonde, so nobody's Trol changes after the update. For the blue-grey of Valheim's own trolls, try `7FA8C9`. A Trol on an older version of the mod shows the defaults to everyone else. Thanks to the player who suggested it. - **Fix - Russian translation:** corrections to several Russian texts, by Axibed. ### v1.5.9 From d5c2d58636ae37167642310ee6fea0fa1fb31aa3 Mon Sep 17 00:00:00 2001 From: kanym Date: Wed, 14 Oct 2026 16:40:27 +0200 Subject: [PATCH 015/163] fix(resetrace): drop every form and every mod status effect on reset ResetRace now undoes each race's form on the spot before it touches status effects: Aswid bat and mist, Fenrir, Skadi drake, Trol True Form, Trenta Muspell and Sverm Ravager. Each race gets a HardResetForReset that stops the form's coroutine, so a transform caught mid-gesture can't finish after the reset and a revert can't hand out its cooldown after the sweep. The hand-written status effect list is gone. The reset now removes everything the mod registers through Jotunn (ModRegistry), which covers the True Form and its cooldowns, Bat and Mist Form, the Skeleton resurrect cooldown and Skadi's ability cooldowns. It also puts the player and the Visual back to scale 1, clears the Sverm's static Ravager cooldown and the Trol's wasTrueFormActive flag, and prints what it removed to the console and the BepInEx log. --- JotunnModStub/Aswid/AswidRace.cs | 71 ++++++++++++++++++++++--- JotunnModStub/Fenrir/FenrirRace.cs | 58 ++++++++++++++++++-- JotunnModStub/RacesOfValheim.cs | 61 +++++++++++++++------ JotunnModStub/Skadi/SkadiRace.cs | 57 ++++++++++++++++++-- JotunnModStub/Sverm/SvermRavagerForm.cs | 34 +++++++++++- JotunnModStub/Trenta/TrentaMuspell.cs | 47 ++++++++++++++-- JotunnModStub/Trol/TrolRace.cs | 45 +++++++++++++++- 7 files changed, 336 insertions(+), 37 deletions(-) diff --git a/JotunnModStub/Aswid/AswidRace.cs b/JotunnModStub/Aswid/AswidRace.cs index e8bb4c7..b95daff 100644 --- a/JotunnModStub/Aswid/AswidRace.cs +++ b/JotunnModStub/Aswid/AswidRace.cs @@ -463,7 +463,7 @@ namespace RacesOfValheim if (EnvMan.instance != null && EnvMan.IsDay() && !isTransformingSequence && Player.m_localPlayer.GetSEMan().HaveStatusEffect("SE_MistForm".GetStableHashCode())) { - StartCoroutine(RevertMistFormRoutine()); + RunFormRoutine(RevertMistFormRoutine()); } // Same rule for a night-only bat: a form the sun forbids cannot be kept through the @@ -474,7 +474,7 @@ namespace RacesOfValheim EnvMan.instance != null && EnvMan.IsDay()) { Player.m_localPlayer.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_aswid_morning_sun_drives_bat_back")); - StartCoroutine(RevertToHumanRoutine()); + RunFormRoutine(RevertToHumanRoutine()); } } @@ -565,7 +565,7 @@ namespace RacesOfValheim if (IsTransformed) { - StartCoroutine(RevertToHumanRoutine()); + RunFormRoutine(RevertToHumanRoutine()); return; } @@ -580,18 +580,73 @@ namespace RacesOfValheim return; } - StartCoroutine(TransformIntoBatRoutine(rules)); + RunFormRoutine(TransformIntoBatRoutine(rules)); + } + + // The one bat or mist routine in flight, if any. Kept so ResetRace can stop it: a + // TransformIntoBatRoutine left running through a reset finishes its 1.1s gesture and + // turns a freshly reset Human into a bat. + private Coroutine formRoutine; + + private void RunFormRoutine(System.Collections.IEnumerator routine) + { + formRoutine = StartCoroutine(routine); + } + + /// + /// Drops bat and mist form on the spot for ResetRace: no puff, no tween, nothing left + /// running. ForceRevert is no use there - it skips a form that is still mid-gesture, and + /// its coroutine would still be shrinking the body back after the reset has finished. + /// + /// True if there was a form to drop. + public bool HardResetForReset() + { + Player player = Player.m_localPlayer; + if (player == null) return false; + + if (formRoutine != null) + { + StopCoroutine(formRoutine); + formRoutine = null; + } + + bool hadMist = mistTransformation != null || player.GetSEMan().HaveStatusEffect("SE_MistForm".GetStableHashCode()); + bool hadBat = IsTransformed || isTransformingSequence; + + // Also clears isTransformingSequence and puts the transform back to scale 1, which + // covers a reset caught halfway through the bat's shrink. + HardResetBatForm(); + + if (hadMist) + { + if (mistTransformation != null) + { + Destroy(mistTransformation); + mistTransformation = null; + } + + Transform playerVisual = player.transform.Find("Visual"); + PlayerVisualHider.Show(playerVisual, "aswid-reset-mist"); + if (playerVisual != null) playerVisual.localScale = Vector3.one; + + player.GetSEMan().RemoveStatusEffect("SE_MistForm".GetStableHashCode(), true); + ZNetView nview = player.GetComponent(); + if (nview != null && nview.IsValid()) nview.GetZDO().Set("Aswid_IsMistForm", false); + } + + isTransformingSequence = false; + return hadBat || hadMist; } public void ForceRevert() { if (IsTransformed && !isTransformingSequence) { - StartCoroutine(RevertToHumanRoutine()); + RunFormRoutine(RevertToHumanRoutine()); } if (Player.m_localPlayer != null && Player.m_localPlayer.GetSEMan().HaveStatusEffect("SE_MistForm".GetStableHashCode()) && !isTransformingSequence) { - StartCoroutine(RevertMistFormRoutine()); + RunFormRoutine(RevertMistFormRoutine()); } } @@ -745,11 +800,11 @@ namespace RacesOfValheim if (Player.m_localPlayer.GetSEMan().HaveStatusEffect("SE_MistForm".GetStableHashCode())) { - StartCoroutine(RevertMistFormRoutine()); + RunFormRoutine(RevertMistFormRoutine()); } else { - StartCoroutine(TransformIntoMistRoutine()); + RunFormRoutine(TransformIntoMistRoutine()); } } diff --git a/JotunnModStub/Fenrir/FenrirRace.cs b/JotunnModStub/Fenrir/FenrirRace.cs index c1d7664..ee5cd5a 100644 --- a/JotunnModStub/Fenrir/FenrirRace.cs +++ b/JotunnModStub/Fenrir/FenrirRace.cs @@ -185,7 +185,7 @@ namespace RacesOfValheim { if (isTransformed) { - StartCoroutine(RevertToHumanRoutine()); + RunFormRoutine(RevertToHumanRoutine()); return; } @@ -213,7 +213,7 @@ namespace RacesOfValheim { } } - StartCoroutine(TransformIntoWolfRoutine(rules)); + RunFormRoutine(TransformIntoWolfRoutine(rules)); } /// @@ -256,11 +256,63 @@ namespace RacesOfValheim { return "$rov_msg_fenrir_formname_fenrir"; } + // The one transform or revert routine in flight, if any, so ResetRace can stop it. A + // revert left to finish on its own lands its cooldown after the reset has already swept + // the status effects, and the next Fenrir starts locked out. + private Coroutine formRoutine; + + private void RunFormRoutine(IEnumerator routine) + { + formRoutine = StartCoroutine(routine); + } + + /// + /// Drops whatever form is up, immediately, for ResetRace: no poof, no message, and no + /// cooldown - ExecuteReversion hands one out, which is right for a form running out and + /// wrong for a player leaving the race. + /// + /// True if there was a form to drop. + public bool HardResetForReset() + { + Player player = Player.m_localPlayer; + if (player == null) return false; + + if (formRoutine != null) + { + StopCoroutine(formRoutine); + formRoutine = null; + } + + bool hadForm = isTransformed || isTransformingSequence || currentTransformation != null; + if (hadForm) + { + if (currentTransformation != null) Destroy(currentTransformation); + currentTransformation = null; + DestroyAllForms(); + + ZNetView nview = player.GetComponent(); + if (nview != null && nview.IsValid()) nview.GetZDO().Set("RacesOfValheim_FenrirForm", ""); + + PlayerVisualHider.Show(player.transform.Find("Visual"), "fenrir-reset"); + + player.GetSEMan().RemoveStatusEffect("SE_FenrirForm".GetStableHashCode()); + player.GetSEMan().RemoveStatusEffect("SE_CultistForm".GetStableHashCode()); + player.GetSEMan().RemoveStatusEffect("SE_WolfForm".GetStableHashCode()); + } + + isTransformed = false; + isTransformingSequence = false; + activeRules = null; + revertMessage = null; + sunSicknessTimer = 0f; + return hadForm; + } + public void ForceRevert() { if (isTransformed && !isTransformingSequence) { - StartCoroutine(RevertToHumanRoutine()); + RunFormRoutine(RevertToHumanRoutine()); } } diff --git a/JotunnModStub/RacesOfValheim.cs b/JotunnModStub/RacesOfValheim.cs index 6e826c6..e6f8289 100644 --- a/JotunnModStub/RacesOfValheim.cs +++ b/JotunnModStub/RacesOfValheim.cs @@ -4,6 +4,7 @@ using HarmonyLib; using Jotunn.Configs; using Jotunn.Entities; using Jotunn.Managers; +using Jotunn.Utils; using UnityEngine; using UnityEngine.UI; // Added for UI @@ -99,6 +100,20 @@ namespace RacesOfValheim Player player = Player.m_localPlayer; if (player == null) return; + // What the reset actually took off, printed at the end so it can be read in the console. + var removed = new System.Collections.Generic.List(); + + // Forms first, before any status effect goes. Taking a form's effect away without + // undoing the form leaves the body hidden (bat, mist, drake, wolf, Muspell, Ravager) + // or oversized (True Form), and several races only ever look at their form from an + // Update that returns early for anyone who is not of that race any more. + if (AswidRace.Instance != null && AswidRace.Instance.HardResetForReset()) removed.Add("form: Aswid bat/mist"); + if (FenrirRace.Instance != null && FenrirRace.Instance.HardResetForReset()) removed.Add("form: Fenrir"); + if (SkadiRace.Instance != null && SkadiRace.Instance.HardResetForReset()) removed.Add("form: Skadi drake"); + if (TrolRace.Instance != null && TrolRace.Instance.HardResetForReset()) removed.Add("form: Trol True Form"); + if (TrentaMuspell.HardResetForReset(player)) removed.Add("form: Trenta Muspell"); + if (SvermRavagerForm.HardResetForReset(player)) removed.Add("form: Sverm Ravager"); + RemovePermanentRaceEquipment(player); player.m_customData.Remove("Race"); @@ -120,21 +135,23 @@ namespace RacesOfValheim } } - player.GetSEMan().RemoveStatusEffect("SE_FenrirCurse".GetStableHashCode()); - player.GetSEMan().RemoveStatusEffect("SE_AswidStats".GetStableHashCode()); - player.GetSEMan().RemoveStatusEffect("SE_SkeletonStats".GetStableHashCode()); - player.GetSEMan().RemoveStatusEffect("SE_SkadiStats".GetStableHashCode()); - player.GetSEMan().RemoveStatusEffect("SE_SkadiCooldown".GetStableHashCode()); - player.GetSEMan().RemoveStatusEffect(DvergarConfig.StatsSE.GetStableHashCode()); - player.GetSEMan().RemoveStatusEffect(DvergarConfig.OverchargeSE.GetStableHashCode()); - player.GetSEMan().RemoveStatusEffect(DvergarConfig.OverchargeCdSE.GetStableHashCode()); - player.GetSEMan().RemoveStatusEffect(DvergarConfig.RunicPingCdSE.GetStableHashCode()); - player.GetSEMan().RemoveStatusEffect(TrentaConfig.StatsSE.GetStableHashCode()); - player.GetSEMan().RemoveStatusEffect(TrentaConfig.PurpleRainCdSE.GetStableHashCode()); - player.GetSEMan().RemoveStatusEffect(TrentaConfig.PortalCdSE.GetStableHashCode()); - player.GetSEMan().RemoveStatusEffect(SvermConfig.StatsSE.GetStableHashCode()); - player.GetSEMan().RemoveStatusEffect(SvermConfig.RavagerSE.GetStableHashCode()); - player.GetSEMan().RemoveStatusEffect(SvermConfig.RavagerCdSE.GetStableHashCode()); + // Every status effect this mod registers, rather than a list kept by hand: the hand + // list was missing the True Form and both of its cooldowns, Bat and Mist Form, the + // Skeleton's resurrect cooldown and most of Skadi's, and the next effect anyone adds + // would have been missing too. The forms were dropped above, so taking their effects + // away here no longer leaves a body hidden or blown up. + SEMan seman = player.GetSEMan(); + foreach (CustomStatusEffect custom in ModRegistry.GetStatusEffects(PluginGUID)) + { + StatusEffect se = custom?.StatusEffect; + if (se == null) continue; + + int hash = se.name.GetStableHashCode(); + if (!seman.HaveStatusEffect(hash)) continue; + + seman.RemoveStatusEffect(hash, true); + removed.Add(se.name); + } // COLD, which is not one of ours at all - and that is exactly why it has to go. // @@ -161,9 +178,21 @@ namespace RacesOfValheim // Only after the ZDO above already says "Human" - see the class doc comment. RaceItemCleanup.PurgeForeignRaceItems(player); + // Normal size. The Trol, the Skeleton past Fader and the self-sizing races all scale + // either the player or its Visual, and each puts its own size back only from code that + // may not run again now the race has changed. The next race sets its own size anyway. + player.transform.localScale = Vector3.one; + GameObject visual = Traverse.Create(player).Field("m_visual").GetValue(); + if (visual != null) visual.transform.localScale = Vector3.one; + + string summary = removed.Count == 0 + ? "[ResetRace] Nothing race-specific was left on the player." + : "[ResetRace] Removed: " + string.Join(", ", removed); + Jotunn.Logger.LogInfo(summary); + if (Console.instance != null) Console.instance.Print(summary); + if (Instance != null) { - if (FenrirRace.Instance != null) FenrirRace.Instance.ForceRevert(); Instance.ShowRaceSelectionMenu(); } } diff --git a/JotunnModStub/Skadi/SkadiRace.cs b/JotunnModStub/Skadi/SkadiRace.cs index 573685d..27ea13e 100644 --- a/JotunnModStub/Skadi/SkadiRace.cs +++ b/JotunnModStub/Skadi/SkadiRace.cs @@ -247,7 +247,7 @@ namespace RacesOfValheim { formExpireTime = 0f; Player.m_localPlayer.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_skadi_dragon_form_fades")); - StartCoroutine(RevertToHumanRoutine()); + RunFormRoutine(RevertToHumanRoutine()); return; } @@ -687,7 +687,7 @@ namespace RacesOfValheim if (isTransformed) { - StartCoroutine(RevertToHumanRoutine()); + RunFormRoutine(RevertToHumanRoutine()); return; } @@ -707,7 +707,7 @@ namespace RacesOfValheim } activeRules = rules; - StartCoroutine(TransformRoutine(rules)); + RunFormRoutine(TransformRoutine(rules)); } private Vector3 GetFormScale(SkadiProgression.FormType form) @@ -914,6 +914,57 @@ namespace RacesOfValheim if (se != null) se.m_ttl = seconds; } + // The one transform or revert routine in flight, if any, so ResetRace can stop it. + private Coroutine formRoutine; + + private void RunFormRoutine(System.Collections.IEnumerator routine) + { + formRoutine = StartCoroutine(routine); + } + + /// + /// Drops the drake form on the spot for ResetRace. Update bails out on its first line for + /// anyone who is not a Skadi, so once the race changes nothing in this class ever looks at + /// the form again - a Skadi reset in drake form stayed a drake for good. No message and no + /// cooldown here, unlike ExecuteReversion. + /// + /// True if there was a form to drop. + public bool HardResetForReset() + { + Player player = Player.m_localPlayer; + if (player == null) return false; + + if (formRoutine != null) + { + StopCoroutine(formRoutine); + formRoutine = null; + } + + bool hadForm = isTransformed || isTransformingSequence || currentTransformation != null; + if (hadForm) + { + if (currentTransformation != null) Destroy(currentTransformation); + currentTransformation = null; + foreach (var f in player.GetComponentsInChildren(true)) Destroy(f.gameObject); + + ZNetView nview = player.GetComponent(); + if (nview != null && nview.IsValid()) + { + nview.GetZDO().Set("Skadi_Form", ""); + nview.GetZDO().Set("RacesOfValheim_SkadiForm", ""); + } + + PlayerVisualHider.Show(player.transform.Find("Visual"), "skadi-reset"); + player.GetSEMan().RemoveStatusEffect("SE_SkadiForm".GetStableHashCode(), true); + } + + isTransformed = false; + isTransformingSequence = false; + formExpireTime = 0f; + activeRules = null; + return hadForm; + } + private void ExecuteReversion() { Transform playerVisual = Player.m_localPlayer.transform.Find("Visual"); diff --git a/JotunnModStub/Sverm/SvermRavagerForm.cs b/JotunnModStub/Sverm/SvermRavagerForm.cs index b0e6497..f41b7f0 100644 --- a/JotunnModStub/Sverm/SvermRavagerForm.cs +++ b/JotunnModStub/Sverm/SvermRavagerForm.cs @@ -177,7 +177,7 @@ namespace RacesOfValheim if (SvermRace.Instance != null) { - SvermRace.Instance.StartCoroutine(EnterRoutine(player)); + formRoutine = SvermRace.Instance.StartCoroutine(EnterRoutine(player)); } else { @@ -342,12 +342,42 @@ namespace RacesOfValheim } } + // The enter or exit routine in flight, if any, so ResetRace can stop it. An ExitRoutine + // left running finishes with Exit(spendCooldown: true), which puts the cooldown back on + // after the reset has swept it. + private static Coroutine formRoutine; + + /// + /// Drops Ravager Strain on the spot for ResetRace, and forgets its cooldown: nextAllowedAt + /// is a static the status effect sweep never touches, so without this a player who left + /// the Sverm and came back stayed locked out of the form with no timer in the HUD. + /// + /// True if there was a form to drop. + public static bool HardResetForReset(Player player) + { + if (player == null) return false; + + if (formRoutine != null && SvermRace.Instance != null) + { + SvermRace.Instance.StopCoroutine(formRoutine); + } + formRoutine = null; + + bool hadForm = IsActive || transforming || exiting || model != null; + if (IsActive || model != null) Exit(player, spendCooldown: false); + + transforming = false; + exiting = false; + nextAllowedAt = 0f; + return hadForm; + } + /// Kicks off the graceful exit (shrink, then Exit) if there is a host to run it on. private static void RunExit(Player player, bool spendCooldown, string message) { if (SvermRace.Instance != null) { - SvermRace.Instance.StartCoroutine(ExitRoutine(player, spendCooldown, message)); + formRoutine = SvermRace.Instance.StartCoroutine(ExitRoutine(player, spendCooldown, message)); } else { diff --git a/JotunnModStub/Trenta/TrentaMuspell.cs b/JotunnModStub/Trenta/TrentaMuspell.cs index 4499faf..d3af9ef 100644 --- a/JotunnModStub/Trenta/TrentaMuspell.cs +++ b/JotunnModStub/Trenta/TrentaMuspell.cs @@ -53,11 +53,11 @@ namespace RacesOfValheim if (IsTransformed) { - TrentaRace.Instance.StartCoroutine(RevertRoutine(player)); + formRoutine = TrentaRace.Instance.StartCoroutine(RevertRoutine(player)); } else { - TrentaRace.Instance.StartCoroutine(TransformRoutine(player)); + formRoutine = TrentaRace.Instance.StartCoroutine(TransformRoutine(player)); } } @@ -68,10 +68,51 @@ namespace RacesOfValheim { if (IsTransformed && !isTransformingSequence) { - TrentaRace.Instance.StartCoroutine(RevertRoutine(player)); + formRoutine = TrentaRace.Instance.StartCoroutine(RevertRoutine(player)); } } + // The one transform or revert routine in flight, if any, so ResetRace can stop it. + private static Coroutine formRoutine; + + /// + /// Drops the Muspell on the spot for ResetRace. ForceRevert would get there too, from + /// TrentaRace.Update, but a frame and a half-second tween later - after ResetRace has + /// already reopened the menu - and not at all if the reset lands mid-gesture. + /// + /// True if there was a form to drop. + public static bool HardResetForReset(Player player) + { + if (player == null) return false; + + if (formRoutine != null && TrentaRace.Instance != null) + { + TrentaRace.Instance.StopCoroutine(formRoutine); + } + formRoutine = null; + + bool hadForm = IsTransformed || isTransformingSequence || currentTransformation != null; + if (hadForm) + { + if (currentTransformation != null) Object.Destroy(currentTransformation); + currentTransformation = null; + + ZNetView nview = player.GetComponent(); + if (nview != null && nview.IsValid()) nview.GetZDO().Set("RacesOfValheim_MuspellForm", false); + + Transform playerVisual = player.transform.Find("Visual"); + if (playerVisual != null) + { + playerVisual.localScale = Vector3.one; + playerVisual.gameObject.SetActive(true); + } + } + + IsTransformed = false; + isTransformingSequence = false; + return hadForm; + } + /// /// Called by Purple Rain instead of its usual staff_summon trigger whenever Muspell is /// active - The Elder's own root-summon gesture, played on the transformation clone's diff --git a/JotunnModStub/Trol/TrolRace.cs b/JotunnModStub/Trol/TrolRace.cs index e1894ec..e2d26c4 100644 --- a/JotunnModStub/Trol/TrolRace.cs +++ b/JotunnModStub/Trol/TrolRace.cs @@ -206,11 +206,52 @@ namespace RacesOfValheim bool isTrueFormActive = Player.m_localPlayer.GetSEMan().HaveStatusEffect("SE_TrolTrueForm".GetStableHashCode()); if (wasTrueFormActive && !isTrueFormActive && !isTransforming) { - StartCoroutine(RevertTrueFormRoutine()); + RunFormRoutine(RevertTrueFormRoutine()); } wasTrueFormActive = isTrueFormActive; } + // The one grow or shrink routine in flight, if any, so ResetRace can stop it. + private Coroutine formRoutine; + + private void RunFormRoutine(System.Collections.IEnumerator routine) + { + formRoutine = StartCoroutine(routine); + } + + /// + /// Drops True Form on the spot for ResetRace. Update returns on its first line for anyone + /// who is not a Trol, so its auto-revert never saw the form end. wasTrueFormActive is the + /// part that would bite later: left true, the next time this player picks Trol the first + /// Update reads it as a form that just ran out and hands out a True Form cooldown. + /// + /// True if there was a form to drop. + public bool HardResetForReset() + { + Player player = Player.m_localPlayer; + if (player == null) return false; + + if (formRoutine != null) + { + StopCoroutine(formRoutine); + formRoutine = null; + } + + int trueFormHash = "SE_TrolTrueForm".GetStableHashCode(); + bool hadForm = isTransforming || wasTrueFormActive || player.GetSEMan().HaveStatusEffect(trueFormHash); + if (hadForm) + { + player.GetSEMan().RemoveStatusEffect(trueFormHash, true); + + ZNetView nview = player.GetComponent(); + if (nview != null && nview.IsValid()) nview.GetZDO().Set(Trol_PlayerUpdate_Patch.TrueFormKey, false); + } + + isTransforming = false; + wasTrueFormActive = false; + return hadForm; + } + private void TryTrueForm() { if (BossProgressionManager.GetCurrentProgressionState() < 5) return; // Requires Moder @@ -239,7 +280,7 @@ namespace RacesOfValheim if (!isTransforming) { - StartCoroutine(TransformToTrueFormRoutine()); + RunFormRoutine(TransformToTrueFormRoutine()); } } From c64cb393c7ddbb1bed9108f0509616cec0f2ac94 Mon Sep 17 00:00:00 2001 From: kanym Date: Wed, 14 Oct 2026 16:56:34 +0200 Subject: [PATCH 016/163] feat(trol): True Form wears Valheim's own troll True Form now hides the Trol's body and puts the vanilla forest troll's model in its place, on the owner's client and on every other player's. The costume stands as tall as the old True Form did: it follows the Visual scale Trol_PlayerUpdate_Patch already grows and publishes, so the grow-in, the shrink back and the size others see come for free. It takes the Trol skin colour from Trol - Appearance. Weapons are out while it is up. Left click is the troll's punch, right click its ground slam, and with a log in hand they become its two log swings, which wear the log down per hit as a club swing did. Throw Rock plays the troll's throw. The attacks, their triggers and reach are read off the troll's own weapons at runtime, and each hit lands on the troll's OnAttackTrigger event rather than a fixed delay. Damage is a share of the troll's own (Troll Attack Damage, 0.5), scaled by the Clubs skill like a club and hit as Clubs, so the True Form and tier melee bonuses still add on top. Other players see the troll from the existing True Form ZDO flag, with attacks replayed from a new trigger key. New options in Trol - True Form: Troll Model (on/off), Troll Model Size, Troll Attack Damage. --- JotunnModStub/Trol/TrolConfig.cs | 9 + JotunnModStub/Trol/TrolRace.cs | 22 +- JotunnModStub/Trol/TrolTrueFormBehavior.cs | 399 ++++++++++++++++++++ JotunnModStub/Trol/TrolTrueFormModel.cs | 407 +++++++++++++++++++++ 4 files changed, 835 insertions(+), 2 deletions(-) create mode 100644 JotunnModStub/Trol/TrolTrueFormBehavior.cs create mode 100644 JotunnModStub/Trol/TrolTrueFormModel.cs diff --git a/JotunnModStub/Trol/TrolConfig.cs b/JotunnModStub/Trol/TrolConfig.cs index 2a152ae..eaecaae 100644 --- a/JotunnModStub/Trol/TrolConfig.cs +++ b/JotunnModStub/Trol/TrolConfig.cs @@ -51,6 +51,9 @@ namespace RacesOfValheim public static ConfigEntry TrueFormCooldown; public static ConfigEntry TrueFormScaleNormal; public static ConfigEntry TrueFormScaleAdvanced; + public static ConfigEntry TrueFormUseTrollModel; + public static ConfigEntry TrueFormModelSize; + public static ConfigEntry TrueFormTrollDamageShare; // ─── Log Weapon (tier 7+) ────────────────────────────────────────────── public static ConfigEntry LogWeaponMaxDurability; @@ -133,6 +136,12 @@ namespace RacesOfValheim new ConfigDescription("Model scale while in True Form, tier 5-6.", new AcceptableValueRange(1f, 4f))); TrueFormScaleAdvanced = config.Bind(trueForm, "Scale (Tier 7+)", 2.5f, new ConfigDescription("Model scale while in True Form, tier 7+.", new AcceptableValueRange(1f, 4f))); + TrueFormUseTrollModel = config.Bind(trueForm, "Troll Model", true, + new ConfigDescription("Wear Valheim's own troll in True Form, with its own punch and ground slam instead of your weapons. Off: the old True Form, a bigger Trol with weapons in hand.")); + TrueFormModelSize = config.Bind(trueForm, "Troll Model Size", 1f, + new ConfigDescription("How tall the troll stands, as a share of the True Form size set by Scale above. 1 = exactly as tall as the old True Form.", new AcceptableValueRange(0.5f, 2f))); + TrueFormTrollDamageShare = config.Bind(trueForm, "Troll Attack Damage", 0.5f, + new ConfigDescription("Share of a real troll's damage each troll attack deals. Your Clubs skill then scales it the way it scales a club, and the True Form Melee Bonus and tier bonuses add on top.", new AcceptableValueRange(0.1f, 2f))); const string logWeapon = "Trol - Log Weapon"; LogWeaponMaxDurability = config.Bind(logWeapon, "Max Durability", 6f, diff --git a/JotunnModStub/Trol/TrolRace.cs b/JotunnModStub/Trol/TrolRace.cs index e2d26c4..dd5e546 100644 --- a/JotunnModStub/Trol/TrolRace.cs +++ b/JotunnModStub/Trol/TrolRace.cs @@ -153,6 +153,10 @@ namespace RacesOfValheim private void Update() { + // Before the race check, on purpose: a race change or a death has to take the troll + // costume off, and nothing below the check runs for them any more. + TrolTrueFormModel.Tick(Player.m_localPlayer); + if (!IsTrol()) return; if (RaceInput.Allowed) @@ -247,6 +251,8 @@ namespace RacesOfValheim if (nview != null && nview.IsValid()) nview.GetZDO().Set(Trol_PlayerUpdate_Patch.TrueFormKey, false); } + if (TrolTrueFormModel.RemoveLocal(player)) hadForm = true; + isTransforming = false; wasTrueFormActive = false; return hadForm; @@ -402,8 +408,20 @@ namespace RacesOfValheim Player.m_localPlayer.GetInventory().RemoveItem(rightItem); } - // Wait a moment for the animation to reach the throw point - yield return new WaitForSeconds(0.4f); + // Wait a moment for the animation to reach the throw point. Wearing the troll, that is + // the troll's own throw, and the rock leaves the hand on its OnAttackTrigger. + TrolTrueFormBehavior troll = isTrueForm ? FindObjectOfType() : null; + int baseline = troll != null ? troll.PlayThrow() : -1; + if (baseline >= 0) + { + float started = Time.time; + while (TrolTrueFormModel.AttackEvents == baseline && Time.time - started < 1.5f) yield return null; + } + else + { + yield return new WaitForSeconds(0.4f); + } + if (Player.m_localPlayer == null) yield break; Vector3 spawnPos = Player.m_localPlayer.GetEyePoint() + Player.m_localPlayer.GetLookDir() * 1.5f; diff --git a/JotunnModStub/Trol/TrolTrueFormBehavior.cs b/JotunnModStub/Trol/TrolTrueFormBehavior.cs new file mode 100644 index 0000000..1e52a57 --- /dev/null +++ b/JotunnModStub/Trol/TrolTrueFormBehavior.cs @@ -0,0 +1,399 @@ +using System.Collections; +using System.Collections.Generic; +using HarmonyLib; +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// Drives the local player's troll: its legs from the hidden player's Animator, its fists from + /// the mouse. FenrirFormBehavior in shape - a trigger on the costume's Animator, then a sweep for + /// whatever is in reach - with two differences. The hit waits for the troll's own OnAttackTrigger + /// (see TrolTrueFormModel) instead of a fixed delay, and the damage is the troll's own, scaled. + /// + /// Left click punches, right click slams the ground. With a log in hand they become the troll's + /// two log swings, and each one that lands wears the log down the way a club swing used to. + /// + public class TrolTrueFormBehavior : MonoBehaviour + { + // Longest a swing waits for the troll's own hit event before landing anyway: a clip with + // no event must not leave the player swinging at nothing. + private const float HitEventTimeout = 1.5f; + + private Animator anim; + private Animator playerAnim; + private readonly FormLocomotion locomotion = new FormLocomotion(); + private readonly HashSet triggers = new HashSet(); + + private bool isAttacking; + private float busySince = -1f; + + private GameObject heldLog; + private string heldLogName; + + public bool IsAttacking => isAttacking; + + private void Start() + { + anim = GetComponentInChildren(); + Transform visual = Player.m_localPlayer != null ? Player.m_localPlayer.transform.Find("Visual") : null; + if (visual != null) playerAnim = visual.GetComponent(); + + if (anim != null) + { + foreach (AnimatorControllerParameter p in anim.parameters) + { + if (p.type == AnimatorControllerParameterType.Trigger) triggers.Add(p.name); + } + } + } + + /// Re-hides the body every frame; see RavagerFormBehavior.LateUpdate for why a + /// timer is not enough. + private void LateUpdate() + { + Player player = Player.m_localPlayer; + if (player == null) return; + PlayerVisualHider.Hide(player.transform.Find("Visual"), "trol-trueform-local"); + } + + private void Update() + { + Player player = Player.m_localPlayer; + if (player == null || anim == null || playerAnim == null) return; + + transform.localScale = Vector3.one * TrolTrueFormModel.ScaleFor(player); + + ItemDrop.ItemData right = Traverse.Create(player).Field("m_rightItem").Value; + TrolTrueFormModel.UpdateHeldLog(gameObject, right?.m_dropPrefab, ref heldLog, ref heldLogName); + + if (FormAnimGuard.Stuck(isAttacking, ref busySince)) + { + StopAllCoroutines(); + isAttacking = false; + } + + if (isAttacking || player.IsDead()) return; + + bool grounded = locomotion.Mirror(anim, playerAnim, player.IsCrouching()); + if (!grounded || !RaceInput.Allowed) return; + + bool log = heldLogName != null; + if (RaceInput.AttackDown(0)) + { + Play(log ? TrolTrueFormModel.AttackKind.LogSwingH : TrolTrueFormModel.AttackKind.Punch); + } + else if (RaceInput.AttackDown(1)) + { + Play(log ? TrolTrueFormModel.AttackKind.LogSwingV : TrolTrueFormModel.AttackKind.Slam); + } + } + + private void Play(TrolTrueFormModel.AttackKind kind) + { + TrolTrueFormModel.Profile profile = TrolTrueFormModel.Get(kind); + // A log swing the troll does not have falls back on the fist, rather than doing nothing. + if (profile == null && kind == TrolTrueFormModel.AttackKind.LogSwingH) profile = TrolTrueFormModel.Get(TrolTrueFormModel.AttackKind.Punch); + if (profile == null && kind == TrolTrueFormModel.AttackKind.LogSwingV) profile = TrolTrueFormModel.Get(TrolTrueFormModel.AttackKind.Slam); + if (profile == null) return; + + bool log = kind == TrolTrueFormModel.AttackKind.LogSwingH || kind == TrolTrueFormModel.AttackKind.LogSwingV; + StartCoroutine(AttackRoutine(profile, log)); + } + + /// + /// Plays the troll's throw for TrolRace's Throw Rock and holds the troll still through it. + /// Returns the event count to wait on, or -1 if the troll has no throw to play. + /// + public int PlayThrow() + { + TrolTrueFormModel.Profile profile = TrolTrueFormModel.Get(TrolTrueFormModel.AttackKind.Throw); + if (profile == null || isAttacking) return -1; + + int baseline = TrolTrueFormModel.AttackEvents; + StartCoroutine(ThrowRoutine(profile)); + return baseline; + } + + private IEnumerator ThrowRoutine(TrolTrueFormModel.Profile profile) + { + isAttacking = true; + Fire(profile.Trigger); + yield return WaitForClip(); + isAttacking = false; + } + + private IEnumerator AttackRoutine(TrolTrueFormModel.Profile profile, bool log) + { + isAttacking = true; + Player player = Player.m_localPlayer; + + int baseline = TrolTrueFormModel.AttackEvents; + Fire(profile.Trigger); + profile.Shared.m_startEffect.Create(player.transform.position, player.transform.rotation, player.transform); + float started = Time.time; + + while (TrolTrueFormModel.AttackEvents == baseline && Time.time - started < HitEventTimeout) + { + yield return null; + } + + if (player != null && !player.IsDead()) + { + profile.Shared.m_triggerEffect.Create(player.transform.position, player.transform.rotation, player.transform); + int landed = TrolTrueFormHit.Sweep(player, profile, transform.localScale.x); + if (landed > 0) + { + player.RaiseSkill(Skills.SkillType.Clubs, 1f); + if (log) WearLog(player); + } + } + + yield return WaitForClip(Time.time - started); + isAttacking = false; + } + + private void Fire(string trigger) + { + if (anim == null || string.IsNullOrEmpty(trigger) || !triggers.Contains(trigger)) return; + + try { anim.SetFloat("forward_speed", 0f); } catch {} + try { anim.SetFloat("sideway_speed", 0f); } catch {} + anim.SetTrigger(trigger); + TrolTrueFormModel.PublishAttackTrigger(Player.m_localPlayer, trigger); + } + + /// + /// Holds the lock until the attack clip has played out. The clip is read off the Animator a + /// frame after the trigger, when the transition into it has started; the length is clamped + /// so a wrong guess can neither cut a swing short nor freeze the troll. + /// + private IEnumerator WaitForClip(float alreadySpent = 0f) + { + yield return null; + + float length = 1.2f; + if (anim != null) + { + AnimatorClipInfo[] clips = anim.IsInTransition(0) ? anim.GetNextAnimatorClipInfo(0) : anim.GetCurrentAnimatorClipInfo(0); + if (clips != null && clips.Length > 0 && clips[0].clip != null) length = clips[0].clip.length; + } + + float remaining = Mathf.Clamp(length, 0.6f, 3f) - alreadySpent; + if (remaining > 0f) yield return new WaitForSeconds(remaining); + } + + /// The same wear a club swing put on the log, per swing that lands. TrolRace.Update + /// breaks it once it reaches zero. + private static void WearLog(Player player) + { + ItemDrop.ItemData right = Traverse.Create(player).Field("m_rightItem").Value; + if (right == null || right.m_dropPrefab == null || !right.m_dropPrefab.name.StartsWith("TrolWeapon_")) return; + right.m_durability = Mathf.Max(0f, right.m_durability - TrolConfig.LogWeaponDurabilityDrainPerHit.Value); + } + } + + /// + /// One troll blow against whatever is in reach. FenrirFormBehavior.ExecuteClawDamage's shape and + /// cover test, with the reach taken off the troll's own weapon and multiplied by how big the + /// costume is - a troll's arm is a troll's arm, at whatever size it is worn. + /// + internal static class TrolTrueFormHit + { + private const string FormLabel = "Troll"; + + private static readonly int Mask = LayerMask.GetMask("Default", "static_solid", "Default_small", "piece", + "piece_nonsolid", "terrain", "character", "character_net", "character_ghost", "hitbox", + "character_noenv", "vehicle"); + + /// How many things the blow landed on. + public static int Sweep(Player player, TrolTrueFormModel.Profile profile, float costumeScale) + { + Vector3 pos = player.transform.position; + Vector3 forward = player.transform.forward; + float range = Mathf.Max(1.5f, profile.Range * costumeScale); + bool area = profile.Type == Attack.AttackType.Area; + + Vector3 center = area + ? pos + forward * (range * 0.3f) + Vector3.up + : pos + forward * (range * 0.5f) + Vector3.up * Mathf.Max(1f, profile.Height * costumeScale); + float radius = area ? range * 0.7f : range * 0.5f + 0.5f; + float halfAngle = area ? 180f : Mathf.Max(60f, profile.Angle * 0.5f); + + Collider[] hits = Physics.OverlapSphere(center, radius, Mask); + FormMelee.LogSwing(FormLabel, hits.Length); + + HitData.DamageTypes damage = TrolTrueFormModel.DamageFor(player, profile); + var done = new HashSet(); + int landed = 0; + + foreach (Collider hit in hits) + { + if (hit.gameObject == player.gameObject) continue; + if (hit.attachedRigidbody != null && hit.attachedRigidbody.gameObject == player.gameObject) continue; + + IDestructible target = hit.GetComponentInParent(); + if (target == null || (target is Character c && c == player)) continue; + + GameObject targetObj = (target as MonoBehaviour)?.gameObject; + if (targetObj != null && done.Contains(targetObj)) continue; + + Vector3 targetCenter = hit.bounds.center; + Vector3 flat = targetCenter - pos; + flat.y = 0f; + float angle = flat.sqrMagnitude > 0.0001f ? Vector3.Angle(forward, flat) : 0f; + if (angle > halfAngle) + { + FormMelee.LogMiss(FormLabel, hit, $"outside the swing arc ({angle:0} deg)"); + continue; + } + + Vector3 eye = player.GetEyePoint(); + if (!FormMelee.CanReach(eye, center, hit, target, out string cover)) + { + FormMelee.LogMiss(FormLabel, hit, "no clear line, blocked by '" + cover + "'"); + continue; + } + + HitData hitData = new HitData(); + hitData.m_damage = damage; + hitData.m_point = targetCenter; + hitData.m_dir = (targetCenter - pos).normalized; + hitData.m_pushForce = profile.PushForce; + hitData.m_skill = Skills.SkillType.Clubs; + hitData.m_toolTier = (short)profile.ToolTier; + hitData.m_dodgeable = true; + hitData.m_blockable = true; + hitData.m_hitType = HitData.HitType.PlayerHit; + hitData.SetAttacker(player); + + if (targetObj != null) done.Add(targetObj); + FormMelee.LogHit(FormLabel, target, damage.GetTotalDamage()); + target.Damage(hitData); + profile.Shared.m_hitEffect.Create(targetCenter, Quaternion.identity); + landed++; + } + + return landed; + } + } + + /// + /// The troll every other client sees. RemoteFenrirAnimator in shape: legs from the remote + /// player's own Animator, which ZSyncAnimation keeps fed over the network, and attacks replayed + /// from the trigger the owner publishes. Sized and given its log the same way as the owner's. + /// + public class RemoteTrolTrueFormAnimator : MonoBehaviour + { + private Player player; + private Animator anim; + private Animator playerAnim; + private ZNetView nview; + private string lastAttack; + private readonly FormLocomotion locomotion = new FormLocomotion(); + + private GameObject heldLog; + private string heldLogName; + + private void LateUpdate() + { + if (player == null) return; + PlayerVisualHider.Hide(player.transform.Find("Visual"), "trol-trueform-remote"); + } + + private void Update() + { + if (player == null) player = GetComponentInParent(); + if (player == null) return; + if (nview == null) nview = player.GetComponent(); + if (anim == null) anim = GetComponentInChildren(); + if (playerAnim == null) + { + Transform visual = player.transform.Find("Visual"); + if (visual != null) playerAnim = visual.GetComponent(); + } + if (anim == null || playerAnim == null || nview == null || !nview.IsValid()) return; + + transform.localScale = Vector3.one * TrolTrueFormModel.ScaleFor(player); + + int rightHash = nview.GetZDO().GetInt(ZDOVars.s_rightItem, 0); + GameObject rightPrefab = rightHash != 0 && ObjectDB.instance != null ? ObjectDB.instance.GetItemPrefab(rightHash) : null; + TrolTrueFormModel.UpdateHeldLog(gameObject, rightPrefab, ref heldLog, ref heldLogName); + + ReplayAttack(); + locomotion.Mirror(anim, playerAnim, player.IsCrouching()); + } + + private void ReplayAttack() + { + string current = nview.GetZDO().GetString(TrolTrueFormModel.AttackTriggerKey, ""); + + // The first look only records what is there, so a punch from an earlier True Form does + // not replay the moment this troll is built. + if (lastAttack == null) { lastAttack = current; return; } + if (string.IsNullOrEmpty(current) || current == lastAttack) return; + lastAttack = current; + + int seqAt = current.LastIndexOf('#'); + string trigger = seqAt >= 0 ? current.Substring(0, seqAt) : current; + + foreach (AnimatorControllerParameter p in anim.parameters) + { + if (p.type == AnimatorControllerParameterType.Trigger && p.name == trigger) + { + try { anim.SetFloat("forward_speed", 0f); } catch {} + anim.SetTrigger(trigger); + break; + } + } + } + } + + /// + /// Puts the troll on every other client, from the True Form flag Trol_PlayerUpdate_Patch already + /// publishes for sizing. Sverm_RavagerRemoteVisuals_Patch's arrangement. + /// + [HarmonyPatch(typeof(VisEquipment), "UpdateVisuals")] + public static class Trol_TrueFormRemoteVisuals_Patch + { + public static void Postfix(VisEquipment __instance) + { + if (__instance == null || !__instance.m_isPlayer) return; + + Player player = __instance.GetComponent(); + if (player == null || player.IsOwner()) return; // The owner's own troll: TrolTrueFormModel.Tick. + + ZNetView nview = player.GetComponent(); + if (nview == null || !nview.IsValid()) return; + + ZDO zdo = nview.GetZDO(); + bool active = TrolConfig.TrueFormUseTrollModel.Value && + !player.IsDead() && + zdo.GetString("RacesOfValheim_Race", "Human") == "Trol" && + zdo.GetBool(Trol_PlayerUpdate_Patch.TrueFormKey, false); + + Transform existing = player.transform.Find(TrolTrueFormModel.RemoteModelName); + Transform playerVisual = player.transform.Find("Visual"); + + if (!active) + { + if (existing != null) + { + existing.gameObject.SetActive(false); + Object.Destroy(existing.gameObject); + PlayerVisualHider.Show(playerVisual, "trol-trueform-remote-revert"); + } + return; + } + + if (existing == null) + { + GameObject model = TrolTrueFormModel.Spawn(player, TrolTrueFormModel.RemoteModelName); + if (model == null) return; + model.AddComponent(); + } + + PlayerVisualHider.Hide(playerVisual, "trol-trueform-remote"); + } + } +} diff --git a/JotunnModStub/Trol/TrolTrueFormModel.cs b/JotunnModStub/Trol/TrolTrueFormModel.cs new file mode 100644 index 0000000..9748bf8 --- /dev/null +++ b/JotunnModStub/Trol/TrolTrueFormModel.cs @@ -0,0 +1,407 @@ +using System.Collections.Generic; +using HarmonyLib; +using Jotunn.Managers; +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// True Form wears Valheim's own forest troll instead of a scaled-up player. + /// + /// Built the way the Fenrir forms are, not the way the Sverm's Ravager is: the troll's Visual is + /// instantiated live under the player, CharacterAnimEvent and AnimationEffect included. That + /// costs a FormFootsteps.Detach, and in return the troll's own clips play their own sounds and, + /// more to the point here, fire OnAttackTrigger at the exact frame a fist lands. That event + /// resolves to the PLAYER (the first Character up the hierarchy), and + /// Trol_TrueFormAttackTrigger_Patch catches it there - so every hit lands on the troll's own + /// timing rather than on a delay somebody guessed. + /// + /// SIZE. The costume does not have a size of its own. Every frame it is sized to stand as tall as + /// the player's hidden Visual would - the same Visual Trol_PlayerUpdate_Patch already grows from + /// 1.2-1.3 to the True Form scale, on the owner's client and every onlooker's. So the grow-in, the + /// shrink back and the size other players see all come from code that already worked, and + /// "Scale" / "Scale (Tier 7+)" keep meaning what they meant: how many player heights tall. + /// + /// ATTACKS. Read once off the troll's own weapons (Humanoid.m_defaultItems and friends): the + /// trigger each one plays, its damage, its reach. Nothing is cloned or equipped. The damage is a + /// share of the troll's (Troll Attack Damage), scaled by the player's Clubs skill exactly the way + /// a weapon is, and hit as Clubs - so Trol_Character_ApplyDamage_Patch adds the True Form and tier + /// bonuses on top just as it did for a club in hand. + /// + public static class TrolTrueFormModel + { + public const string Creature = "Troll"; + public const string LocalModelName = "TrolTrueFormModel"; + public const string RemoteModelName = "TrolTrueFormRemoteModel"; + + // Published by the owner after every trigger it fires, with a running count so the same + // punch twice in a row still reads as two - see FenrirAttackSync. + public const string AttackTriggerKey = "RacesOfValheim_TrolTrueFormAttack"; + private static int attackSeq; + + private static readonly int TrueFormHash = "SE_TrolTrueForm".GetStableHashCode(); + + public enum AttackKind { Punch, Slam, Throw, LogSwingH, LogSwingV } + + public class Profile + { + public string Source; + public string Trigger; + public HitData.DamageTypes Damage; + public Attack.AttackType Type; + public float Range; + public float Height; + public float Angle; + public float PushForce; + public int ToolTier; + public ItemDrop.ItemData.SharedData Shared; + } + + private static readonly Dictionary profiles = new Dictionary(); + private static bool profilesRead; + + // Measured once off the prefab: how tall the troll stands at scale 1. + private static float trollHeight = -1f; + private static string rightHandPath; + + private static GameObject localModel; + private static int attackEvents; + + public static bool LocalActive => localModel != null; + + /// How many OnAttackTrigger events the local troll has fired. Attack routines + /// remember the count and wait for it to move. + public static int AttackEvents => attackEvents; + + public static void NotifyAttackTrigger() => attackEvents++; + + // ─── Lifecycle ─────────────────────────────────────────────────────── + + /// + /// Called every frame from TrolRace.Update, before its race check, so a race change, a death + /// or the form running out all take the costume off even though nothing else in TrolRace + /// looks at the player any more by then. + /// + public static void Tick(Player player) + { + if (player == null || player != Player.m_localPlayer) return; + + bool wanted = TrolConfig.TrueFormUseTrollModel.Value && + !player.IsDead() && + TrolRace.IsTrol() && + player.GetSEMan().HaveStatusEffect(TrueFormHash); + + if (wanted && localModel == null) SpawnLocal(player); + else if (!wanted && localModel != null) RemoveLocal(player); + } + + private static void SpawnLocal(Player player) + { + localModel = Spawn(player, LocalModelName); + if (localModel == null) return; + + localModel.AddComponent(); + PlayerVisualHider.Hide(player.transform.Find("Visual"), "trol-trueform-local"); + + GameObject smoke = PrefabManager.Cache.GetPrefab("vfx_corpse_destruction_medium"); + if (smoke != null) Object.Instantiate(smoke, player.transform.position + Vector3.up, Quaternion.identity); + } + + /// Takes the costume off and gives the body back. Safe to call when there is none. + public static bool RemoveLocal(Player player) + { + if (localModel == null) return false; + + // SetActive first: Destroy waits for the end of the frame, and the behaviour's + // LateUpdate would hide the body again after the Show below. Same trap + // SvermRavagerForm.Exit documents. + localModel.SetActive(false); + Object.Destroy(localModel); + localModel = null; + + if (player != null) PlayerVisualHider.Show(player.transform.Find("Visual"), "trol-trueform-revert"); + return true; + } + + /// + /// The troll's Visual, under the given player. Shared by the owner's copy and every + /// onlooker's, so both look alike; only the driving component differs. + /// + public static GameObject Spawn(Player player, string name) + { + GameObject prefab = PrefabManager.Cache.GetPrefab(Creature); + Transform source = prefab != null ? prefab.transform.Find("Visual") : null; + if (source == null) + { + Jotunn.Logger.LogWarning($"[Trol] No '{Creature}' Visual to build True Form from; staying in the old shape."); + return null; + } + + MeasureTroll(prefab); + + GameObject model = Object.Instantiate(source.gameObject, player.transform); + model.name = name; + model.transform.localPosition = Vector3.zero; + model.transform.localRotation = Quaternion.identity; + model.transform.localScale = Vector3.one * ScaleFor(player); + + FormFootsteps.Detach(model, Creature); + + Animator anim = model.GetComponentInChildren(true); + if (anim != null) + { + anim.cullingMode = AnimatorCullingMode.AlwaysAnimate; + if (anim.GetComponent("AnimationEffect") == null) anim.gameObject.AddComponent(); + } + + Tint(model, SkinColorOf(player)); + return model; + } + + /// + /// The costume's scale for this player right now: as tall as their Visual stands, in + /// player heights, times the Troll Model Size setting. + /// + public static float ScaleFor(Player player) + { + if (player == null || trollHeight <= 0f) return 1f; + + GameObject visual = Traverse.Create(player).Field("m_visual").GetValue(); + float visualScale = visual != null ? visual.transform.localScale.y : 1f; + + CapsuleCollider capsule = player.GetComponent(); + float playerHeight = capsule != null ? capsule.height : 1.85f; + + return playerHeight * visualScale / trollHeight * TrolConfig.TrueFormModelSize.Value; + } + + private static void MeasureTroll(GameObject prefab) + { + if (trollHeight > 0f) return; + + CapsuleCollider capsule = prefab.GetComponent(); + trollHeight = capsule != null ? capsule.height * prefab.transform.localScale.y : 0f; + if (trollHeight <= 0.5f) trollHeight = 4.5f; + + // Where the troll holds its log: VisEquipment knows, so ask it rather than guess bones. + VisEquipment vis = prefab.GetComponent(); + Transform hand = vis != null ? vis.m_rightHand : null; + Transform visualRoot = prefab.transform.Find("Visual"); + if (hand != null && visualRoot != null && hand.IsChildOf(visualRoot)) + { + rightHandPath = PathFrom(visualRoot, hand); + } + + Jotunn.Logger.LogInfo($"[Trol] True Form model: '{Creature}' stands {trollHeight:0.00} m at scale 1, " + + $"right hand '{rightHandPath ?? "not found"}'."); + } + + private static string PathFrom(Transform root, Transform child) + { + var parts = new List(); + for (Transform t = child; t != null && t != root; t = t.parent) parts.Insert(0, t.name); + return string.Join("/", parts); + } + + // ─── Looks ─────────────────────────────────────────────────────────── + + /// The colour this Trol picked in Trol - Appearance, as published on their ZDO. + public static Color SkinColorOf(Player player) + { + ZNetView nview = player != null ? player.GetComponent() : null; + if (nview != null && nview.IsValid()) + { + Vector3 v = nview.GetZDO().GetVec3(TrolSkinColorPatch.SkinColorKey, new Vector3(-1f, -1f, -1f)); + if (v.x >= 0f) return new Color(v.x, v.y, v.z, 1f); + } + return player == Player.m_localPlayer ? TrolConfig.SkinColor.Value : TrolConfig.DefaultSkinColor; + } + + /// + /// Multiplies the troll's own colour by the player's skin colour, brought up to full + /// brightness first: the troll's texture is already dark, and multiplying it by the swatch + /// as-is turned it nearly black. The hue is the player's, the shading stays the troll's. + /// + private static void Tint(GameObject model, Color skin) + { + float max = Mathf.Max(skin.r, Mathf.Max(skin.g, skin.b)); + if (max <= 0.001f) return; + Color tint = new Color(skin.r / max, skin.g / max, skin.b / max, 1f); + + foreach (Renderer r in model.GetComponentsInChildren(true)) + { + if (r is ParticleSystemRenderer) continue; + foreach (Material m in r.materials) + { + if (m != null && m.HasProperty("_Color")) m.SetColor("_Color", m.GetColor("_Color") * tint); + } + } + } + + /// + /// Puts a copy of the held Trol log in the troll's right hand, or takes it away. Called every + /// frame by both drivers with whatever the player has in their right hand. + /// + public static void UpdateHeldLog(GameObject model, GameObject itemPrefab, ref GameObject current, ref string currentName) + { + string wanted = itemPrefab != null && itemPrefab.name.StartsWith("TrolWeapon_") ? itemPrefab.name : null; + if (wanted == currentName) return; + + if (current != null) Object.Destroy(current); + current = null; + currentName = wanted; + if (wanted == null || rightHandPath == null) return; + + Transform hand = model.transform.Find(rightHandPath); + Transform attach = itemPrefab.transform.Find("attach"); + if (hand == null || attach == null) return; + + current = Object.Instantiate(attach.gameObject, hand); + current.name = "TrolTrueFormLog"; + current.transform.localPosition = Vector3.zero; + current.transform.localRotation = Quaternion.identity; + // Left at the attach's own scale: the hand bone already carries the costume's, so the + // log grows and shrinks with the troll. Whether it looks right in the fist is a thing + // only an eye can settle - this is the line to change if it does not. + current.transform.localScale = Vector3.one; + } + + // ─── Attacks ───────────────────────────────────────────────────────── + + public static Profile Get(AttackKind kind) + { + EnsureProfiles(); + profiles.TryGetValue(kind, out Profile p); + return p; + } + + private static void EnsureProfiles() + { + if (profilesRead) return; + GameObject prefab = PrefabManager.Cache.GetPrefab(Creature); + Humanoid humanoid = prefab != null ? prefab.GetComponent() : null; + if (humanoid == null) return; + profilesRead = true; + + var weapons = new List(); + if (humanoid.m_defaultItems != null) weapons.AddRange(humanoid.m_defaultItems); + if (humanoid.m_randomWeapon != null) weapons.AddRange(humanoid.m_randomWeapon); + if (humanoid.m_randomSets != null) + { + foreach (Humanoid.ItemSet set in humanoid.m_randomSets) + { + if (set?.m_items != null) weapons.AddRange(set.m_items); + } + } + + foreach (GameObject weapon in weapons) + { + ItemDrop drop = weapon != null ? weapon.GetComponent() : null; + ItemDrop.ItemData.SharedData shared = drop?.m_itemData?.m_shared; + if (shared?.m_attack == null || string.IsNullOrEmpty(shared.m_attack.m_attackAnimation)) continue; + + AttackKind? kind = Classify(weapon.name.ToLower(), shared); + if (kind == null || profiles.ContainsKey(kind.Value)) continue; + + Attack a = shared.m_attack; + Profile p = new Profile + { + Source = weapon.name, + Trigger = a.m_attackAnimation, + Damage = shared.m_damages, + Type = a.m_attackType, + Range = a.m_attackRange, + Height = a.m_attackHeight, + Angle = a.m_attackAngle, + PushForce = shared.m_attackForce, + ToolTier = shared.m_toolTier, + Shared = shared, + }; + profiles[kind.Value] = p; + + Jotunn.Logger.LogInfo($"[Trol] True Form {kind.Value} <- '{p.Source}': trigger '{p.Trigger}', {p.Type}, " + + $"range {p.Range:0.0}, blunt {p.Damage.m_blunt:0} slash {p.Damage.m_slash:0} " + + $"chop {p.Damage.m_chop:0} pickaxe {p.Damage.m_pickaxe:0}."); + } + + if (!profiles.ContainsKey(AttackKind.Punch)) + { + Jotunn.Logger.LogWarning($"[Trol] '{Creature}' carries no punch; True Form left click will do nothing."); + } + } + + private static AttackKind? Classify(string name, ItemDrop.ItemData.SharedData shared) + { + if (name.Contains("throw") || shared.m_attack.m_attackProjectile != null) return AttackKind.Throw; + if (name.Contains("log")) + { + return name.EndsWith("_v") || name.Contains("vertical") ? AttackKind.LogSwingV : AttackKind.LogSwingH; + } + if (name.Contains("slam") || shared.m_attack.m_attackType == Attack.AttackType.Area) return AttackKind.Slam; + if (name.Contains("punch")) return AttackKind.Punch; + return null; + } + + /// + /// The owner's side of a remote replay: records the trigger just fired, so + /// RemoteTrolTrueFormAnimator plays it on every other client's copy. + /// + public static void PublishAttackTrigger(Player player, string trigger) + { + ZNetView nview = player != null ? player.GetComponent() : null; + if (nview == null || !nview.IsValid()) return; + + attackSeq++; + nview.GetZDO().Set(AttackTriggerKey, trigger + "#" + attackSeq); + } + + /// + /// The damage a troll attack deals for this player right now: the troll's own numbers, times + /// Troll Attack Damage, times the same random Clubs factor a club would get. + /// + public static HitData.DamageTypes DamageFor(Player player, Profile profile) + { + HitData.DamageTypes damage = profile.Damage.Clone(); + float factor = TrolConfig.TrueFormTrollDamageShare.Value * player.GetRandomSkillFactor(Skills.SkillType.Clubs); + damage.Modify(factor); + return damage; + } + + // ─── Native attack loop, shut while the costume is on ──────────────── + + [HarmonyPatch(typeof(Humanoid), "StartAttack")] + public static class Trol_TrueFormBlockNativeAttack_Patch + { + public static bool Prefix(Humanoid __instance) + { + return __instance != Player.m_localPlayer || !LocalActive; + } + } + + /// Crossbow reload and draw live here; see Fenrir's BlockPlayerAttackInputPatch. + [HarmonyPatch(typeof(Player), "PlayerAttackInput")] + public static class Trol_TrueFormBlockAttackInput_Patch + { + public static bool Prefix(Player __instance) + { + return __instance != Player.m_localPlayer || !LocalActive; + } + } + + /// + /// The troll's own clips call OnAttackTrigger at the moment a blow lands, and it arrives on + /// the player. It is the hit cue for TrolTrueFormBehavior, and it must go no further: let + /// through, it fires whatever attack the human still has in hand. + /// + [HarmonyPatch(typeof(Humanoid), nameof(Humanoid.OnAttackTrigger))] + public static class Trol_TrueFormAttackTrigger_Patch + { + public static bool Prefix(Humanoid __instance) + { + if (__instance != Player.m_localPlayer || !LocalActive) return true; + NotifyAttackTrigger(); + return false; + } + } + } +} From db29f868ea8f5dbb80c152310b5998afde9ac113 Mon Sep 17 00:00:00 2001 From: kanym Date: Wed, 14 Oct 2026 17:08:20 +0200 Subject: [PATCH 017/163] fix(trol): True Form troll size, log, reach, root during attacks, slam The troll pulsed several times a second and stayed small because PlayerVisualHider.Hide put the hidden Visual back to scale 1 every frame while Trol_PlayerUpdate_Patch grew it back, and the troll follows that scale. Hide and Show take keepScale now, and the Trol calls pass it. The camera height, which reads the same scale, stops jumping too. The log in the troll's hand is the troll's own log model, hung the way VisEquipment does it, instead of the Trol's, which was built for a person's hand and came out huge and sideways. Punch and slam reach further and hit wider, with a new Troll Attack Reach option (1.3). The player is held still through every attack clip, throw included. The ground slam spawns the troll's own troll_groundslam_aoe with the player's damage, kept off friends, plus its trigger and terrain effects. It carries chop and pickaxe at least equal to its blunt, so it breaks trees and rocks, and with Ground Slam Crater on it digs into the terrain where it lands, never inside a ward without access. --- JotunnModStub/PlayerVisualHider.cs | 12 +- JotunnModStub/Trol/TrolConfig.cs | 6 + JotunnModStub/Trol/TrolTrueFormBehavior.cs | 150 ++++++++++++++++++--- JotunnModStub/Trol/TrolTrueFormModel.cs | 53 ++++++-- 4 files changed, 189 insertions(+), 32 deletions(-) diff --git a/JotunnModStub/PlayerVisualHider.cs b/JotunnModStub/PlayerVisualHider.cs index 0f92cbf..6e753e5 100644 --- a/JotunnModStub/PlayerVisualHider.cs +++ b/JotunnModStub/PlayerVisualHider.cs @@ -37,14 +37,18 @@ namespace RacesOfValheim private float m_nextLog; private string m_context = ""; - public static void Hide(Transform playerVisual, string context) + /// Leave the Visual's scale alone. For a body that is meant to be + /// sized while hidden: the Trol's True Form troll stands as tall as the Visual does, and + /// resetting it here every frame fought Trol_PlayerUpdate_Patch growing it back - the troll + /// pulsed several times a second and never reached full size. + public static void Hide(Transform playerVisual, string context, bool keepScale = false) { if (playerVisual == null) return; // Undo the two older ways this body could have been hidden, so a form entered right // after one of those code paths still starts from a sane state. if (!playerVisual.gameObject.activeSelf) playerVisual.gameObject.SetActive(true); - if (playerVisual.localScale != Vector3.one) playerVisual.localScale = Vector3.one; + if (!keepScale && playerVisual.localScale != Vector3.one) playerVisual.localScale = Vector3.one; // Belt and braces: if anything else ever does deactivate the Visual, at least keep the // animator from snapping back to its spawn state. @@ -68,12 +72,12 @@ namespace RacesOfValheim } } - public static void Show(Transform playerVisual, string context) + public static void Show(Transform playerVisual, string context, bool keepScale = false) { if (playerVisual == null) return; if (!playerVisual.gameObject.activeSelf) playerVisual.gameObject.SetActive(true); - if (playerVisual.localScale != Vector3.one) playerVisual.localScale = Vector3.one; + if (!keepScale && playerVisual.localScale != Vector3.one) playerVisual.localScale = Vector3.one; PlayerVisualHider hider = playerVisual.GetComponent(); if (hider == null || !hider.enabled) return; diff --git a/JotunnModStub/Trol/TrolConfig.cs b/JotunnModStub/Trol/TrolConfig.cs index eaecaae..2588e9a 100644 --- a/JotunnModStub/Trol/TrolConfig.cs +++ b/JotunnModStub/Trol/TrolConfig.cs @@ -54,6 +54,8 @@ namespace RacesOfValheim public static ConfigEntry TrueFormUseTrollModel; public static ConfigEntry TrueFormModelSize; public static ConfigEntry TrueFormTrollDamageShare; + public static ConfigEntry TrueFormAttackReach; + public static ConfigEntry TrueFormSlamCrater; // ─── Log Weapon (tier 7+) ────────────────────────────────────────────── public static ConfigEntry LogWeaponMaxDurability; @@ -142,6 +144,10 @@ namespace RacesOfValheim new ConfigDescription("How tall the troll stands, as a share of the True Form size set by Scale above. 1 = exactly as tall as the old True Form.", new AcceptableValueRange(0.5f, 2f))); TrueFormTrollDamageShare = config.Bind(trueForm, "Troll Attack Damage", 0.5f, new ConfigDescription("Share of a real troll's damage each troll attack deals. Your Clubs skill then scales it the way it scales a club, and the True Form Melee Bonus and tier bonuses add on top.", new AcceptableValueRange(0.1f, 2f))); + TrueFormAttackReach = config.Bind(trueForm, "Troll Attack Reach", 1.3f, + new ConfigDescription("Multiplies how far the troll's punch and slam reach and how wide they hit. 1 = a real troll's reach at the size you stand.", new AcceptableValueRange(0.5f, 3f))); + TrueFormSlamCrater = config.Bind(trueForm, "Ground Slam Crater", true, + new ConfigDescription("The ground slam digs into the ground where it lands, like a pickaxe blow. Never inside a ward you have no access to.")); const string logWeapon = "Trol - Log Weapon"; LogWeaponMaxDurability = config.Bind(logWeapon, "Max Durability", 6f, diff --git a/JotunnModStub/Trol/TrolTrueFormBehavior.cs b/JotunnModStub/Trol/TrolTrueFormBehavior.cs index 1e52a57..004f99c 100644 --- a/JotunnModStub/Trol/TrolTrueFormBehavior.cs +++ b/JotunnModStub/Trol/TrolTrueFormBehavior.cs @@ -33,6 +33,17 @@ namespace RacesOfValheim public bool IsAttacking => isAttacking; + private void SetAttacking(bool on) + { + isAttacking = on; + TrolTrueFormModel.LocalAttacking = on; + } + + private void OnDestroy() + { + TrolTrueFormModel.LocalAttacking = false; + } + private void Start() { anim = GetComponentInChildren(); @@ -54,7 +65,7 @@ namespace RacesOfValheim { Player player = Player.m_localPlayer; if (player == null) return; - PlayerVisualHider.Hide(player.transform.Find("Visual"), "trol-trueform-local"); + PlayerVisualHider.Hide(player.transform.Find("Visual"), "trol-trueform-local", keepScale: true); } private void Update() @@ -70,7 +81,7 @@ namespace RacesOfValheim if (FormAnimGuard.Stuck(isAttacking, ref busySince)) { StopAllCoroutines(); - isAttacking = false; + SetAttacking(false); } if (isAttacking || player.IsDead()) return; @@ -117,15 +128,15 @@ namespace RacesOfValheim private IEnumerator ThrowRoutine(TrolTrueFormModel.Profile profile) { - isAttacking = true; + SetAttacking(true); Fire(profile.Trigger); yield return WaitForClip(); - isAttacking = false; + SetAttacking(false); } private IEnumerator AttackRoutine(TrolTrueFormModel.Profile profile, bool log) { - isAttacking = true; + SetAttacking(true); Player player = Player.m_localPlayer; int baseline = TrolTrueFormModel.AttackEvents; @@ -140,8 +151,18 @@ namespace RacesOfValheim if (player != null && !player.IsDead()) { - profile.Shared.m_triggerEffect.Create(player.transform.position, player.transform.rotation, player.transform); - int landed = TrolTrueFormHit.Sweep(player, profile, transform.localScale.x); + float scale = transform.localScale.x; + int landed; + if (profile.Type == Attack.AttackType.Area) + { + landed = TrolTrueFormHit.Slam(player, profile, scale); + } + else + { + profile.Shared.m_triggerEffect.Create(player.transform.position, player.transform.rotation, player.transform); + landed = TrolTrueFormHit.Sweep(player, profile, scale); + } + if (landed > 0) { player.RaiseSkill(Skills.SkillType.Clubs, 1f); @@ -150,7 +171,7 @@ namespace RacesOfValheim } yield return WaitForClip(Time.time - started); - isAttacking = false; + SetAttacking(false); } private void Fire(string trigger) @@ -206,24 +227,115 @@ namespace RacesOfValheim "piece_nonsolid", "terrain", "character", "character_net", "character_ghost", "hitbox", "character_noenv", "vehicle"); + private const string SlamAoeFallback = "troll_groundslam_aoe"; + private const string CraterPrefab = "digg_v3"; + + private static readonly int GroundMask = LayerMask.GetMask("terrain", "Default", "static_solid", "piece"); + + /// + /// The ground slam, done the way the troll does it: its attack's own spawn-on-trigger, the + /// troll_groundslam_aoe that carries the dust and the area hit. Set up with this player's + /// damage instead of the troll's (m_useAttackSettings) and kept off friends. The first + /// version swept a sphere and spawned nothing, so a slam that hit no creature looked like + /// nothing had happened at all. + /// + /// It also breaks things: the slam's damage gets chop and pickaxe at least equal to its + /// blunt, so trees, rocks and ore around the fists take the blow. With Ground Slam Crater on, + /// the ground gives way too - a pickaxe's dig, which TerrainOp does not check against wards on + /// its own, so the ward check is done here. + /// + /// 1 if the slam went off, so the caller raises the skill; the AoE does its own hits. + public static int Slam(Player player, TrolTrueFormModel.Profile profile, float costumeScale) + { + float range = Mathf.Max(2f, profile.Range * costumeScale * TrolConfig.TrueFormAttackReach.Value); + Vector3 impact = player.transform.position + player.transform.forward * (range * 0.5f); + + // Down onto whatever is under the fists, so the dust and the crater sit on the ground. + bool onTerrain = false; + if (Physics.Raycast(impact + Vector3.up * 3f, Vector3.down, out RaycastHit ground, 8f, GroundMask)) + { + impact = ground.point; + onTerrain = ground.collider != null && ground.collider.GetComponent() != null; + } + + HitData.DamageTypes damage = TrolTrueFormModel.DamageFor(player, profile); + damage.m_chop = Mathf.Max(damage.m_chop, damage.m_blunt); + damage.m_pickaxe = Mathf.Max(damage.m_pickaxe, damage.m_blunt); + + HitData hitData = new HitData(); + hitData.m_damage = damage; + hitData.m_pushForce = profile.PushForce; + hitData.m_skill = Skills.SkillType.Clubs; + hitData.m_toolTier = (short)profile.ToolTier; + hitData.m_dodgeable = true; + hitData.m_blockable = true; + hitData.m_hitType = HitData.HitType.PlayerHit; + hitData.SetAttacker(player); + + profile.Shared.m_triggerEffect.Create(impact, player.transform.rotation); + profile.Shared.m_hitTerrainEffect.Create(impact, Quaternion.identity); + + GameObject aoePrefab = profile.Shared.m_attack.m_spawnOnTrigger; + if (aoePrefab == null) aoePrefab = Jotunn.Managers.PrefabManager.Cache.GetPrefab(SlamAoeFallback); + + bool spawned = false; + if (aoePrefab != null) + { + GameObject instance = Object.Instantiate(aoePrefab, impact, Quaternion.identity); + Aoe aoe = instance.GetComponent(); + if (aoe != null) + { + aoe.m_useAttackSettings = true; + aoe.m_hitFriendly = false; + aoe.m_hitOwner = false; + aoe.m_hitProps = true; + aoe.m_radius = Mathf.Max(aoe.m_radius, range * 0.6f); + aoe.Setup(player, player.transform.forward, -1f, hitData, null, null); + spawned = true; + } + else + { + Object.Destroy(instance); + } + } + + // No Aoe to borrow: the sphere, centred on the impact, so the slam still hits. + if (!spawned) SphereHit(player, impact + Vector3.up, range * 0.7f, 180f, damage, profile); + + if (TrolConfig.TrueFormSlamCrater.Value && onTerrain && PrivateArea.CheckAccess(impact, 0f, false)) + { + GameObject crater = Jotunn.Managers.PrefabManager.Cache.GetPrefab(CraterPrefab); + if (crater != null) Object.Instantiate(crater, impact, Quaternion.identity); + } + + Jotunn.Logger.LogInfo($"[Trol] Ground slam: aoe '{aoePrefab?.name ?? "none"}' spawned={spawned}, " + + $"range {range:0.0}, onTerrain={onTerrain}."); + return 1; + } + /// How many things the blow landed on. public static int Sweep(Player player, TrolTrueFormModel.Profile profile, float costumeScale) { Vector3 pos = player.transform.position; Vector3 forward = player.transform.forward; - float range = Mathf.Max(1.5f, profile.Range * costumeScale); - bool area = profile.Type == Attack.AttackType.Area; + float range = Mathf.Max(2f, profile.Range * costumeScale * TrolConfig.TrueFormAttackReach.Value); - Vector3 center = area - ? pos + forward * (range * 0.3f) + Vector3.up - : pos + forward * (range * 0.5f) + Vector3.up * Mathf.Max(1f, profile.Height * costumeScale); - float radius = area ? range * 0.7f : range * 0.5f + 0.5f; - float halfAngle = area ? 180f : Mathf.Max(60f, profile.Angle * 0.5f); + Vector3 center = pos + forward * (range * 0.55f) + Vector3.up * Mathf.Max(1f, profile.Height * costumeScale); + float radius = range * 0.6f + 0.75f; + float halfAngle = Mathf.Max(75f, profile.Angle * 0.5f); + + return SphereHit(player, center, radius, halfAngle, TrolTrueFormModel.DamageFor(player, profile), profile); + } + + private static int SphereHit(Player player, Vector3 center, float radius, float halfAngle, + HitData.DamageTypes damage, TrolTrueFormModel.Profile profile) + { + Vector3 pos = player.transform.position; + Vector3 forward = player.transform.forward; Collider[] hits = Physics.OverlapSphere(center, radius, Mask); FormMelee.LogSwing(FormLabel, hits.Length); - HitData.DamageTypes damage = TrolTrueFormModel.DamageFor(player, profile); var done = new HashSet(); int landed = 0; @@ -298,7 +410,7 @@ namespace RacesOfValheim private void LateUpdate() { if (player == null) return; - PlayerVisualHider.Hide(player.transform.Find("Visual"), "trol-trueform-remote"); + PlayerVisualHider.Hide(player.transform.Find("Visual"), "trol-trueform-remote", keepScale: true); } private void Update() @@ -381,7 +493,7 @@ namespace RacesOfValheim { existing.gameObject.SetActive(false); Object.Destroy(existing.gameObject); - PlayerVisualHider.Show(playerVisual, "trol-trueform-remote-revert"); + PlayerVisualHider.Show(playerVisual, "trol-trueform-remote-revert", keepScale: true); } return; } @@ -393,7 +505,7 @@ namespace RacesOfValheim model.AddComponent(); } - PlayerVisualHider.Hide(playerVisual, "trol-trueform-remote"); + PlayerVisualHider.Hide(playerVisual, "trol-trueform-remote", keepScale: true); } } } diff --git a/JotunnModStub/Trol/TrolTrueFormModel.cs b/JotunnModStub/Trol/TrolTrueFormModel.cs index 9748bf8..435d8f2 100644 --- a/JotunnModStub/Trol/TrolTrueFormModel.cs +++ b/JotunnModStub/Trol/TrolTrueFormModel.cs @@ -55,6 +55,10 @@ namespace RacesOfValheim public float PushForce; public int ToolTier; public ItemDrop.ItemData.SharedData Shared; + + // The weapon's own model, as VisEquipment would hang it in the troll's hand. Only the + // log swings have one worth showing. + public GameObject Attach; } private static readonly Dictionary profiles = new Dictionary(); @@ -69,6 +73,10 @@ namespace RacesOfValheim public static bool LocalActive => localModel != null; + /// True while the local troll is in the middle of a swing, a slam or a throw. + /// Trol_TrueFormHoldStill_Patch holds the player still for exactly that long. + public static bool LocalAttacking { get; set; } + /// How many OnAttackTrigger events the local troll has fired. Attack routines /// remember the count and wait for it to move. public static int AttackEvents => attackEvents; @@ -101,7 +109,7 @@ namespace RacesOfValheim if (localModel == null) return; localModel.AddComponent(); - PlayerVisualHider.Hide(player.transform.Find("Visual"), "trol-trueform-local"); + PlayerVisualHider.Hide(player.transform.Find("Visual"), "trol-trueform-local", keepScale: true); GameObject smoke = PrefabManager.Cache.GetPrefab("vfx_corpse_destruction_medium"); if (smoke != null) Object.Instantiate(smoke, player.transform.position + Vector3.up, Quaternion.identity); @@ -118,8 +126,9 @@ namespace RacesOfValheim localModel.SetActive(false); Object.Destroy(localModel); localModel = null; + LocalAttacking = false; - if (player != null) PlayerVisualHider.Show(player.transform.Find("Visual"), "trol-trueform-revert"); + if (player != null) PlayerVisualHider.Show(player.transform.Find("Visual"), "trol-trueform-revert", keepScale: true); return true; } @@ -253,17 +262,23 @@ namespace RacesOfValheim if (wanted == null || rightHandPath == null) return; Transform hand = model.transform.Find(rightHandPath); - Transform attach = itemPrefab.transform.Find("attach"); - if (hand == null || attach == null) return; + if (hand == null) return; - current = Object.Instantiate(attach.gameObject, hand); + // The troll's OWN log, not the Trol's. The Trol's was built for a person's hand - turned + // 90 degrees, pushed 1.5 m along it, scaled to 0.4 - and in the troll's fist that came + // out huge and pointing the wrong way. The troll's log weapon carries a model made for + // exactly this bone, and hanging it the way VisEquipment.AttachItem does (zero offset, + // no rotation, its own scale) puts it where vanilla puts it. + Profile log = Get(AttackKind.LogSwingH) ?? Get(AttackKind.LogSwingV); + GameObject source = log?.Attach; + if (source == null) return; + + current = Object.Instantiate(source, hand); current.name = "TrolTrueFormLog"; current.transform.localPosition = Vector3.zero; current.transform.localRotation = Quaternion.identity; - // Left at the attach's own scale: the hand bone already carries the costume's, so the - // log grows and shrinks with the troll. Whether it looks right in the fist is a thing - // only an eye can settle - this is the line to change if it does not. - current.transform.localScale = Vector3.one; + current.transform.localScale = source.transform.localScale; + foreach (Collider c in current.GetComponentsInChildren(true)) Object.Destroy(c); } // ─── Attacks ───────────────────────────────────────────────────────── @@ -316,6 +331,7 @@ namespace RacesOfValheim PushForce = shared.m_attackForce, ToolTier = shared.m_toolTier, Shared = shared, + Attach = weapon.transform.Find("attach")?.gameObject, }; profiles[kind.Value] = p; @@ -369,6 +385,25 @@ namespace RacesOfValheim // ─── Native attack loop, shut while the costume is on ──────────────── + /// + /// Holds the troll still through its own attack clips, the way vanilla roots a creature in + /// mid-swing. SkeletonRiseControlsPatch's arrangement: the move direction is the first + /// argument of SetControls, bound by position. + /// + [HarmonyPatch(typeof(Player), "SetControls")] + public static class Trol_TrueFormHoldStill_Patch + { + public static void Prefix(Player __instance, ref Vector3 __0, ref bool jump, ref bool crouch, ref bool dodge) + { + if (__instance != Player.m_localPlayer || !LocalActive || !LocalAttacking) return; + + __0 = Vector3.zero; + jump = false; + crouch = false; + dodge = false; + } + } + [HarmonyPatch(typeof(Humanoid), "StartAttack")] public static class Trol_TrueFormBlockNativeAttack_Patch { From a9e66aeeb7fd8122695fdab1d6817b815b7108ed Mon Sep 17 00:00:00 2001 From: kanym Date: Wed, 14 Oct 2026 17:17:20 +0200 Subject: [PATCH 018/163] fix(trol): True Form log visible, slam reaches the ground, skin tint The log in the troll's fist was there but switched off: an item's attach child is stored inactive in its prefab and VisEquipment turns it on after the Instantiate. It is now switched on, hung with the item's equipoffset, and sized to the costume, since AttachItem keeps an attach at its world size and the costume is not at scale 1. The slam never ran its slam code. troll_groundslam is a Vertical attack in vanilla, not Area, so asking the attack type sent every slam down the punch's sweep: damage, but no AoE, no dust and no crater. The slam now goes by the key that was pressed. The tint multiplied _Color, which the creature shader does not read. It now shifts _Hue, _Saturation and _Value, as LevelEffects does for starred creatures, by the distance from the vanilla troll's colour to the player's skin colour. --- JotunnModStub/Trol/TrolTrueFormBehavior.cs | 10 ++- JotunnModStub/Trol/TrolTrueFormModel.cs | 72 +++++++++++++++++++--- 2 files changed, 69 insertions(+), 13 deletions(-) diff --git a/JotunnModStub/Trol/TrolTrueFormBehavior.cs b/JotunnModStub/Trol/TrolTrueFormBehavior.cs index 004f99c..4cf4acd 100644 --- a/JotunnModStub/Trol/TrolTrueFormBehavior.cs +++ b/JotunnModStub/Trol/TrolTrueFormBehavior.cs @@ -109,7 +109,11 @@ namespace RacesOfValheim if (profile == null) return; bool log = kind == TrolTrueFormModel.AttackKind.LogSwingH || kind == TrolTrueFormModel.AttackKind.LogSwingV; - StartCoroutine(AttackRoutine(profile, log)); + // The slam goes by what the key means, not by the troll's attack type: troll_groundslam + // is a Vertical attack in vanilla, not an Area one, so asking the type sent every slam + // down the punch's sweep - no dust, no crater, only the damage. + bool slam = kind == TrolTrueFormModel.AttackKind.Slam && profile == TrolTrueFormModel.Get(TrolTrueFormModel.AttackKind.Slam); + StartCoroutine(AttackRoutine(profile, log, slam)); } /// @@ -134,7 +138,7 @@ namespace RacesOfValheim SetAttacking(false); } - private IEnumerator AttackRoutine(TrolTrueFormModel.Profile profile, bool log) + private IEnumerator AttackRoutine(TrolTrueFormModel.Profile profile, bool log, bool slam) { SetAttacking(true); Player player = Player.m_localPlayer; @@ -153,7 +157,7 @@ namespace RacesOfValheim { float scale = transform.localScale.x; int landed; - if (profile.Type == Attack.AttackType.Area) + if (slam) { landed = TrolTrueFormHit.Slam(player, profile, scale); } diff --git a/JotunnModStub/Trol/TrolTrueFormModel.cs b/JotunnModStub/Trol/TrolTrueFormModel.cs index 435d8f2..5437696 100644 --- a/JotunnModStub/Trol/TrolTrueFormModel.cs +++ b/JotunnModStub/Trol/TrolTrueFormModel.cs @@ -68,6 +68,8 @@ namespace RacesOfValheim private static float trollHeight = -1f; private static string rightHandPath; + private static readonly HashSet logged = new HashSet(); + private static GameObject localModel; private static int attackEvents; @@ -226,25 +228,48 @@ namespace RacesOfValheim return player == Player.m_localPlayer ? TrolConfig.SkinColor.Value : TrolConfig.DefaultSkinColor; } + // The vanilla forest troll's own colour, as near as a single swatch gets: the same value the + // Skin Color description recommends for "the look of Valheim's own trolls". + private static readonly Color VanillaTrollColor = new Color(0x7F / 255f, 0xA8 / 255f, 0xC9 / 255f, 1f); + /// - /// Multiplies the troll's own colour by the player's skin colour, brought up to full - /// brightness first: the troll's texture is already dark, and multiplying it by the swatch - /// as-is turned it nearly black. The hue is the player's, the shading stays the troll's. + /// Shifts the troll's colour toward the player's skin colour, the way Valheim recolours a + /// starred creature: LevelEffects writes _Hue, _Saturation and _Value on the creature + /// shader. The first version multiplied _Color, which this shader does not read, so the + /// troll stayed vanilla blue. The shift is the distance from the vanilla troll's colour to + /// the chosen one, so the default Trol skin gives a troll close to its own colour and the + /// texture's shading survives whatever hue is picked. /// private static void Tint(GameObject model, Color skin) { - float max = Mathf.Max(skin.r, Mathf.Max(skin.g, skin.b)); - if (max <= 0.001f) return; - Color tint = new Color(skin.r / max, skin.g / max, skin.b / max, 1f); + Color.RGBToHSV(VanillaTrollColor, out float baseH, out float baseS, out float baseV); + Color.RGBToHSV(skin, out float h, out float s, out float v); + float hue = Mathf.Repeat(h - baseH + 0.5f, 1f) - 0.5f; + float saturation = Mathf.Clamp(s - baseS, -1f, 1f); + // Value is halved: the swatch reads darker on the skin than it looks in the picker (the + // Skin Color description says as much), and a full shift took the troll to near black. + float value = Mathf.Clamp((v - baseV) * 0.5f, -1f, 1f); + + int tinted = 0; foreach (Renderer r in model.GetComponentsInChildren(true)) { if (r is ParticleSystemRenderer) continue; foreach (Material m in r.materials) { - if (m != null && m.HasProperty("_Color")) m.SetColor("_Color", m.GetColor("_Color") * tint); + if (m == null || !m.HasProperty("_Hue")) continue; + m.SetFloat("_Hue", hue); + if (m.HasProperty("_Saturation")) m.SetFloat("_Saturation", saturation); + if (m.HasProperty("_Value")) m.SetFloat("_Value", value); + tinted++; } } + + if (logged.Add("tint/" + model.name)) + { + Jotunn.Logger.LogInfo($"[Trol] True Form tint: hue {hue:+0.00;-0.00}, saturation {saturation:+0.00;-0.00}, " + + $"value {value:+0.00;-0.00} on {tinted} material(s)."); + } } /// @@ -273,12 +298,39 @@ namespace RacesOfValheim GameObject source = log?.Attach; if (source == null) return; - current = Object.Instantiate(source, hand); + // An item's "attach" child is stored INACTIVE in its prefab; VisEquipment.AttachItem + // switches it on after the Instantiate. Copied as it was, the log hung in the fist + // switched off - invisible, and it looked as if the Trol held nothing. + current = Object.Instantiate(source); + current.SetActive(true); current.name = "TrolTrueFormLog"; + foreach (Collider c in current.GetComponentsInChildren(true)) Object.Destroy(c); + + // Hung the way AttachItem hangs it: on the joint at zero, then the item's equipoffset. + current.transform.SetParent(hand, false); current.transform.localPosition = Vector3.zero; current.transform.localRotation = Quaternion.identity; - current.transform.localScale = source.transform.localScale; - foreach (Collider c in current.GetComponentsInChildren(true)) Object.Destroy(c); + Transform offset = source.transform.parent != null ? source.transform.parent.Find("equipoffset") : null; + if (offset != null) + { + current.transform.localPosition += offset.position; + current.transform.localRotation *= offset.rotation; + } + + // AttachItem keeps the attach at its own WORLD size, and a vanilla troll stands at scale 1. + // This one is worn smaller or bigger, so the log takes the costume's share on top. Once + // set, the hand carries it through the grow and shrink like any child. + float handScale = hand.lossyScale.x; + float costume = model.transform.localScale.x; + current.transform.localScale = handScale > 0.0001f + ? source.transform.localScale * (costume / handScale) + : source.transform.localScale; + + if (logged.Add("log/" + source.name)) + { + Jotunn.Logger.LogInfo($"[Trol] True Form log '{log.Source}' in hand: hand scale {handScale:0.###}, " + + $"costume {costume:0.###}, offset {(offset != null ? "yes" : "no")}."); + } } // ─── Attacks ───────────────────────────────────────────────────────── From b2346c1437e44794b6e68cbc414553452a026c3b Mon Sep 17 00:00:00 2001 From: kanym Date: Sat, 17 Oct 2026 15:32:06 +0200 Subject: [PATCH 019/163] feat(trol): Legacy True Form switch, chosen per player The Troll Model option becomes Legacy True Form, off by default. On, True Form is the old one: the player's own Trol grown bigger, weapons in hand, body untouched, which player model mods such as VRM need. It is a local preference, not a synced one, so a server cannot force the troll costume on a VRM user. The owner publishes the choice on the ZDO and every other client reads it from there, so onlookers see each Trol the way that Trol's owner picked. --- JotunnModStub/ConfigSync.cs | 3 +++ JotunnModStub/Trol/TrolConfig.cs | 6 +++--- JotunnModStub/Trol/TrolTrueFormBehavior.cs | 3 ++- JotunnModStub/Trol/TrolTrueFormModel.cs | 13 ++++++++++++- 4 files changed, 20 insertions(+), 5 deletions(-) diff --git a/JotunnModStub/ConfigSync.cs b/JotunnModStub/ConfigSync.cs index 996168a..f743b4c 100644 --- a/JotunnModStub/ConfigSync.cs +++ b/JotunnModStub/ConfigSync.cs @@ -40,6 +40,9 @@ namespace RacesOfValheim private static readonly string[] LocalKeyParts = { "marker light", "tint", "colour", "color", "glow", "swarm scale", "log rounds", "debug", + // Each player picks their own True Form: a player model mod (VRM and the like) breaks + // under the troll costume, so a server cannot be allowed to force the costume on. + "legacy true form", }; public static void Apply(ConfigFile config) diff --git a/JotunnModStub/Trol/TrolConfig.cs b/JotunnModStub/Trol/TrolConfig.cs index 2588e9a..5521be7 100644 --- a/JotunnModStub/Trol/TrolConfig.cs +++ b/JotunnModStub/Trol/TrolConfig.cs @@ -51,7 +51,7 @@ namespace RacesOfValheim public static ConfigEntry TrueFormCooldown; public static ConfigEntry TrueFormScaleNormal; public static ConfigEntry TrueFormScaleAdvanced; - public static ConfigEntry TrueFormUseTrollModel; + public static ConfigEntry TrueFormLegacy; public static ConfigEntry TrueFormModelSize; public static ConfigEntry TrueFormTrollDamageShare; public static ConfigEntry TrueFormAttackReach; @@ -138,8 +138,8 @@ namespace RacesOfValheim new ConfigDescription("Model scale while in True Form, tier 5-6.", new AcceptableValueRange(1f, 4f))); TrueFormScaleAdvanced = config.Bind(trueForm, "Scale (Tier 7+)", 2.5f, new ConfigDescription("Model scale while in True Form, tier 7+.", new AcceptableValueRange(1f, 4f))); - TrueFormUseTrollModel = config.Bind(trueForm, "Troll Model", true, - new ConfigDescription("Wear Valheim's own troll in True Form, with its own punch and ground slam instead of your weapons. Off: the old True Form, a bigger Trol with weapons in hand.")); + TrueFormLegacy = config.Bind(trueForm, "Legacy True Form", false, + new ConfigDescription("Off: True Form wears Valheim's own troll, with its punch and ground slam instead of your weapons. On: the old True Form, your own Trol grown bigger with weapons in hand. Turn it on if you use a player model mod such as VRM, which needs the player's body to stay visible. Your own choice: other players see you the way you picked.")); TrueFormModelSize = config.Bind(trueForm, "Troll Model Size", 1f, new ConfigDescription("How tall the troll stands, as a share of the True Form size set by Scale above. 1 = exactly as tall as the old True Form.", new AcceptableValueRange(0.5f, 2f))); TrueFormTrollDamageShare = config.Bind(trueForm, "Troll Attack Damage", 0.5f, diff --git a/JotunnModStub/Trol/TrolTrueFormBehavior.cs b/JotunnModStub/Trol/TrolTrueFormBehavior.cs index 4cf4acd..4e17311 100644 --- a/JotunnModStub/Trol/TrolTrueFormBehavior.cs +++ b/JotunnModStub/Trol/TrolTrueFormBehavior.cs @@ -483,7 +483,8 @@ namespace RacesOfValheim if (nview == null || !nview.IsValid()) return; ZDO zdo = nview.GetZDO(); - bool active = TrolConfig.TrueFormUseTrollModel.Value && + // The owner's choice, not this client's: see TrolTrueFormModel.LegacyKey. + bool active = !zdo.GetBool(TrolTrueFormModel.LegacyKey, false) && !player.IsDead() && zdo.GetString("RacesOfValheim_Race", "Human") == "Trol" && zdo.GetBool(Trol_PlayerUpdate_Patch.TrueFormKey, false); diff --git a/JotunnModStub/Trol/TrolTrueFormModel.cs b/JotunnModStub/Trol/TrolTrueFormModel.cs index 5437696..ef02c33 100644 --- a/JotunnModStub/Trol/TrolTrueFormModel.cs +++ b/JotunnModStub/Trol/TrolTrueFormModel.cs @@ -37,6 +37,10 @@ namespace RacesOfValheim // Published by the owner after every trigger it fires, with a running count so the same // punch twice in a row still reads as two - see FenrirAttackSync. public const string AttackTriggerKey = "RacesOfValheim_TrolTrueFormAttack"; + + // The owner's Legacy True Form choice, so every other client draws this Trol the way its + // owner picked rather than the way the onlooker's own setting says. + public const string LegacyKey = "RacesOfValheim_TrolTrueFormLegacy"; private static int attackSeq; private static readonly int TrueFormHash = "SE_TrolTrueForm".GetStableHashCode(); @@ -96,7 +100,14 @@ namespace RacesOfValheim { if (player == null || player != Player.m_localPlayer) return; - bool wanted = TrolConfig.TrueFormUseTrollModel.Value && + bool legacy = TrolConfig.TrueFormLegacy.Value; + ZNetView nview = player.GetComponent(); + if (nview != null && nview.IsValid() && nview.GetZDO().GetBool(LegacyKey, false) != legacy) + { + nview.GetZDO().Set(LegacyKey, legacy); + } + + bool wanted = !legacy && !player.IsDead() && TrolRace.IsTrol() && player.GetSEMan().HaveStatusEffect(TrueFormHash); From b566adbfb9a84f31025b3009fc8899d18c91c1ee Mon Sep 17 00:00:00 2001 From: kanym Date: Sat, 17 Oct 2026 15:50:41 +0200 Subject: [PATCH 020/163] fix(factions): allied mobs spare a race's buildings with nobody home FactionStaticTargetPatch only vetoed a mob's piece target while an allied player stood within 100 m. Inside a troll cave that was the collapse bug: the Trol walks out, the resident Troll (its prefab has m_attackPlayerObjects) finds nobody to stop it, and the cooking station built there is in pieces when the Trol comes back. Every piece now carries the race of its builder on its ZDO, stamped in Piece.SetCreator at placement, and in Piece.Awake for older pieces the first time their builder loads them, so no timer and no scan. An allied mob of that race can't pick the piece as a target and its blows do it no damage, which also covers a swing at a foreign wall that would have hit the Trol's workbench next to it. A mob holding a grudge against the builder gets no such truce. --- .../Factions/FactionHostilityPatch.cs | 8 ++ JotunnModStub/Factions/FactionPieceTruce.cs | 120 ++++++++++++++++++ 2 files changed, 128 insertions(+) create mode 100644 JotunnModStub/Factions/FactionPieceTruce.cs diff --git a/JotunnModStub/Factions/FactionHostilityPatch.cs b/JotunnModStub/Factions/FactionHostilityPatch.cs index f8f873f..b445dbe 100644 --- a/JotunnModStub/Factions/FactionHostilityPatch.cs +++ b/JotunnModStub/Factions/FactionHostilityPatch.cs @@ -212,6 +212,14 @@ namespace RacesOfValheim Character monster = Traverse.Create(__instance).Field("m_character").Value; if (monster == null) return; + // A piece an allied race built is never a target, with or without anyone around. + // See FactionPieceTruce. + if (targetStatic.GetValue() is Component target && FactionPieceTruce.Protects(target.gameObject, monster)) + { + targetStatic.SetValue(null); + return; + } + foreach (Player player in Player.GetAllPlayers()) { if (Vector3.Distance(player.transform.position, monster.transform.position) > FactionCheckRange) continue; diff --git a/JotunnModStub/Factions/FactionPieceTruce.cs b/JotunnModStub/Factions/FactionPieceTruce.cs new file mode 100644 index 0000000..76321aa --- /dev/null +++ b/JotunnModStub/Factions/FactionPieceTruce.cs @@ -0,0 +1,120 @@ +using HarmonyLib; +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// Allied mobs leave a race's buildings alone whether or not anyone is home. + /// + /// FactionStaticTargetPatch only spares a base while an allied player stands within 100 m of + /// the mob. That left the troll cave bug: a Trol builds a cooking station inside a troll cave, + /// walks out, and the cave's resident Troll - m_attackPlayerObjects is true on its prefab - finds + /// nobody to stop it and smashes the station. The player came back to the materials on the floor. + /// + /// So every piece remembers the race of whoever built it (BuilderRaceKey on its ZDO), and an + /// allied mob of that race can neither pick it as a target nor damage it. The damage veto is + /// for the blows meant for something else: a Troll swinging at a Dvergar's wall must not take + /// the Trol's workbench next to it down too. The target veto is what keeps the Troll from + /// standing there forever: it never picks an allied piece, so once the foreign one is gone it + /// has nothing to swing at. + /// + /// A piece built before this existed carries no race. It gets one the next time its builder + /// loads it, from Piece.Awake, which runs anyway for every piece in a zone as it loads - so + /// there is no timer and no scan. Until then it is protected only the old way. + /// + public static class FactionPieceTruce + { + public const string BuilderRaceKey = "RacesOfValheim_BuilderRace"; + + /// True if this piece was built by a race whose ally is, + /// and the monster holds no grudge against the builder. + public static bool Protects(GameObject pieceObject, Character monster) + { + if (!FactionsConfig.Hostility || pieceObject == null || monster == null) return false; + if (monster.IsPlayer() || monster.IsTamed()) return false; + + ZNetView nview = pieceObject.GetComponentInParent(); + if (nview == null || !nview.IsValid()) return false; + + string race = nview.GetZDO().GetString(BuilderRaceKey, ""); + if (string.IsNullOrEmpty(race)) return false; + if (!FactionHostilityPatch.IsAlliedMob(race, monster.gameObject.name)) return false; + + // A mob fighting the builder right now is no ally of the builder's house either. + long creator = nview.GetZDO().GetLong(ZDOVars.s_creator, 0L); + if (creator != 0L) + { + foreach (Player player in Player.GetAllPlayers()) + { + if (player.GetPlayerID() == creator && RaceGrudge.Holds(monster, player)) return false; + } + } + return true; + } + + private static void Stamp(ZNetView nview) + { + Player local = Player.m_localPlayer; + if (local == null) return; + + string race = FactionHostilityPatch.GetPlayerRace(local); + if (string.IsNullOrEmpty(race)) return; + + nview.GetZDO().Set(BuilderRaceKey, race); + } + + /// A new piece: stamped by its builder the moment it is placed. + [HarmonyPatch(typeof(Piece), nameof(Piece.SetCreator))] + public static class Faction_PieceSetCreator_Patch + { + public static void Postfix(Piece __instance, long uid) + { + if (__instance == null || Player.m_localPlayer == null) return; + if (uid != Player.m_localPlayer.GetPlayerID()) return; + + ZNetView nview = __instance.GetComponent(); + if (nview == null || !nview.IsValid() || !nview.IsOwner()) return; + Stamp(nview); + } + } + + /// + /// An old piece: stamped by its builder the first time it loads for them. Only the ZDO's + /// owner writes, as everywhere else in the mod; a piece some other player owns right now + /// gets its race on a later load. + /// + [HarmonyPatch(typeof(Piece), "Awake")] + public static class Faction_PieceAwake_Patch + { + public static void Postfix(Piece __instance) + { + Player local = Player.m_localPlayer; + if (__instance == null || local == null) return; + + ZNetView nview = __instance.GetComponent(); + if (nview == null || !nview.IsValid() || !nview.IsOwner()) return; + + ZDO zdo = nview.GetZDO(); + if (zdo.GetLong(ZDOVars.s_creator, 0L) != local.GetPlayerID()) return; + if (!string.IsNullOrEmpty(zdo.GetString(BuilderRaceKey, ""))) return; + + Stamp(nview); + } + } + + /// + /// Blows from an allied mob land on nothing. Patched on Damage, the attacker's side, where + /// the mob is a live object; RPC_Damage runs on the piece's owner, who may not have it. + /// + [HarmonyPatch(typeof(WearNTear), nameof(WearNTear.Damage))] + public static class Faction_PieceDamage_Patch + { + public static bool Prefix(WearNTear __instance, HitData hit) + { + if (hit == null) return true; + Character attacker = hit.GetAttacker(); + return !Protects(__instance.gameObject, attacker); + } + } + } +} From 87d0f2642c98894fdae50d9083eb97a8d74fbc92 Mon Sep 17 00:00:00 2001 From: kanym Date: Sat, 17 Oct 2026 15:51:53 +0200 Subject: [PATCH 021/163] fix(texts): four messages showed as [msg_...] Four tokens the mod printed exist in no vanilla table (checked on Valheim 1.0.20) and were never registered by the mod, so players saw the raw name in brackets. - $msg_eatanother (Trol, a food still being digested): vanilla's $msg_nomore, "You can't eat more $1", called as Player.CanEat calls it. - $msg_canteatanymore (Trol, every stomach full): vanilla's $msg_isfull. - $msg_ate (Aswid, Vae Victis): vanilla's $msg_consumed. - $msg_notenoughmoney (Dvergar bank, Trol totem): a new mod text, rov_msg_not_enough_coins, in English, Italian and Russian. --- JotunnModStub/Aswid/AswidRace.cs | 3 ++- JotunnModStub/Dvergar/DvergarBancoBehaviour.cs | 2 +- JotunnModStub/Translations/English/messages.json | 1 + JotunnModStub/Translations/Italian/messages.json | 1 + JotunnModStub/Translations/Russian/messages.json | 1 + JotunnModStub/Trol/TrolFoodPatches.cs | 10 ++++++---- JotunnModStub/Trol/TrolTotemBehaviour.cs | 2 +- 7 files changed, 13 insertions(+), 7 deletions(-) diff --git a/JotunnModStub/Aswid/AswidRace.cs b/JotunnModStub/Aswid/AswidRace.cs index b95daff..fb949a3 100644 --- a/JotunnModStub/Aswid/AswidRace.cs +++ b/JotunnModStub/Aswid/AswidRace.cs @@ -1258,7 +1258,8 @@ namespace RacesOfValheim { // Show the Vae Victis message in the center of the screen Player.m_localPlayer.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_aswid_vae_victis")); - Player.m_localPlayer.Message(MessageHud.MessageType.TopLeft, "$msg_ate " + addedItem.m_shared.m_name); + // "$msg_ate" exists in no vanilla table and players saw [msg_ate]; vanilla's "Consumed" reads the same. + Player.m_localPlayer.Message(MessageHud.MessageType.TopLeft, "$msg_consumed " + addedItem.m_shared.m_name); // Vae Victis XP logic - similar to Dead Raiser Player.m_localPlayer.RaiseSkill(Skills.SkillType.BloodMagic, 1f); diff --git a/JotunnModStub/Dvergar/DvergarBancoBehaviour.cs b/JotunnModStub/Dvergar/DvergarBancoBehaviour.cs index 444b065..fcdd94d 100644 --- a/JotunnModStub/Dvergar/DvergarBancoBehaviour.cs +++ b/JotunnModStub/Dvergar/DvergarBancoBehaviour.cs @@ -157,7 +157,7 @@ namespace RacesOfValheim if (CountCoins(inventory) < price) { - player.Message(MessageHud.MessageType.Center, "$msg_notenoughmoney"); + player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_not_enough_coins")); return; } diff --git a/JotunnModStub/Translations/English/messages.json b/JotunnModStub/Translations/English/messages.json index 6e6ee1e..8f7c7fa 100644 --- a/JotunnModStub/Translations/English/messages.json +++ b/JotunnModStub/Translations/English/messages.json @@ -106,6 +106,7 @@ "rov_msg_fenrir_trough_takes_line_runs_deeper": "The trough takes it. The line runs deeper now.", "rov_msg_fenrir_wants_meat_any_meat": "It wants meat. Any meat.", "rov_msg_fenrir_wants_what_yagluth_left_behind": "It wants what Yagluth left behind.", + "rov_msg_not_enough_coins": "Not enough coins", "rov_msg_skadi_are_drake": "You are a Drake!", "rov_msg_skadi_are_fader": "You are Fader!", "rov_msg_skadi_are_moder": "You are Moder!", diff --git a/JotunnModStub/Translations/Italian/messages.json b/JotunnModStub/Translations/Italian/messages.json index 6d3cb6f..f0e20bb 100644 --- a/JotunnModStub/Translations/Italian/messages.json +++ b/JotunnModStub/Translations/Italian/messages.json @@ -106,6 +106,7 @@ "rov_msg_fenrir_trough_takes_line_runs_deeper": "La mangiatoia lo accetta. Ora la discendenza va più a fondo.", "rov_msg_fenrir_wants_meat_any_meat": "Vuole carne. Qualsiasi carne.", "rov_msg_fenrir_wants_what_yagluth_left_behind": "Vuole ciò che Yagluth ha lasciato.", + "rov_msg_not_enough_coins": "Monete insufficienti", "rov_msg_skadi_are_drake": "Sei un Drake!", "rov_msg_skadi_are_fader": "Sei Fader!", "rov_msg_skadi_are_moder": "Sei Moder!", diff --git a/JotunnModStub/Translations/Russian/messages.json b/JotunnModStub/Translations/Russian/messages.json index 2e70a33..3ef6918 100644 --- a/JotunnModStub/Translations/Russian/messages.json +++ b/JotunnModStub/Translations/Russian/messages.json @@ -106,6 +106,7 @@ "rov_msg_fenrir_trough_takes_line_runs_deeper": "Кормушка принимает жертву. Родословная стаи крепнет.", "rov_msg_fenrir_wants_meat_any_meat": "Требуется мясо. Любое мясо.", "rov_msg_fenrir_wants_what_yagluth_left_behind": "Требуется то, что осталось после падения Яглута.", + "rov_msg_not_enough_coins": "Недостаточно монет", "rov_msg_skadi_are_drake": "Вы — Дрейк!", "rov_msg_skadi_are_fader": "Вы — Прародитель!", "rov_msg_skadi_are_moder": "Вы — Матерь!", diff --git a/JotunnModStub/Trol/TrolFoodPatches.cs b/JotunnModStub/Trol/TrolFoodPatches.cs index b0d452d..97232bb 100644 --- a/JotunnModStub/Trol/TrolFoodPatches.cs +++ b/JotunnModStub/Trol/TrolFoodPatches.cs @@ -90,7 +90,7 @@ namespace RacesOfValheim if (f.m_item.m_shared.m_name != item.m_shared.m_name) continue; if (f.CanEatAgain()) return true; - __instance.Message(MessageHud.MessageType.Center, "$msg_eatanother"); + __instance.Message(MessageHud.MessageType.Center, Localization.instance.Localize("$msg_nomore", item.m_shared.m_name)); __result = false; return false; } @@ -110,12 +110,12 @@ namespace RacesOfValheim if (has4 && food4.m_item.m_shared.m_name == item.m_shared.m_name) { if (canEat4) { TrolFoodManager.SetExtraFood(__instance, item); ConsumeItemEffect(__instance, item); __result = true; return false; } - else { __instance.Message(MessageHud.MessageType.Center, "$msg_eatanother"); __result = false; return false; } + else { __instance.Message(MessageHud.MessageType.Center, Localization.instance.Localize("$msg_nomore", item.m_shared.m_name)); __result = false; return false; } } if (has5 && food5.m_item.m_shared.m_name == item.m_shared.m_name) { if (state5 && canEat5) { TrolFoodManager.SetExtraFood5(__instance, item); ConsumeItemEffect(__instance, item); __result = true; return false; } - else { __instance.Message(MessageHud.MessageType.Center, "$msg_eatanother"); __result = false; return false; } + else { __instance.Message(MessageHud.MessageType.Center, Localization.instance.Localize("$msg_nomore", item.m_shared.m_name)); __result = false; return false; } } // 3. A free vanilla slot takes it the vanilla way. @@ -137,7 +137,9 @@ namespace RacesOfValheim return false; } - __instance.Message(MessageHud.MessageType.Center, "$msg_canteatanymore"); + // Vanilla's own "You are full already", the line Player.CanEat shows for a full stomach. + // "$msg_canteatanymore" was never a vanilla token, so players saw [msg_canteatanymore]. + __instance.Message(MessageHud.MessageType.Center, "$msg_isfull"); __result = false; return false; } diff --git a/JotunnModStub/Trol/TrolTotemBehaviour.cs b/JotunnModStub/Trol/TrolTotemBehaviour.cs index cf040b6..d43f028 100644 --- a/JotunnModStub/Trol/TrolTotemBehaviour.cs +++ b/JotunnModStub/Trol/TrolTotemBehaviour.cs @@ -157,7 +157,7 @@ namespace RacesOfValheim if (CountCoins(inventory) < troop.Price) { - player.Message(MessageHud.MessageType.Center, "$msg_notenoughmoney"); + player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_not_enough_coins")); return; } From 916ba5bd6f853973bc1c125d537bc4c1ed287bbd Mon Sep 17 00:00:00 2001 From: kanym Date: Sat, 17 Oct 2026 15:59:08 +0200 Subject: [PATCH 022/163] fix(pieces): placement ghost vanished off terrain for most stations Eleven pieces set m_groundPiece. Player.UpdatePlacementGhost switches the ghost off outright and returns whenever the aim is not on a Heightmap, which vanilla means for hoe and cultivator pieces. Floors, rocks and a troll cave's mesh floor are not a Heightmap, so players saw no ghost at all there, and with either flag Valheim never shows the blue placement marker. Reported for the Trol War Totem. m_groundPiece is off everywhere now. The stations (War Totem, Cursed Body Pile, Dvergar Bank, Rune Barrel, Pack Trough, Skadi Golem, Bone Servants) drop m_groundOnly too and go on floors, foundations and in caves, like the Bone Pile since 1.5.8. The living pieces (Furling bushes, Sverm nest and Hive Market, Trenta Elder Root) keep m_groundOnly: terrain only, and the ghost shows red elsewhere. --- JotunnModStub/Butler/BoneServant.cs | 8 ++++++-- JotunnModStub/Draugh/DraughSpawner.cs | 8 ++++++-- JotunnModStub/Dvergar/DvergarBanco.cs | 8 ++++++-- JotunnModStub/Dvergar/DvergarBotte.cs | 8 ++++++-- JotunnModStub/Fenrir/FenrirMangiatoia.cs | 8 ++++++-- JotunnModStub/Furling/FurlingCrops.cs | 5 ++++- JotunnModStub/Skadi/SkadiGolem.cs | 8 ++++++-- JotunnModStub/Sverm/SvermHive.cs | 5 ++++- JotunnModStub/Sverm/SvermHiveStore.cs | 5 ++++- JotunnModStub/Trenta/TrentaElderRoot.cs | 5 ++++- JotunnModStub/Trol/TrolTotem.cs | 8 ++++++-- 11 files changed, 58 insertions(+), 18 deletions(-) diff --git a/JotunnModStub/Butler/BoneServant.cs b/JotunnModStub/Butler/BoneServant.cs index 6126d1d..714016f 100644 --- a/JotunnModStub/Butler/BoneServant.cs +++ b/JotunnModStub/Butler/BoneServant.cs @@ -233,8 +233,12 @@ namespace RacesOfValheim piece.m_resources = new Piece.Requirement[0]; piece.m_name = displayName; piece.m_canBeRemoved = true; - piece.m_groundPiece = true; - piece.m_groundOnly = true; + // Neither flag, like the Bone Pile. m_groundPiece made Player.UpdatePlacementGhost switch + // the ghost off outright wherever the aim was not terrain - floors, rocks, a troll cave's + // mesh floor - so players saw no ghost at all and could not tell why. A station belongs + // in a house or a cave as much as outside. + piece.m_groundPiece = false; + piece.m_groundOnly = false; piece.m_icon = icon; Piece template = PrefabManager.Cache.GetPrefab("piece_workbench"); diff --git a/JotunnModStub/Draugh/DraughSpawner.cs b/JotunnModStub/Draugh/DraughSpawner.cs index a2604b2..61ea53d 100644 --- a/JotunnModStub/Draugh/DraughSpawner.cs +++ b/JotunnModStub/Draugh/DraughSpawner.cs @@ -251,8 +251,12 @@ namespace RacesOfValheim piece.m_resources = new Piece.Requirement[0]; piece.m_name = PieceDisplayName; piece.m_canBeRemoved = true; - piece.m_groundPiece = true; - piece.m_groundOnly = true; + // Neither flag, like the Bone Pile. m_groundPiece made Player.UpdatePlacementGhost switch + // the ghost off outright wherever the aim was not terrain - floors, rocks, a troll cave's + // mesh floor - so players saw no ghost at all and could not tell why. A station belongs + // in a house or a cave as much as outside. + piece.m_groundPiece = false; + piece.m_groundOnly = false; piece.m_icon = BorrowIcon(TrophyDraugr); // Learned on the Furling's bushes: a Piece added to world scenery is born with no icon diff --git a/JotunnModStub/Dvergar/DvergarBanco.cs b/JotunnModStub/Dvergar/DvergarBanco.cs index 34ab389..a912a2d 100644 --- a/JotunnModStub/Dvergar/DvergarBanco.cs +++ b/JotunnModStub/Dvergar/DvergarBanco.cs @@ -335,8 +335,12 @@ namespace RacesOfValheim piece.m_resources = new Piece.Requirement[0]; piece.m_name = PieceDisplayName; piece.m_canBeRemoved = true; - piece.m_groundPiece = true; - piece.m_groundOnly = true; + // Neither flag, like the Bone Pile. m_groundPiece made Player.UpdatePlacementGhost switch + // the ghost off outright wherever the aim was not terrain - floors, rocks, a troll cave's + // mesh floor - so players saw no ghost at all and could not tell why. A station belongs + // in a house or a cave as much as outside. + piece.m_groundPiece = false; + piece.m_groundOnly = false; piece.m_icon = BorrowIcon("TrophyDvergr"); Piece template = PrefabManager.Cache.GetPrefab("piece_workbench"); diff --git a/JotunnModStub/Dvergar/DvergarBotte.cs b/JotunnModStub/Dvergar/DvergarBotte.cs index e0a7953..69f30bf 100644 --- a/JotunnModStub/Dvergar/DvergarBotte.cs +++ b/JotunnModStub/Dvergar/DvergarBotte.cs @@ -90,8 +90,12 @@ namespace RacesOfValheim piece.m_resources = new Piece.Requirement[0]; piece.m_name = PieceDisplayName; piece.m_canBeRemoved = true; - piece.m_groundPiece = true; - piece.m_groundOnly = true; + // Neither flag, like the Bone Pile. m_groundPiece made Player.UpdatePlacementGhost switch + // the ghost off outright wherever the aim was not terrain - floors, rocks, a troll cave's + // mesh floor - so players saw no ghost at all and could not tell why. A station belongs + // in a house or a cave as much as outside. + piece.m_groundPiece = false; + piece.m_groundOnly = false; piece.m_icon = BorrowIcon("MeadHealthMinor") ?? BorrowIcon("TrophyDvergr"); Piece template = PrefabManager.Cache.GetPrefab("piece_workbench"); diff --git a/JotunnModStub/Fenrir/FenrirMangiatoia.cs b/JotunnModStub/Fenrir/FenrirMangiatoia.cs index 8280607..93e2e67 100644 --- a/JotunnModStub/Fenrir/FenrirMangiatoia.cs +++ b/JotunnModStub/Fenrir/FenrirMangiatoia.cs @@ -326,8 +326,12 @@ namespace RacesOfValheim piece.m_resources = new Piece.Requirement[0]; piece.m_name = PieceDisplayName; piece.m_canBeRemoved = true; - piece.m_groundPiece = true; - piece.m_groundOnly = true; + // Neither flag, like the Bone Pile. m_groundPiece made Player.UpdatePlacementGhost switch + // the ghost off outright wherever the aim was not terrain - floors, rocks, a troll cave's + // mesh floor - so players saw no ghost at all and could not tell why. A station belongs + // in a house or a cave as much as outside. + piece.m_groundPiece = false; + piece.m_groundOnly = false; piece.m_icon = BorrowIcon("TrophyFenring"); Piece template = PrefabManager.Cache.GetPrefab("piece_workbench"); diff --git a/JotunnModStub/Furling/FurlingCrops.cs b/JotunnModStub/Furling/FurlingCrops.cs index 79cf5c9..4a55b8b 100644 --- a/JotunnModStub/Furling/FurlingCrops.cs +++ b/JotunnModStub/Furling/FurlingCrops.cs @@ -381,7 +381,10 @@ namespace RacesOfValheim piece.m_craftingStation = null; piece.m_resources = new Piece.Requirement[0]; piece.m_canBeRemoved = true; - piece.m_groundPiece = true; + // Terrain only, as a living thing should be - but through m_groundOnly alone, which shows + // the ghost red off the terrain. m_groundPiece switched the ghost off outright there + // (Player.UpdatePlacementGhost), and players saw nothing at all. + piece.m_groundPiece = false; piece.m_groundOnly = true; piece.m_cultivatedGroundOnly = false; // a bush of rocks does not want tilled soil piece.m_icon = BorrowIcon(berry.YieldPrefab); diff --git a/JotunnModStub/Skadi/SkadiGolem.cs b/JotunnModStub/Skadi/SkadiGolem.cs index 99fca6a..1f14080 100644 --- a/JotunnModStub/Skadi/SkadiGolem.cs +++ b/JotunnModStub/Skadi/SkadiGolem.cs @@ -264,8 +264,12 @@ namespace RacesOfValheim piece.m_resources = new Piece.Requirement[0]; piece.m_name = DisplayName; piece.m_canBeRemoved = true; - piece.m_groundPiece = true; - piece.m_groundOnly = true; + // Neither flag, like the Bone Pile. m_groundPiece made Player.UpdatePlacementGhost switch + // the ghost off outright wherever the aim was not terrain - floors, rocks, a troll cave's + // mesh floor - so players saw no ghost at all and could not tell why. A station belongs + // in a house or a cave as much as outside. + piece.m_groundPiece = false; + piece.m_groundOnly = false; piece.m_icon = BorrowIcon(CrystalItem); PieceManager.Instance.AddPiece(new CustomPiece(prefab, fixReference: false, new PieceConfig diff --git a/JotunnModStub/Sverm/SvermHive.cs b/JotunnModStub/Sverm/SvermHive.cs index cc30a09..6116fab 100644 --- a/JotunnModStub/Sverm/SvermHive.cs +++ b/JotunnModStub/Sverm/SvermHive.cs @@ -96,7 +96,10 @@ namespace RacesOfValheim Piece piece = prefab.GetComponent() ?? prefab.AddComponent(); piece.m_name = DisplayName; piece.m_description = "$rov_piece_sverm_broodmound_desc"; - piece.m_groundPiece = true; + // Terrain only, as a living thing should be - but through m_groundOnly alone, which shows + // the ghost red off the terrain. m_groundPiece switched the ghost off outright there + // (Player.UpdatePlacementGhost), and players saw nothing at all. + piece.m_groundPiece = false; piece.m_groundOnly = true; piece.m_cultivatedGroundOnly = false; piece.m_canBeRemoved = true; diff --git a/JotunnModStub/Sverm/SvermHiveStore.cs b/JotunnModStub/Sverm/SvermHiveStore.cs index ef96cc7..0699fda 100644 --- a/JotunnModStub/Sverm/SvermHiveStore.cs +++ b/JotunnModStub/Sverm/SvermHiveStore.cs @@ -324,7 +324,10 @@ namespace RacesOfValheim piece.m_resources = new Piece.Requirement[0]; piece.m_name = DisplayName; piece.m_description = "$rov_piece_sverm_hivemarket_desc"; - piece.m_groundPiece = true; + // Terrain only, as a living thing should be - but through m_groundOnly alone, which shows + // the ghost red off the terrain. m_groundPiece switched the ghost off outright there + // (Player.UpdatePlacementGhost), and players saw nothing at all. + piece.m_groundPiece = false; piece.m_groundOnly = true; piece.m_canBeRemoved = true; diff --git a/JotunnModStub/Trenta/TrentaElderRoot.cs b/JotunnModStub/Trenta/TrentaElderRoot.cs index ba21936..8e8e421 100644 --- a/JotunnModStub/Trenta/TrentaElderRoot.cs +++ b/JotunnModStub/Trenta/TrentaElderRoot.cs @@ -83,7 +83,10 @@ namespace RacesOfValheim piece.m_resources = new Piece.Requirement[0]; piece.m_name = TrentaConfig.ElderRootDisplayName; piece.m_canBeRemoved = true; - piece.m_groundPiece = true; + // Terrain only, as a living thing should be - but through m_groundOnly alone, which shows + // the ghost red off the terrain. m_groundPiece switched the ghost off outright there + // (Player.UpdatePlacementGhost), and players saw nothing at all. + piece.m_groundPiece = false; piece.m_groundOnly = true; piece.m_icon = icon; diff --git a/JotunnModStub/Trol/TrolTotem.cs b/JotunnModStub/Trol/TrolTotem.cs index 99f94c9..5bd38f8 100644 --- a/JotunnModStub/Trol/TrolTotem.cs +++ b/JotunnModStub/Trol/TrolTotem.cs @@ -303,8 +303,12 @@ namespace RacesOfValheim piece.m_resources = new Piece.Requirement[0]; piece.m_name = PieceDisplayName; piece.m_canBeRemoved = true; - piece.m_groundPiece = true; - piece.m_groundOnly = true; + // Neither flag, like the Bone Pile. m_groundPiece made Player.UpdatePlacementGhost switch + // the ghost off outright wherever the aim was not terrain - floors, rocks, a troll cave's + // mesh floor - so players saw no ghost at all and could not tell why. A station belongs + // in a house or a cave as much as outside. + piece.m_groundPiece = false; + piece.m_groundOnly = false; piece.m_icon = BorrowIcon(TrollHead); Piece template = PrefabManager.Cache.GetPrefab("piece_workbench"); From edc7fd33b7ee1aa567ddc4c84cd888a1efb2f0b4 Mon Sep 17 00:00:00 2001 From: kanym Date: Sat, 17 Oct 2026 16:11:16 +0200 Subject: [PATCH 023/163] debug: F8 dumps the build ghost and the placement ray (temporary) --- JotunnModStub/PlacementGhostDebug.cs | 70 ++++++++++++++++++++++++++++ JotunnModStub/RacesOfValheim.cs | 2 + 2 files changed, 72 insertions(+) create mode 100644 JotunnModStub/PlacementGhostDebug.cs diff --git a/JotunnModStub/PlacementGhostDebug.cs b/JotunnModStub/PlacementGhostDebug.cs new file mode 100644 index 0000000..17fd667 --- /dev/null +++ b/JotunnModStub/PlacementGhostDebug.cs @@ -0,0 +1,70 @@ +using System.Text; +using HarmonyLib; +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// TEMPORARY DEBUG. F8 dumps the build ghost in hand and what the placement ray hits, to the + /// console and the BepInEx log - for the Trol War Totem, whose ghost stays invisible where every + /// other station's now shows. Remove once that is fixed. + /// + public class PlacementGhostDebug : MonoBehaviour + { + private void Update() + { + if (!Input.GetKeyDown(KeyCode.F8)) return; + + Player player = Player.m_localPlayer; + if (player == null) return; + + var sb = new StringBuilder(); + GameObject ghost = Traverse.Create(player).Field("m_placementGhost").Value; + sb.AppendLine($"[GhostDebug] status={Traverse.Create(player).Field("m_placementStatus").GetValue()} ghost={(ghost != null ? ghost.name : "none")}"); + + Camera cam = GameCamera.instance != null ? GameCamera.instance.GetComponent() : null; + if (GameCamera.instance != null && Physics.Raycast(GameCamera.instance.transform.position, GameCamera.instance.transform.forward, out RaycastHit hit, 50f)) + { + sb.AppendLine($"[GhostDebug] ray hit '{hit.collider.name}' layer={LayerMask.LayerToName(hit.collider.gameObject.layer)} " + + $"dist={hit.distance:0.0} heightmap={(hit.collider.GetComponent() != null)} rigidbody={(hit.collider.attachedRigidbody != null)}"); + } + + if (ghost != null) + { + sb.AppendLine($"[GhostDebug] ghost active={ghost.activeInHierarchy} pos={ghost.transform.position} scale={ghost.transform.lossyScale} " + + $"layer={LayerMask.LayerToName(ghost.layer)} cameraMask has ghost layer={(cam != null && (cam.cullingMask & (1 << ghost.layer)) != 0)}"); + + foreach (LODGroup lod in ghost.GetComponentsInChildren(true)) + { + sb.AppendLine($"[GhostDebug] LODGroup on '{lod.name}' enabled={lod.enabled} active={lod.gameObject.activeInHierarchy} lods={lod.lodCount}"); + } + + foreach (Renderer r in ghost.GetComponentsInChildren(true)) + { + Material m = r.sharedMaterial; + sb.AppendLine($"[GhostDebug] renderer '{PathOf(r.transform, ghost.transform)}' {r.GetType().Name} enabled={r.enabled} " + + $"forceOff={r.forceRenderingOff} active={r.gameObject.activeInHierarchy} visible={r.isVisible} " + + $"layer={LayerMask.LayerToName(r.gameObject.layer)} bounds={r.bounds.size} " + + $"shader={(m != null && m.shader != null ? m.shader.name : "none")}"); + } + } + + string text = sb.ToString(); + Jotunn.Logger.LogInfo(text); + if (Console.instance != null) + { + foreach (string line in text.Split('\n')) + { + if (!string.IsNullOrWhiteSpace(line)) Console.instance.Print(line.TrimEnd()); + } + } + } + + private static string PathOf(Transform t, Transform root) + { + string path = t.name; + for (Transform p = t.parent; p != null && p != root; p = p.parent) path = p.name + "/" + path; + return path; + } + } +} diff --git a/JotunnModStub/RacesOfValheim.cs b/JotunnModStub/RacesOfValheim.cs index e6f8289..6bb439d 100644 --- a/JotunnModStub/RacesOfValheim.cs +++ b/JotunnModStub/RacesOfValheim.cs @@ -69,6 +69,8 @@ namespace RacesOfValheim // Not a race: a perk two races share (Skadi and Trol build inside troll caves), so it // gets its own component rather than living inside either one's Update. gameObject.AddComponent(); + // TEMPORARY DEBUG: F8 dumps the build ghost (Trol War Totem ghost investigation). + gameObject.AddComponent(); PrefabManager.OnVanillaPrefabsAvailable += CreateAllModAssets; CommandManager.Instance.AddConsoleCommand(new ResetRaceCommand()); CommandManager.Instance.AddConsoleCommand(new CheckProgressionCommand()); From e1bd3b66e16e6fc4d2782ac0dda7ea5aa50a555b Mon Sep 17 00:00:00 2001 From: kanym Date: Sat, 17 Oct 2026 16:19:03 +0200 Subject: [PATCH 024/163] fix(trol): War Totem ghost invisible everywhere The totem borrowed its look from the GoblinTotem item, whose root holds a ParticleSystem while the mesh sits in its attach child. Player.SetupPlacementGhost switches off every GameObject with a ParticleSystem, so it took the root and the mesh with it: the F8 dump showed TotemModel/model/attach/model active=False on the ghost. The Yagluth head (TrophyGoblinKing) is built the same way. Both now borrow the item's attach child, which is the mesh itself. ModelBorrow switches the copy on, since an item's attach is stored inactive in its prefab. --- JotunnModStub/ModelBorrow.cs | 5 +++++ JotunnModStub/Trol/TrolTotem.cs | 19 +++++++++++++++++-- 2 files changed, 22 insertions(+), 2 deletions(-) diff --git a/JotunnModStub/ModelBorrow.cs b/JotunnModStub/ModelBorrow.cs index b064361..20b2ded 100644 --- a/JotunnModStub/ModelBorrow.cs +++ b/JotunnModStub/ModelBorrow.cs @@ -89,6 +89,11 @@ namespace RacesOfValheim copy.transform.localRotation = localRotation; copy.transform.localScale = Vector3.one; + // An item's "attach" child is stored switched off in its prefab (VisEquipment turns it on + // when it is worn), so a copy of one comes out switched off too. The holder above is still + // inactive, so turning the copy on wakes nothing. + if (!copy.activeSelf) copy.SetActive(true); + // Everything that is not a Renderer or a Transform. Order matters for the same reason it did // on the Aswid's lights: behaviours first, then the things they hold references to. foreach (MonoBehaviour behaviour in copy.GetComponentsInChildren(true)) diff --git a/JotunnModStub/Trol/TrolTotem.cs b/JotunnModStub/Trol/TrolTotem.cs index 5bd38f8..f3d567f 100644 --- a/JotunnModStub/Trol/TrolTotem.cs +++ b/JotunnModStub/Trol/TrolTotem.cs @@ -239,7 +239,7 @@ namespace RacesOfValheim // The look the player asked for: the totem itself, not a log with a head on it. Grounded on // its own base, so Vector3.zero really is "standing on the spot the hammer picked". - GameObject totemModel = ModelBorrow.Attach(prefab.transform, "TotemModel", "GoblinTotem", + GameObject totemModel = ModelBorrow.Attach(prefab.transform, "TotemModel", ItemMesh("GoblinTotem"), Vector3.zero, Quaternion.identity, TotemHeight, "Trol"); TrolTotemBehaviour totem = prefab.AddComponent(); @@ -293,7 +293,7 @@ namespace RacesOfValheim Jotunn.Logger.LogInfo($"[Trol] Totem crown measured at {crown:0.##} m; the king's head is " + $"{HeadSize} m across and sunk {HeadSize * HeadSink:0.##} m into it."); - totem.m_yagluthHead = ModelBorrow.Attach(prefab.transform, "TotemHeadYagluth", YagluthHead, + totem.m_yagluthHead = ModelBorrow.Attach(prefab.transform, "TotemHeadYagluth", ItemMesh(YagluthHead), new Vector3(0f, crown - HeadSize * HeadSink, 0f), HeadTilt, HeadSize, "Trol"); totem.m_yagluthHead.SetActive(false); @@ -329,6 +329,21 @@ namespace RacesOfValheim })); } + /// + /// The part of an item that IS the item: its "attach" child, which holds the mesh, rather than + /// the whole prefab. GoblinTotem carries a ParticleSystem on its root, and + /// Player.SetupPlacementGhost switches off every GameObject that has one - taking the root and, + /// with it, the mesh underneath. That is why the War Totem showed no ghost anywhere while every + /// other station did. TrophyGoblinKing is built the same way. Falls back to the whole prefab + /// for an item without an attach. + /// + private static GameObject ItemMesh(string itemPrefab) + { + GameObject source = PrefabManager.Cache.GetPrefab(itemPrefab); + Transform attach = source != null ? source.transform.Find("attach") : null; + return attach != null ? attach.gameObject : source; + } + public static void EnsureKnown(Player player) { if (player == null) return; From 0cc10b437e41642f6e6f35de1009ee8ada314dd5 Mon Sep 17 00:00:00 2001 From: kanym Date: Sat, 17 Oct 2026 16:21:50 +0200 Subject: [PATCH 025/163] Revert "debug: F8 dumps the build ghost and the placement ray (temporary)" This reverts commit edc7fd33b7ee1aa567ddc4c84cd888a1efb2f0b4. --- JotunnModStub/PlacementGhostDebug.cs | 70 ---------------------------- JotunnModStub/RacesOfValheim.cs | 2 - 2 files changed, 72 deletions(-) delete mode 100644 JotunnModStub/PlacementGhostDebug.cs diff --git a/JotunnModStub/PlacementGhostDebug.cs b/JotunnModStub/PlacementGhostDebug.cs deleted file mode 100644 index 17fd667..0000000 --- a/JotunnModStub/PlacementGhostDebug.cs +++ /dev/null @@ -1,70 +0,0 @@ -using System.Text; -using HarmonyLib; -using UnityEngine; - -namespace RacesOfValheim -{ - /// - /// TEMPORARY DEBUG. F8 dumps the build ghost in hand and what the placement ray hits, to the - /// console and the BepInEx log - for the Trol War Totem, whose ghost stays invisible where every - /// other station's now shows. Remove once that is fixed. - /// - public class PlacementGhostDebug : MonoBehaviour - { - private void Update() - { - if (!Input.GetKeyDown(KeyCode.F8)) return; - - Player player = Player.m_localPlayer; - if (player == null) return; - - var sb = new StringBuilder(); - GameObject ghost = Traverse.Create(player).Field("m_placementGhost").Value; - sb.AppendLine($"[GhostDebug] status={Traverse.Create(player).Field("m_placementStatus").GetValue()} ghost={(ghost != null ? ghost.name : "none")}"); - - Camera cam = GameCamera.instance != null ? GameCamera.instance.GetComponent() : null; - if (GameCamera.instance != null && Physics.Raycast(GameCamera.instance.transform.position, GameCamera.instance.transform.forward, out RaycastHit hit, 50f)) - { - sb.AppendLine($"[GhostDebug] ray hit '{hit.collider.name}' layer={LayerMask.LayerToName(hit.collider.gameObject.layer)} " + - $"dist={hit.distance:0.0} heightmap={(hit.collider.GetComponent() != null)} rigidbody={(hit.collider.attachedRigidbody != null)}"); - } - - if (ghost != null) - { - sb.AppendLine($"[GhostDebug] ghost active={ghost.activeInHierarchy} pos={ghost.transform.position} scale={ghost.transform.lossyScale} " + - $"layer={LayerMask.LayerToName(ghost.layer)} cameraMask has ghost layer={(cam != null && (cam.cullingMask & (1 << ghost.layer)) != 0)}"); - - foreach (LODGroup lod in ghost.GetComponentsInChildren(true)) - { - sb.AppendLine($"[GhostDebug] LODGroup on '{lod.name}' enabled={lod.enabled} active={lod.gameObject.activeInHierarchy} lods={lod.lodCount}"); - } - - foreach (Renderer r in ghost.GetComponentsInChildren(true)) - { - Material m = r.sharedMaterial; - sb.AppendLine($"[GhostDebug] renderer '{PathOf(r.transform, ghost.transform)}' {r.GetType().Name} enabled={r.enabled} " + - $"forceOff={r.forceRenderingOff} active={r.gameObject.activeInHierarchy} visible={r.isVisible} " + - $"layer={LayerMask.LayerToName(r.gameObject.layer)} bounds={r.bounds.size} " + - $"shader={(m != null && m.shader != null ? m.shader.name : "none")}"); - } - } - - string text = sb.ToString(); - Jotunn.Logger.LogInfo(text); - if (Console.instance != null) - { - foreach (string line in text.Split('\n')) - { - if (!string.IsNullOrWhiteSpace(line)) Console.instance.Print(line.TrimEnd()); - } - } - } - - private static string PathOf(Transform t, Transform root) - { - string path = t.name; - for (Transform p = t.parent; p != null && p != root; p = p.parent) path = p.name + "/" + path; - return path; - } - } -} diff --git a/JotunnModStub/RacesOfValheim.cs b/JotunnModStub/RacesOfValheim.cs index 6bb439d..e6f8289 100644 --- a/JotunnModStub/RacesOfValheim.cs +++ b/JotunnModStub/RacesOfValheim.cs @@ -69,8 +69,6 @@ namespace RacesOfValheim // Not a race: a perk two races share (Skadi and Trol build inside troll caves), so it // gets its own component rather than living inside either one's Update. gameObject.AddComponent(); - // TEMPORARY DEBUG: F8 dumps the build ghost (Trol War Totem ghost investigation). - gameObject.AddComponent(); PrefabManager.OnVanillaPrefabsAvailable += CreateAllModAssets; CommandManager.Instance.AddConsoleCommand(new ResetRaceCommand()); CommandManager.Instance.AddConsoleCommand(new CheckProgressionCommand()); From 5b2e5f4f86ac2df15e346f83fa8fdf32bbaa030f Mon Sep 17 00:00:00 2001 From: kanym Date: Sat, 17 Oct 2026 16:24:09 +0200 Subject: [PATCH 026/163] feat(stations): the race is a build requirement, shown in the panel Every race station is listed in RaceStationLock with the race (or races) that may build it. The build panel shows it in the requirement row after the materials and the crafting station, with the race's icon from the race menu and its translated name, blinking red when the player is not of that race, the way vanilla flags a missing station. Player.HaveRequirements answers false for CanBuild, so the piece is greyed and a click gets vanilla's "Missing requirements". IsKnown and CanAlmostBuild stay vanilla, so every station is still listed. Seven stations had no race lock at all and are now locked too: Cursed Body Pile, Pack Trough, Bone Pile, Bound Sentry, Blood Refinery, Composter and Heartwood Grove. The stations' own placement gates stay for their boss-tier checks and for no-cost debug building. --- JotunnModStub/RaceStationLock.cs | 131 +++++++++++++++++++++++++++++++ JotunnModStub/RacesOfValheim.cs | 22 ++++++ 2 files changed, 153 insertions(+) create mode 100644 JotunnModStub/RaceStationLock.cs diff --git a/JotunnModStub/RaceStationLock.cs b/JotunnModStub/RaceStationLock.cs new file mode 100644 index 0000000..ba84346 --- /dev/null +++ b/JotunnModStub/RaceStationLock.cs @@ -0,0 +1,131 @@ +using System.Collections.Generic; +using System.Linq; +using HarmonyLib; +using TMPro; +using UnityEngine; +using UnityEngine.UI; + +namespace RacesOfValheim +{ + /// + /// A race station asks for its race the way a piece asks for wood: as a requirement. + /// + /// Each station used to have its own lock, or none. Nine refused at placement with a message of + /// their own (PieceDensityLimit gates, the Trol totem, the Dvergar bank and barrel, the Trenta + /// root); seven - the Cursed Body Pile, the Pack Trough, the Bone Pile and Sentry, the Blood + /// Refinery, the Composter and the Heartwood Grove - anybody could build. And none of them said so + /// before the click: the build panel listed the wood and the trophy and nothing else. + /// + /// Now every one of them is listed here with its race, and two things follow. The build panel + /// shows the race in the requirement row, with the race's icon and name, blinking red when the + /// player is not of it - the same row and the same blink vanilla uses for a missing crafting + /// station. And Player.HaveRequirements answers false for CanBuild, so the piece is greyed in the + /// menu and a click gets vanilla's "Missing requirements", exactly as for a missing item. IsKnown + /// and CanAlmostBuild are left alone, so the station stays in the menu for everyone to read. + /// + /// The stations' own gates stay: they also check boss tiers, and they still catch a build in + /// no-cost debug mode, which skips HaveRequirements altogether. + /// + public static class RaceStationLock + { + private static readonly Dictionary Races = new Dictionary + { + { TrolTotem.PieceName, new[] { TrolTotem.RaceId } }, + { DraughSpawner.PieceName, new[] { DraughVisuals.RaceId } }, + { DvergarBanco.PieceName, new[] { DvergarConfig.RaceId } }, + { DvergarBotte.PieceName, new[] { DvergarConfig.RaceId } }, + { FenrirMangiatoia.PieceName, new[] { FenrirMangiatoia.RaceId } }, + { SkadiGolem.SeedPieceName, new[] { "Skadi" } }, + { BoneServant.SmithTableName, new[] { SkeletonVisuals.RaceId, "Skadi" } }, + { BoneServant.CookTableName, new[] { "Skadi" } }, + { SkeletonBonePile.PieceName, new[] { SkeletonVisuals.RaceId } }, + { SkeletonSentry.SeedPieceName, new[] { SkeletonVisuals.RaceId } }, + { SvermHive.PieceName, new[] { SvermConfig.RaceId } }, + { SvermHiveMarketPiece.PieceName, new[] { SvermConfig.RaceId } }, + { TrentaConfig.ElderRootPieceName, new[] { TrentaConfig.RaceId } }, + { TrentaConfig.ComposterPieceName, new[] { TrentaConfig.RaceId } }, + { TrentaConfig.GrovePieceName, new[] { TrentaConfig.RaceId } }, + { AswidBloodRefinery.PieceName, new[] { "Aswid" } }, + }; + + /// The races allowed to build this piece, or null for a piece anyone builds. + public static string[] For(Piece piece) + { + if (piece == null) return null; + return Races.TryGetValue(Utils.GetPrefabName(piece.gameObject), out string[] races) ? races : null; + } + + public static bool Allows(Player player, string[] races) + { + if (races == null) return true; + if (player == null) return false; + string race = FactionHostilityPatch.GetPlayerRace(player); + return race != null && races.Contains(race); + } + + public static string NameOf(string race) => ModText.Get("rov_race_" + race.ToLowerInvariant() + "_name"); + + /// CanBuild only: see the class doc for why IsKnown and CanAlmostBuild stay vanilla. + [HarmonyPatch(typeof(Player), nameof(Player.HaveRequirements), new[] { typeof(Piece), typeof(Player.RequirementMode) })] + public static class RaceStation_HaveRequirements_Patch + { + public static void Postfix(Player __instance, Piece piece, Player.RequirementMode mode, ref bool __result) + { + if (!__result || mode != Player.RequirementMode.CanBuild) return; + if (!Allows(__instance, For(piece))) __result = false; + } + } + + /// + /// The race in the build panel's requirement row, in the first slot after the materials and + /// the crafting station - the slots Hud.SetupPieceInfo has just filled or switched off. + /// + [HarmonyPatch(typeof(Hud), "SetupPieceInfo")] + public static class RaceStation_PieceInfo_Patch + { + // Vanilla never sets the name's colour, so a row this patch left red would stay red for + // whatever item the next piece puts in it. + public static void Prefix(Hud __instance) + { + if (__instance.m_requirementItems == null) return; + foreach (GameObject row in __instance.m_requirementItems) + { + TMP_Text name = row != null ? row.transform.Find("res_name")?.GetComponent() : null; + if (name != null) name.color = Color.white; + } + } + + public static void Postfix(Hud __instance, Piece piece) + { + string[] races = For(piece); + if (races == null || races.Length == 0 || __instance.m_requirementItems == null) return; + + int slot = piece.m_resources.Length + (piece.m_craftingStation != null ? 1 : 0); + if (slot >= __instance.m_requirementItems.Length) return; + + GameObject row = __instance.m_requirementItems[slot]; + Image icon = row.transform.Find("res_icon")?.GetComponent(); + TMP_Text name = row.transform.Find("res_name")?.GetComponent(); + TMP_Text amount = row.transform.Find("res_amount")?.GetComponent(); + UITooltip tooltip = row.GetComponent(); + if (icon == null || name == null || amount == null) return; + + row.SetActive(true); + icon.gameObject.SetActive(true); + name.gameObject.SetActive(true); + amount.gameObject.SetActive(true); + + string label = string.Join(" / ", races.Select(NameOf)); + icon.sprite = RacesOfValheim.RaceIcon(races[0]); + name.text = label; + if (tooltip != null) tooltip.m_text = label; + amount.text = ""; + + bool ok = Allows(Player.m_localPlayer, races); + icon.color = ok ? Color.white : Color.gray; + // Vanilla's blink for a missing crafting station, on the name since there is no number. + name.color = ok || Mathf.Sin(Time.time * 10f) <= 0f ? Color.white : Color.red; + } + } + } +} diff --git a/JotunnModStub/RacesOfValheim.cs b/JotunnModStub/RacesOfValheim.cs index e6f8289..0702646 100644 --- a/JotunnModStub/RacesOfValheim.cs +++ b/JotunnModStub/RacesOfValheim.cs @@ -451,6 +451,28 @@ namespace RacesOfValheim GUIManager.BlockInput(true); } + /// + /// The icon the race menu shows for a race, for anything else that names a race - the race + /// requirement in the build panel (RaceStationLock). One source, so the two never disagree. + /// + public static Sprite RaceIcon(string race) + { + if (Instance == null || string.IsNullOrEmpty(race)) return null; + switch (race) + { + case "Fenrir": return Instance.GetFenrirIcon(); + case "Skadi": return Instance.GetSkadiIcon(); + case SkeletonVisuals.RaceId: return Instance.GetSkeletonIcon(); + case "Aswid": return Instance.GetAswidIcon(); + case "Furling": return Instance.GetFurlingIcon(); + case "Trol": return Instance.GetTrolIcon(); + case DvergarConfig.RaceId: return Instance.GetDvergarIcon(); + case TrentaConfig.RaceId: return Instance.GetTrentaIcon(); + case SvermConfig.RaceId: return Instance.GetSvermIcon(); + } + return race == DraughVisuals.RaceId ? Instance.GetDraughIcon() : Instance.GetHumanIcon(); + } + private Sprite GetHumanIcon() { GameObject clubPrefab = PrefabManager.Cache.GetPrefab("Club")?.gameObject; From 7647b66aa051553a6d44c1fcb52602726a635358 Mon Sep 17 00:00:00 2001 From: kanym Date: Sat, 17 Oct 2026 16:39:56 +0200 Subject: [PATCH 027/163] fix(stations): the race requirement comes first in the build panel The race took the first free row after the materials and the crafting station. Each of those rows now moves one to the right and the race takes row 0: it decides whether the rest matters at all. --- JotunnModStub/RaceStationLock.cs | 42 ++++++++++++++++++++++++++++---- 1 file changed, 37 insertions(+), 5 deletions(-) diff --git a/JotunnModStub/RaceStationLock.cs b/JotunnModStub/RaceStationLock.cs index ba84346..b7eaab6 100644 --- a/JotunnModStub/RaceStationLock.cs +++ b/JotunnModStub/RaceStationLock.cs @@ -77,8 +77,9 @@ namespace RacesOfValheim } /// - /// The race in the build panel's requirement row, in the first slot after the materials and - /// the crafting station - the slots Hud.SetupPieceInfo has just filled or switched off. + /// The race in the build panel's requirement row, FIRST: the race decides whether the rest + /// matters at all. Hud.SetupPieceInfo has just filled one row per material and one for the + /// crafting station; each of those is moved one row to the right, and the race takes row 0. /// [HarmonyPatch(typeof(Hud), "SetupPieceInfo")] public static class RaceStation_PieceInfo_Patch @@ -100,10 +101,13 @@ namespace RacesOfValheim string[] races = For(piece); if (races == null || races.Length == 0 || __instance.m_requirementItems == null) return; - int slot = piece.m_resources.Length + (piece.m_craftingStation != null ? 1 : 0); - if (slot >= __instance.m_requirementItems.Length) return; + GameObject[] rows = __instance.m_requirementItems; + int used = piece.m_resources.Length + (piece.m_craftingStation != null ? 1 : 0); + if (used >= rows.Length) return; - GameObject row = __instance.m_requirementItems[slot]; + for (int i = used; i > 0; i--) CopyRow(rows[i - 1], rows[i]); + + GameObject row = rows[0]; Image icon = row.transform.Find("res_icon")?.GetComponent(); TMP_Text name = row.transform.Find("res_name")?.GetComponent(); TMP_Text amount = row.transform.Find("res_amount")?.GetComponent(); @@ -126,6 +130,34 @@ namespace RacesOfValheim // Vanilla's blink for a missing crafting station, on the name since there is no number. name.color = ok || Mathf.Sin(Time.time * 10f) <= 0f ? Color.white : Color.red; } + + /// Everything SetupRequirement and the station row write, from one row to the next. + private static void CopyRow(GameObject from, GameObject to) + { + to.SetActive(from.activeSelf); + foreach (string child in new[] { "res_icon", "res_name", "res_amount" }) + { + Transform a = from.transform.Find(child); + Transform b = to.transform.Find(child); + if (a == null || b == null) continue; + b.gameObject.SetActive(a.gameObject.activeSelf); + } + + Image fromIcon = from.transform.Find("res_icon")?.GetComponent(); + Image toIcon = to.transform.Find("res_icon")?.GetComponent(); + if (fromIcon != null && toIcon != null) { toIcon.sprite = fromIcon.sprite; toIcon.color = fromIcon.color; } + + foreach (string child in new[] { "res_name", "res_amount" }) + { + TMP_Text a = from.transform.Find(child)?.GetComponent(); + TMP_Text b = to.transform.Find(child)?.GetComponent(); + if (a != null && b != null) { b.text = a.text; b.color = a.color; } + } + + UITooltip fromTip = from.GetComponent(); + UITooltip toTip = to.GetComponent(); + if (fromTip != null && toTip != null) toTip.m_text = fromTip.m_text; + } } } } From 580ef6d4684906ba82714dc1dd890d541cf6fd65 Mon Sep 17 00:00:00 2001 From: kanym Date: Sat, 17 Oct 2026 18:51:14 +0200 Subject: [PATCH 028/163] feat(fenrir): forms sneak at a walk and sleep when the player sits FormLocomotion zeroed the speed whenever the player crouched, so a sneaking form slid across the ground in its idle pose. Only airborne reads as still now: crouched, the player moves at sneaking speed and the creature's controller picks its walk. Sitting sets the "sleeping" bool the creature's own MonsterAI uses, when its controller has one; the log says once per controller which do. IsSitting reads the replicated animator state, so onlookers' copies sleep too. Covers every Fenrir form, local and remote, and the True Form troll, which share FormLocomotion. Mirror now takes the Player. Requested by a player on Discord. --- JotunnModStub/Fenrir/FenrirBehaviors.cs | 10 +++--- JotunnModStub/Fenrir/FenrirFormShared.cs | 42 ++++++++++++++++++---- JotunnModStub/Trol/TrolTrueFormBehavior.cs | 4 +-- 3 files changed, 42 insertions(+), 14 deletions(-) diff --git a/JotunnModStub/Fenrir/FenrirBehaviors.cs b/JotunnModStub/Fenrir/FenrirBehaviors.cs index abe0846..dfbbaeb 100644 --- a/JotunnModStub/Fenrir/FenrirBehaviors.cs +++ b/JotunnModStub/Fenrir/FenrirBehaviors.cs @@ -422,7 +422,7 @@ namespace RacesOfValheim // The same helper the local behaviours use, so both views of the same wolf agree. // Player.IsCrouching answers off the animator's current state, which is replicated, so // it is true here too. - locomotion.Mirror(formAnim, playerAnim, player.IsCrouching()); + locomotion.Mirror(formAnim, playerAnim, player); } // Written every frame while the flag is set, and only when the controller has the bool: a @@ -539,7 +539,7 @@ namespace RacesOfValheim // Meglio continuare a sincronizzare i movimenti base. if (!isAttacking) { - bool isGrounded = locomotion.Mirror(fenrirAnim, playerAnim, Player.m_localPlayer.IsCrouching()); + bool isGrounded = locomotion.Mirror(fenrirAnim, playerAnim, Player.m_localPlayer); if (isGrounded && RaceInput.Allowed) { @@ -790,7 +790,7 @@ namespace RacesOfValheim if (!isAttacking) { // Se tiene premuto Ctrl (Crouch), ferma il movimento per preparare l'attacco - bool isGrounded = locomotion.Mirror(cultistAnim, playerAnim, Player.m_localPlayer.IsCrouching()); + bool isGrounded = locomotion.Mirror(cultistAnim, playerAnim, Player.m_localPlayer); if (isGrounded) { @@ -1172,7 +1172,7 @@ namespace RacesOfValheim if (!isAttacking) { - bool isGrounded = locomotion.Mirror(wolfAnim, playerAnim, Player.m_localPlayer.IsCrouching()); + bool isGrounded = locomotion.Mirror(wolfAnim, playerAnim, Player.m_localPlayer); if (isGrounded && RaceInput.Allowed) { @@ -1384,7 +1384,7 @@ namespace RacesOfValheim if (!isAttacking) { - bool isGrounded = locomotion.Mirror(ulvAnim, playerAnim, Player.m_localPlayer.IsCrouching()); + bool isGrounded = locomotion.Mirror(ulvAnim, playerAnim, Player.m_localPlayer); if (isGrounded && RaceInput.Allowed) { diff --git a/JotunnModStub/Fenrir/FenrirFormShared.cs b/JotunnModStub/Fenrir/FenrirFormShared.cs index 4bb14e4..e74407c 100644 --- a/JotunnModStub/Fenrir/FenrirFormShared.cs +++ b/JotunnModStub/Fenrir/FenrirFormShared.cs @@ -40,22 +40,50 @@ namespace RacesOfValheim private float airborneFor; + // Whether this form's controller has a "sleeping" bool, asked once per Animator: MonsterAI + // drives the creature's own sleep through it, and not every creature has one. + private Animator sleepChecked; + private bool hasSleeping; + private static readonly System.Collections.Generic.HashSet sleepLogged = new System.Collections.Generic.HashSet(); + /// Copies the movement parameters, and says whether the form counts as grounded. - public bool Mirror(Animator form, Animator player, bool crouching) + public bool Mirror(Animator form, Animator playerAnim, Player player) { - bool touching = player.GetBool("onGround"); + bool touching = playerAnim.GetBool("onGround"); airborneFor = touching ? 0f : airborneFor + Time.deltaTime; bool grounded = airborneFor <= AirborneGrace; // try/catch as the behaviours always did it: a controller missing one of these must not // throw once per frame. try { form.SetBool("onGround", grounded); } catch {} - try { form.SetBool("inWater", player.GetBool("inWater")); } catch {} + try { form.SetBool("inWater", playerAnim.GetBool("inWater")); } catch {} - // Airborne and crouching both read as standing still, as before. - bool still = !grounded || crouching; - try { form.SetFloat("forward_speed", still ? 0f : player.GetFloat("forward_speed")); } catch {} - try { form.SetFloat("sideway_speed", still ? 0f : player.GetFloat("sideway_speed")); } catch {} + // Only airborne reads as standing still now. Crouching used to as well, so a player + // sneaking in a form slid across the ground in the idle pose. Crouched, the player moves + // at sneaking speed, and the creature's controller picks its walk for a speed that low: + // the sneak a player asked for, from animations the creature already has. + try { form.SetFloat("forward_speed", grounded ? playerAnim.GetFloat("forward_speed") : 0f); } catch {} + try { form.SetFloat("sideway_speed", grounded ? playerAnim.GetFloat("sideway_speed") : 0f); } catch {} + + // Sitting puts the creature to sleep, on the "sleeping" bool its own MonsterAI uses - the + // Ulv curls up. IsSitting reads the animator's state, which is replicated, so it is right + // for an onlooker's copy too. + if (sleepChecked != form) + { + sleepChecked = form; + hasSleeping = false; + foreach (AnimatorControllerParameter p in form.parameters) + { + if (p.type == AnimatorControllerParameterType.Bool && p.name == "sleeping") { hasSleeping = true; break; } + } + string controller = form.runtimeAnimatorController != null ? form.runtimeAnimatorController.name : form.name; + if (sleepLogged.Add(controller)) + { + Jotunn.Logger.LogInfo($"[FenrirForm] '{controller}' {(hasSleeping ? "has" : "has no")} sleeping animation; " + + (hasSleeping ? "sitting puts it to sleep." : "sitting keeps it idle.")); + } + } + if (hasSleeping) form.SetBool("sleeping", player != null && player.IsSitting()); return grounded; } diff --git a/JotunnModStub/Trol/TrolTrueFormBehavior.cs b/JotunnModStub/Trol/TrolTrueFormBehavior.cs index 4e17311..65ef184 100644 --- a/JotunnModStub/Trol/TrolTrueFormBehavior.cs +++ b/JotunnModStub/Trol/TrolTrueFormBehavior.cs @@ -86,7 +86,7 @@ namespace RacesOfValheim if (isAttacking || player.IsDead()) return; - bool grounded = locomotion.Mirror(anim, playerAnim, player.IsCrouching()); + bool grounded = locomotion.Mirror(anim, playerAnim, player); if (!grounded || !RaceInput.Allowed) return; bool log = heldLogName != null; @@ -437,7 +437,7 @@ namespace RacesOfValheim TrolTrueFormModel.UpdateHeldLog(gameObject, rightPrefab, ref heldLog, ref heldLogName); ReplayAttack(); - locomotion.Mirror(anim, playerAnim, player.IsCrouching()); + locomotion.Mirror(anim, playerAnim, player); } private void ReplayAttack() From 96dc8e4158530409466b4f64860e433f109dbcef Mon Sep 17 00:00:00 2001 From: kanym Date: Sat, 17 Oct 2026 19:01:03 +0200 Subject: [PATCH 029/163] fix(fenrir): Ulv sleeps on the sit key; forms stand still to attack Humanoid.IsSitting asks about the "sitting" animator tag, which belongs to chairs. The sit key is an emote that Player.StartEmote writes on the ZDO as "sit", so the Ulv never saw the player sit down. FormLocomotion now reads the ZDO emote too, which every client sees. Of the four forms only ulv_animator has a sleeping state. The hidden player kept walking under the form through an attack, so a bite slid toward whatever WASD held. Each form's isAttacking now also sets FenrirForms.LocalAttacking, and a SetControls prefix holds the player still while it is set, as the True Form troll does. The leaps move the body directly and are untouched. Cleared on every revert. --- JotunnModStub/Fenrir/FenrirBehaviors.cs | 20 ++++++++--- JotunnModStub/Fenrir/FenrirFormShared.cs | 45 +++++++++++++++++++++++- JotunnModStub/Fenrir/FenrirRace.cs | 2 ++ 3 files changed, 62 insertions(+), 5 deletions(-) diff --git a/JotunnModStub/Fenrir/FenrirBehaviors.cs b/JotunnModStub/Fenrir/FenrirBehaviors.cs index dfbbaeb..2b0783d 100644 --- a/JotunnModStub/Fenrir/FenrirBehaviors.cs +++ b/JotunnModStub/Fenrir/FenrirBehaviors.cs @@ -514,7 +514,10 @@ namespace RacesOfValheim private readonly FormLocomotion locomotion = new FormLocomotion(); private float busySince = -1f; - private bool isAttacking = false; + // A property so every form tells FenrirForms.LocalAttacking too: Fenrir_FormHoldStill_Patch + // holds the player still for exactly as long as an attack clip runs. + private bool attacking; + private bool isAttacking { get => attacking; set { attacking = value; FenrirForms.LocalAttacking = value; } } void Start() { @@ -766,7 +769,10 @@ namespace RacesOfValheim private readonly FormLocomotion locomotion = new FormLocomotion(); private float busySince = -1f; - private bool isAttacking = false; + // A property so every form tells FenrirForms.LocalAttacking too: Fenrir_FormHoldStill_Patch + // holds the player still for exactly as long as an attack clip runs. + private bool attacking; + private bool isAttacking { get => attacking; set { attacking = value; FenrirForms.LocalAttacking = value; } } private bool isShootingFire = false; private float fireTimer = 0f; @@ -1150,7 +1156,10 @@ namespace RacesOfValheim private Animator wolfAnim; private readonly FormLocomotion locomotion = new FormLocomotion(); private float busySince = -1f; - private bool isAttacking = false; + // A property so every form tells FenrirForms.LocalAttacking too: Fenrir_FormHoldStill_Patch + // holds the player still for exactly as long as an attack clip runs. + private bool attacking; + private bool isAttacking { get => attacking; set { attacking = value; FenrirForms.LocalAttacking = value; } } void Start() { @@ -1363,7 +1372,10 @@ namespace RacesOfValheim private readonly FormLocomotion locomotion = new FormLocomotion(); private float busySince = -1f; - private bool isAttacking = false; + // A property so every form tells FenrirForms.LocalAttacking too: Fenrir_FormHoldStill_Patch + // holds the player still for exactly as long as an attack clip runs. + private bool attacking; + private bool isAttacking { get => attacking; set { attacking = value; FenrirForms.LocalAttacking = value; } } void Start() { diff --git a/JotunnModStub/Fenrir/FenrirFormShared.cs b/JotunnModStub/Fenrir/FenrirFormShared.cs index e74407c..f412620 100644 --- a/JotunnModStub/Fenrir/FenrirFormShared.cs +++ b/JotunnModStub/Fenrir/FenrirFormShared.cs @@ -14,6 +14,10 @@ namespace RacesOfValheim /// SE_FenrirForm and the Cultist SE_CultistForm. Checking only SE_FenrirForm, as the attack /// block used to, left three of the four forms out. /// + /// True while the local form is inside an attack, a howl or a breath. Cleared by the + /// form's own routines, and on every revert. + public static bool LocalAttacking { get; set; } + public static bool LocalInForm(Character character) { if (character == null || character != Player.m_localPlayer) return false; @@ -83,10 +87,25 @@ namespace RacesOfValheim (hasSleeping ? "sitting puts it to sleep." : "sitting keeps it idle.")); } } - if (hasSleeping) form.SetBool("sleeping", player != null && player.IsSitting()); + if (hasSleeping) form.SetBool("sleeping", IsSitting(player)); return grounded; } + + /// + /// The sit key, or a chair. The sit key is an EMOTE, not the "sitting" animator tag that + /// Humanoid.IsSitting asks about - that tag belongs to chairs and benches - so IsSitting alone + /// never saw it and the Ulv stayed on its feet. Player.StartEmote writes the emote's name on the + /// ZDO, which every client reads, so this is right for an onlooker's copy as well. + /// + private static bool IsSitting(Player player) + { + if (player == null) return false; + if (player.IsSitting()) return true; + + ZNetView nview = player.GetComponent(); + return nview != null && nview.IsValid() && nview.GetZDO().GetString(ZDOVars.s_emote, "") == "sit"; + } } /// @@ -215,4 +234,28 @@ namespace RacesOfValheim Jotunn.Logger.LogInfo($"[FenrirForm] {form} swing: {candidates} collider(s) in reach."); } } + /// + /// Holds the player still through a form's attack clips, the way a human stands to swing. The + /// hidden player kept walking under the creature, so the bite slid toward whatever WASD held. + /// SkeletonRiseControlsPatch's arrangement: the move direction is SetControls' first argument, + /// bound by position. The Fenring's and the Ulv's leaps move the body directly and are untouched. + /// + [HarmonyLib.HarmonyPatch(typeof(Player), "SetControls")] + public static class Fenrir_FormHoldStill_Patch + { + public static void Prefix(Player __instance, ref Vector3 __0, ref bool jump, ref bool crouch, ref bool dodge) + { + if (__instance != Player.m_localPlayer || !FenrirForms.LocalAttacking) return; + if (!FenrirForms.LocalInForm(__instance)) + { + FenrirForms.LocalAttacking = false; + return; + } + + __0 = Vector3.zero; + jump = false; + crouch = false; + dodge = false; + } + } } diff --git a/JotunnModStub/Fenrir/FenrirRace.cs b/JotunnModStub/Fenrir/FenrirRace.cs index ee5cd5a..655cb86 100644 --- a/JotunnModStub/Fenrir/FenrirRace.cs +++ b/JotunnModStub/Fenrir/FenrirRace.cs @@ -300,6 +300,7 @@ namespace RacesOfValheim { player.GetSEMan().RemoveStatusEffect("SE_WolfForm".GetStableHashCode()); } + FenrirForms.LocalAttacking = false; isTransformed = false; isTransformingSequence = false; activeRules = null; @@ -575,6 +576,7 @@ namespace RacesOfValheim { Player.m_localPlayer.GetSEMan().RemoveStatusEffect("SE_CultistForm".GetStableHashCode()); Player.m_localPlayer.GetSEMan().RemoveStatusEffect("SE_WolfForm".GetStableHashCode()); + FenrirForms.LocalAttacking = false; isTransformed = false; Player.m_localPlayer.Message(MessageHud.MessageType.Center, revertMessage ?? ModText.Get("rov_msg_fenrir_returned_human_form")); revertMessage = null; From 2df8264c42279f941d0aae6ef31f27271ccd6009 Mon Sep 17 00:00:00 2001 From: kanym Date: Sat, 17 Oct 2026 19:06:08 +0200 Subject: [PATCH 030/163] debug: log the Ulv's sleep state while the player sits (temporary) --- JotunnModStub/Fenrir/FenrirFormShared.cs | 29 +++++++++++++++++++++++- 1 file changed, 28 insertions(+), 1 deletion(-) diff --git a/JotunnModStub/Fenrir/FenrirFormShared.cs b/JotunnModStub/Fenrir/FenrirFormShared.cs index f412620..e1a8b72 100644 --- a/JotunnModStub/Fenrir/FenrirFormShared.cs +++ b/JotunnModStub/Fenrir/FenrirFormShared.cs @@ -87,7 +87,9 @@ namespace RacesOfValheim (hasSleeping ? "sitting puts it to sleep." : "sitting keeps it idle.")); } } - if (hasSleeping) form.SetBool("sleeping", IsSitting(player)); + bool sitting = IsSitting(player); + if (hasSleeping) form.SetBool("sleeping", sitting); + DebugSleep(form, player, sitting); return grounded; } @@ -98,6 +100,31 @@ namespace RacesOfValheim /// never saw it and the Ulv stayed on its feet. Player.StartEmote writes the emote's name on the /// ZDO, which every client reads, so this is right for an onlooker's copy as well. /// + // TEMPORARY DEBUG for the Ulv that will not sleep. Remove with the fix. + private bool lastSitting; + private float nextSleepLog; + private void DebugSleep(Animator form, Player player, bool sitting) + { + if (player == null || player != Player.m_localPlayer) return; + ZNetView nview = player.GetComponent(); + string emote = nview != null && nview.IsValid() ? nview.GetZDO().GetString(ZDOVars.s_emote, "") : "?"; + if (sitting != lastSitting) + { + lastSitting = sitting; + Jotunn.Logger.LogInfo($"[SleepDebug] sitting={sitting} IsSitting={player.IsSitting()} emote='{emote}' hasSleeping={hasSleeping}"); + } + if (!sitting && emote != "sit") return; + if (Time.time < nextSleepLog) return; + nextSleepLog = Time.time + 1f; + string clip = "?"; + var clips = form.GetCurrentAnimatorClipInfo(0); + if (clips.Length > 0 && clips[0].clip != null) clip = clips[0].clip.name; + bool sleepingNow = false; + try { sleepingNow = form.GetBool("sleeping"); } catch {} + Jotunn.Logger.LogInfo($"[SleepDebug] sitting={sitting} emote='{emote}' sleepingBool={sleepingNow} clip='{clip}' " + + $"inTransition={form.IsInTransition(0)} enabled={form.enabled} speed={form.speed}"); + } + private static bool IsSitting(Player player) { if (player == null) return false; From 4cb6da801bf669e49a2002fb848b50fff33b0dd9 Mon Sep 17 00:00:00 2001 From: kanym Date: Sat, 17 Oct 2026 19:09:38 +0200 Subject: [PATCH 031/163] Revert "debug: log the Ulv's sleep state while the player sits (temporary)" This reverts commit 2df8264c42279f941d0aae6ef31f27271ccd6009. --- JotunnModStub/Fenrir/FenrirFormShared.cs | 29 +----------------------- 1 file changed, 1 insertion(+), 28 deletions(-) diff --git a/JotunnModStub/Fenrir/FenrirFormShared.cs b/JotunnModStub/Fenrir/FenrirFormShared.cs index e1a8b72..f412620 100644 --- a/JotunnModStub/Fenrir/FenrirFormShared.cs +++ b/JotunnModStub/Fenrir/FenrirFormShared.cs @@ -87,9 +87,7 @@ namespace RacesOfValheim (hasSleeping ? "sitting puts it to sleep." : "sitting keeps it idle.")); } } - bool sitting = IsSitting(player); - if (hasSleeping) form.SetBool("sleeping", sitting); - DebugSleep(form, player, sitting); + if (hasSleeping) form.SetBool("sleeping", IsSitting(player)); return grounded; } @@ -100,31 +98,6 @@ namespace RacesOfValheim /// never saw it and the Ulv stayed on its feet. Player.StartEmote writes the emote's name on the /// ZDO, which every client reads, so this is right for an onlooker's copy as well. /// - // TEMPORARY DEBUG for the Ulv that will not sleep. Remove with the fix. - private bool lastSitting; - private float nextSleepLog; - private void DebugSleep(Animator form, Player player, bool sitting) - { - if (player == null || player != Player.m_localPlayer) return; - ZNetView nview = player.GetComponent(); - string emote = nview != null && nview.IsValid() ? nview.GetZDO().GetString(ZDOVars.s_emote, "") : "?"; - if (sitting != lastSitting) - { - lastSitting = sitting; - Jotunn.Logger.LogInfo($"[SleepDebug] sitting={sitting} IsSitting={player.IsSitting()} emote='{emote}' hasSleeping={hasSleeping}"); - } - if (!sitting && emote != "sit") return; - if (Time.time < nextSleepLog) return; - nextSleepLog = Time.time + 1f; - string clip = "?"; - var clips = form.GetCurrentAnimatorClipInfo(0); - if (clips.Length > 0 && clips[0].clip != null) clip = clips[0].clip.name; - bool sleepingNow = false; - try { sleepingNow = form.GetBool("sleeping"); } catch {} - Jotunn.Logger.LogInfo($"[SleepDebug] sitting={sitting} emote='{emote}' sleepingBool={sleepingNow} clip='{clip}' " + - $"inTransition={form.IsInTransition(0)} enabled={form.enabled} speed={form.speed}"); - } - private static bool IsSitting(Player player) { if (player == null) return false; From 9cf3f5386c7e413ca38690cbe1591e0bfc90f702 Mon Sep 17 00:00:00 2001 From: kanym Date: Sat, 17 Oct 2026 19:09:50 +0200 Subject: [PATCH 032/163] fix(fenrir): the Ulv sleeps when the player sits Sitting now zeroes the form's speed. The seated player's Animator keeps a forward_speed above zero, which kept the Ulv in its Walk clip on the spot and out of reach of its Sleep state, which leaves from idle. The debug log showed it: sitting, sleeping=true, clip 'Walk'. --- JotunnModStub/Fenrir/FenrirFormShared.cs | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/JotunnModStub/Fenrir/FenrirFormShared.cs b/JotunnModStub/Fenrir/FenrirFormShared.cs index f412620..3922be6 100644 --- a/JotunnModStub/Fenrir/FenrirFormShared.cs +++ b/JotunnModStub/Fenrir/FenrirFormShared.cs @@ -66,8 +66,15 @@ namespace RacesOfValheim // sneaking in a form slid across the ground in the idle pose. Crouched, the player moves // at sneaking speed, and the creature's controller picks its walk for a speed that low: // the sneak a player asked for, from animations the creature already has. - try { form.SetFloat("forward_speed", grounded ? playerAnim.GetFloat("forward_speed") : 0f); } catch {} - try { form.SetFloat("sideway_speed", grounded ? playerAnim.GetFloat("sideway_speed") : 0f); } catch {} + // + // Sitting reads as still too. The seated player's own Animator keeps a forward_speed that + // is not zero, and passed through it kept the Ulv in its Walk clip - on the spot, and out + // of reach of its Sleep state, which only leaves from idle. Seen in the log: sitting, + // sleeping=true, clip 'Walk'. + bool sitting = IsSitting(player); + bool still = !grounded || sitting; + try { form.SetFloat("forward_speed", still ? 0f : playerAnim.GetFloat("forward_speed")); } catch {} + try { form.SetFloat("sideway_speed", still ? 0f : playerAnim.GetFloat("sideway_speed")); } catch {} // Sitting puts the creature to sleep, on the "sleeping" bool its own MonsterAI uses - the // Ulv curls up. IsSitting reads the animator's state, which is replicated, so it is right @@ -87,7 +94,7 @@ namespace RacesOfValheim (hasSleeping ? "sitting puts it to sleep." : "sitting keeps it idle.")); } } - if (hasSleeping) form.SetBool("sleeping", IsSitting(player)); + if (hasSleeping) form.SetBool("sleeping", sitting); return grounded; } From fb354c2387dc760e71058197388906d88e4ceb66 Mon Sep 17 00:00:00 2001 From: kanym Date: Sat, 17 Oct 2026 19:13:47 +0200 Subject: [PATCH 033/163] fix(fenrir): enter the Ulv's Sleep state by hand when the player sits A vanilla Ulv is born asleep: its controller only knows the way out of Sleep, so setting the bool from Idle did nothing. The state is now cross-faded into when the player sits; standing drops the bool and the controller's own 'Sleep to Idle' plays. The log names the state found. --- JotunnModStub/Fenrir/FenrirFormShared.cs | 34 ++++++++++++++++++++++-- 1 file changed, 32 insertions(+), 2 deletions(-) diff --git a/JotunnModStub/Fenrir/FenrirFormShared.cs b/JotunnModStub/Fenrir/FenrirFormShared.cs index 3922be6..5ee2233 100644 --- a/JotunnModStub/Fenrir/FenrirFormShared.cs +++ b/JotunnModStub/Fenrir/FenrirFormShared.cs @@ -48,6 +48,9 @@ namespace RacesOfValheim // drives the creature's own sleep through it, and not every creature has one. private Animator sleepChecked; private bool hasSleeping; + private int sleepState; + private bool wasSitting; + private static readonly string[] SleepStateNames = { "Sleep", "sleep", "Sleeping", "sleeping" }; private static readonly System.Collections.Generic.HashSet sleepLogged = new System.Collections.Generic.HashSet(); /// Copies the movement parameters, and says whether the form counts as grounded. @@ -87,14 +90,41 @@ namespace RacesOfValheim { if (p.type == AnimatorControllerParameterType.Bool && p.name == "sleeping") { hasSleeping = true; break; } } + + // The state's name is not readable at runtime, only testable: the clip is 'Sleep', and + // the state is most likely named after it. + sleepState = 0; + string found = "none"; + if (hasSleeping) + { + foreach (string candidate in SleepStateNames) + { + int hash = Animator.StringToHash(candidate); + if (!form.HasState(0, hash)) continue; + sleepState = hash; + found = candidate; + break; + } + } string controller = form.runtimeAnimatorController != null ? form.runtimeAnimatorController.name : form.name; if (sleepLogged.Add(controller)) { Jotunn.Logger.LogInfo($"[FenrirForm] '{controller}' {(hasSleeping ? "has" : "has no")} sleeping animation; " + - (hasSleeping ? "sitting puts it to sleep." : "sitting keeps it idle.")); + (hasSleeping ? $"sitting puts it to sleep (state '{found}')." : "sitting keeps it idle.")); } } - if (hasSleeping) form.SetBool("sleeping", sitting); + if (hasSleeping) + { + form.SetBool("sleeping", sitting); + + // The bool alone never put the Ulv to sleep. A vanilla Ulv is BORN asleep: its + // controller enters Sleep from the start and only knows the way out (Sleep, then + // 'Sleep to Idle' once the bool drops). Nothing leads from Idle back into Sleep, so + // the state is entered by hand when the player sits; standing up drops the bool and + // the controller's own wake-up plays. + if (sitting && !wasSitting && sleepState != 0) form.CrossFadeInFixedTime(sleepState, 0.4f, 0); + } + wasSitting = sitting; return grounded; } From e83c3c5d74757a951343d36d0a4bbce6e224f44e Mon Sep 17 00:00:00 2001 From: kanym Date: Sat, 17 Oct 2026 19:22:24 +0200 Subject: [PATCH 034/163] fix(fenrir): enter the Ulv's sleep by its real state path scripts/dump_controller.py reads an AnimatorController's states and transitions offline from Valheim's bundles with UnityPy. On ulv_animator it shows the entry state "check sleeping" picks Sleep only at start-up and Movement has no way back into it, so the bool alone could never work. The cross-fade now targets "Base Layer.Sleep". --- JotunnModStub/Fenrir/FenrirFormShared.cs | 9 +- scripts/dump_controller.py | 105 +++++++++++++++++++++++ 2 files changed, 111 insertions(+), 3 deletions(-) create mode 100644 scripts/dump_controller.py diff --git a/JotunnModStub/Fenrir/FenrirFormShared.cs b/JotunnModStub/Fenrir/FenrirFormShared.cs index 5ee2233..a6eb382 100644 --- a/JotunnModStub/Fenrir/FenrirFormShared.cs +++ b/JotunnModStub/Fenrir/FenrirFormShared.cs @@ -50,7 +50,10 @@ namespace RacesOfValheim private bool hasSleeping; private int sleepState; private bool wasSitting; - private static readonly string[] SleepStateNames = { "Sleep", "sleep", "Sleeping", "sleeping" }; + // Read off ulv_animator with scripts/dump_controller.py: the entry state "check sleeping" goes + // to Sleep only at start-up, and Movement has no way back into it. "Base Layer.Sleep" is the + // real path; the short name stays as a fallback for another creature built the same way. + private static readonly string[] SleepStateNames = { "Base Layer.Sleep", "Sleep" }; private static readonly System.Collections.Generic.HashSet sleepLogged = new System.Collections.Generic.HashSet(); /// Copies the movement parameters, and says whether the form counts as grounded. @@ -91,8 +94,8 @@ namespace RacesOfValheim if (p.type == AnimatorControllerParameterType.Bool && p.name == "sleeping") { hasSleeping = true; break; } } - // The state's name is not readable at runtime, only testable: the clip is 'Sleep', and - // the state is most likely named after it. + // The state's name is not readable at runtime, only testable - but it is readable offline, + // see SleepStateNames. sleepState = 0; string found = "none"; if (hasSleeping) diff --git a/scripts/dump_controller.py b/scripts/dump_controller.py new file mode 100644 index 0000000..07b9274 --- /dev/null +++ b/scripts/dump_controller.py @@ -0,0 +1,105 @@ +r"""Dump a Unity AnimatorController's parameters, states and transitions from Valheim's own files. + +Reads the game's asset files offline, so animator state and parameter names are read, not guessed. + +Setup, once (UnityPy into a folder of your choice, not into the repo): + python -m pip install --target C:\path o\pylib UnityPy + +Usage (Windows paths: a Git Bash "/c/..." path does not resolve for a Windows Python): + python -I scripts/dump_controller.py C:\path o\pylib " alheim_Data" ulv_animator wolf_animator + +Pass valheim_Data to search everything (slow, a few minutes), or a single bundle file to read +only that one. Creature animators live in valheim_Data\StreamingAssets\SoftRef\Bundles; the +Fenrir forms' four (wolf, ulv, fenring, fenring_cultist) are all in bundle c4210710 as of 1.0.20. +A controller's name is the one dumpanim prints ("controller 'ulv_animator'"). +""" +import os, sys, json + +sys.path.insert(0, sys.argv[1]) +import UnityPy # noqa: E402 + +data_dir = sys.argv[2] +wanted = set(sys.argv[3:]) + +candidates = [data_dir] if os.path.isfile(data_dir) else [] +for root, _, files in ([] if os.path.isfile(data_dir) else os.walk(data_dir)): + for f in files: + p = os.path.join(root, f) + if f.endswith(('.resS', '.resource', '.manifest', '.json', '.dll', '.csv', '.txt', '.info', '.config')): + continue + if os.path.getsize(p) < 1024: + continue + candidates.append(p) + +found = {} +for path in candidates: + try: + env = UnityPy.load(path) + except Exception: + continue + for obj in env.objects: + if obj.type.name != 'AnimatorController': + continue + try: + name = obj.peek_name() + except Exception: + name = None + if name is None: + try: + name = obj.read().m_Name + except Exception: + continue + if name not in wanted or name in found: + continue + tree = obj.read_typetree() + found[name] = (path, tree) + if len(found) == len(wanted): + break + +for name, (path, tree) in found.items(): + print(f'=== {name} ({os.path.basename(path)})') + tos = {int(k): v for k, v in tree.get('m_TOS', [])} + print('m_TOS (hash -> name):') + for h, v in sorted(tos.items(), key=lambda kv: kv[1]): + print(f' {h:>12} {v}') + + ctrl = tree.get('m_Controller', {}) + params = ctrl.get('m_Values', {}).get('data', {}).get('m_ValueArray', []) + print('parameters:') + for p in params: + print(f" {tos.get(p.get('m_ID'), p.get('m_ID'))} type={p.get('m_Type')}") + + for sm_i, sm in enumerate(ctrl.get('m_StateMachineArray', [])): + sm = sm.get('data', sm) + states = sm.get('m_StateConstantArray', []) + print(f'state machine {sm_i}: {len(states)} states, default index {sm.get("m_DefaultState")}') + any_tr = sm.get('m_AnyStateTransitionConstantArray', []) + + def describe(tr): + tr = tr.get('data', tr) + conds = [] + for c in tr.get('m_ConditionConstantArray', []): + c = c.get('data', c) + conds.append(f"{tos.get(c.get('m_EventID'), c.get('m_EventID'))} mode={c.get('m_ConditionMode')} th={c.get('m_EventThreshold')}") + dest = tr.get('m_DestinationState') + return dest, conds + + names = [] + for st in states: + st = st.get('data', st) + names.append(tos.get(st.get('m_NameID'), st.get('m_NameID'))) + for i, st in enumerate(states): + st = st.get('data', st) + print(f' [{i}] state "{names[i]}" fullPath="{tos.get(st.get("m_FullPathID"), st.get("m_FullPathID"))}" tag="{tos.get(st.get("m_TagID"), st.get("m_TagID"))}"') + for tr in st.get('m_TransitionConstantArray', []): + dest, conds = describe(tr) + dname = names[dest] if isinstance(dest, int) and 0 <= dest < len(names) else dest + print(f' -> {dname} when {conds}') + for tr in any_tr: + dest, conds = describe(tr) + dname = names[dest] if isinstance(dest, int) and 0 <= dest < len(names) else dest + print(f' AnyState -> {dname} when {conds}') + +missing = wanted - set(found) +if missing: + print('not found:', ', '.join(sorted(missing))) From 5c0f092c89e19d5e83899eaeff4612edf706c212 Mon Sep 17 00:00:00 2001 From: kanym Date: Sat, 17 Oct 2026 19:28:42 +0200 Subject: [PATCH 035/163] fix(fenrir): a form on a chair settles in front of the seat On a chair the player sits on the seat, and the form stood inside the chair at seat height. The form's root now goes 0.5 m in front of the seat, on whatever is under that point, skipping the seat's own colliders. The seat is found by a short raycast under the player, so it works for onlookers too, who have no attach point. Back to zero on standing up; the sit key is untouched. --- JotunnModStub/Fenrir/FenrirFormShared.cs | 66 ++++++++++++++++++++++++ 1 file changed, 66 insertions(+) diff --git a/JotunnModStub/Fenrir/FenrirFormShared.cs b/JotunnModStub/Fenrir/FenrirFormShared.cs index a6eb382..3d33ddf 100644 --- a/JotunnModStub/Fenrir/FenrirFormShared.cs +++ b/JotunnModStub/Fenrir/FenrirFormShared.cs @@ -129,9 +129,75 @@ namespace RacesOfValheim } wasSitting = sitting; + PlaceOnChair(form, player); + return grounded; } + // How far in front of the seat a creature on a chair settles, in metres. + private const float ChairForward = 0.5f; + private static readonly int ChairGroundMask = LayerMask.GetMask("Default", "static_solid", "terrain", "piece", "vehicle"); + private static readonly RaycastHit[] chairHits = new RaycastHit[16]; + private Transform placedRoot; + + /// + /// On a chair the player sits on the seat itself, and a creature there stood inside the chair, + /// at seat height. It goes half a metre in front of the seat instead, standing on whatever is + /// under that point. Moves the form's own root (the child of the player), never the player. + /// The sit key is left alone: the player is on the ground already. + /// + private void PlaceOnChair(Animator form, Player player) + { + Transform root = RootUnder(form.transform, player != null ? player.transform : null); + if (root == null) return; + + bool onChair = player.IsSitting(); + if (!onChair) + { + if (placedRoot == root && root.localPosition != Vector3.zero) root.localPosition = Vector3.zero; + return; + } + placedRoot = root; + + Transform body = player.transform; + Piece seat = SeatUnder(body.position); + Vector3 target = body.position + body.forward * ChairForward; + + float groundY = target.y; + int count = Physics.RaycastNonAlloc(target + Vector3.up * 1.5f, Vector3.down, chairHits, 4f, ChairGroundMask); + float best = float.MaxValue; + for (int i = 0; i < count; i++) + { + Collider c = chairHits[i].collider; + if (c == null || c.transform.IsChildOf(body)) continue; + if (seat != null && c.GetComponentInParent() == seat) continue; + if (chairHits[i].distance < best) { best = chairHits[i].distance; groundY = chairHits[i].point.y; } + } + + root.localPosition = body.InverseTransformPoint(new Vector3(target.x, groundY, target.z)); + } + + /// The chair or bench the player sits on: the first piece straight under them. + private static Piece SeatUnder(Vector3 position) + { + int count = Physics.RaycastNonAlloc(position + Vector3.up * 0.3f, Vector3.down, chairHits, 1.5f, ChairGroundMask); + Piece seat = null; + float best = float.MaxValue; + for (int i = 0; i < count; i++) + { + Piece piece = chairHits[i].collider != null ? chairHits[i].collider.GetComponentInParent() : null; + if (piece != null && chairHits[i].distance < best) { best = chairHits[i].distance; seat = piece; } + } + return seat; + } + + private static Transform RootUnder(Transform t, Transform player) + { + if (player == null) return null; + while (t != null && t.parent != player) t = t.parent; + return t; + } + /// /// The sit key, or a chair. The sit key is an EMOTE, not the "sitting" animator tag that /// Humanoid.IsSitting asks about - that tag belongs to chairs and benches - so IsSitting alone From ba7f56550d84e7e6bb16661cf8367d0fb41f89ca Mon Sep 17 00:00:00 2001 From: kanym Date: Sat, 17 Oct 2026 19:34:51 +0200 Subject: [PATCH 036/163] fix(forms): no form attacks in build mode; chair pose 1 m out, turned RaceInput.AttackDown and AttackHeld now return false while the player is in place mode (hammer, hoe, cultivator). Right click removes a piece there and middle click picks a snap point, and every form read both as its own attacks. Allowed only covered the piece selection panel. Every form reads the mouse through RaceInput, so all of them are covered. On a chair the form now settles 1 m in front of the seat and turns a quarter counter-clockwise, at the player's request after the first try. --- JotunnModStub/Fenrir/FenrirFormShared.cs | 13 +++++++++++-- JotunnModStub/RaceInput.cs | 11 +++++++++-- 2 files changed, 20 insertions(+), 4 deletions(-) diff --git a/JotunnModStub/Fenrir/FenrirFormShared.cs b/JotunnModStub/Fenrir/FenrirFormShared.cs index 3d33ddf..6fafc2e 100644 --- a/JotunnModStub/Fenrir/FenrirFormShared.cs +++ b/JotunnModStub/Fenrir/FenrirFormShared.cs @@ -135,7 +135,11 @@ namespace RacesOfValheim } // How far in front of the seat a creature on a chair settles, in metres. - private const float ChairForward = 0.5f; + private const float ChairForward = 1f; + + // And turned a quarter left, counter-clockwise seen from above, so it lies across the front + // of the seat rather than facing out of it. + private static readonly Quaternion ChairTurn = Quaternion.Euler(0f, -90f, 0f); private static readonly int ChairGroundMask = LayerMask.GetMask("Default", "static_solid", "terrain", "piece", "vehicle"); private static readonly RaycastHit[] chairHits = new RaycastHit[16]; private Transform placedRoot; @@ -154,7 +158,11 @@ namespace RacesOfValheim bool onChair = player.IsSitting(); if (!onChair) { - if (placedRoot == root && root.localPosition != Vector3.zero) root.localPosition = Vector3.zero; + if (placedRoot == root) + { + if (root.localPosition != Vector3.zero) root.localPosition = Vector3.zero; + if (root.localRotation != Quaternion.identity) root.localRotation = Quaternion.identity; + } return; } placedRoot = root; @@ -175,6 +183,7 @@ namespace RacesOfValheim } root.localPosition = body.InverseTransformPoint(new Vector3(target.x, groundY, target.z)); + root.localRotation = ChairTurn; } /// The chair or bench the player sits on: the first piece straight under them. diff --git a/JotunnModStub/RaceInput.cs b/JotunnModStub/RaceInput.cs index 283b34e..c045f2c 100644 --- a/JotunnModStub/RaceInput.cs +++ b/JotunnModStub/RaceInput.cs @@ -31,6 +31,13 @@ namespace RacesOfValheim // Not public on Player, hence the reflection; resolved once rather than per frame. private static readonly MethodInfo TakeInputMethod = AccessTools.Method(typeof(Player), "TakeInput"); + /// + /// Hammer, hoe or cultivator in hand. Right click removes a piece there and middle click picks + /// a snap point, and a form read both as its own attacks: an Ulv building a wall bit the air + /// on every click. Allowed only covered the piece selection panel, not the build mode itself. + /// + private static bool InBuildMode => Player.m_localPlayer != null && Player.m_localPlayer.InPlaceMode(); + public static bool Allowed { get @@ -156,14 +163,14 @@ namespace RacesOfValheim /// public static bool AttackDown(int mouseButton) { - if (RadialOpen) return false; + if (RadialOpen || InBuildMode) return false; return Input.GetMouseButtonDown(mouseButton) || PadAttackDown(mouseButton); } /// Held-down counterpart of . public static bool AttackHeld(int mouseButton) { - if (RadialOpen) return false; + if (RadialOpen || InBuildMode) return false; return Input.GetMouseButton(mouseButton) || PadAttackHeld(mouseButton); } From 5cf1ae7fb0a4e30a8a30027821c09b3aa33e5c63 Mon Sep 17 00:00:00 2001 From: kanym Date: Sat, 17 Oct 2026 19:42:14 +0200 Subject: [PATCH 037/163] fix(sverm): the Ravager costume no longer keeps a live Humanoid The BepInEx log showed "Can't remove Humanoid (Script) because CharacterDrop (Script) depends on it" right after the Ravager template was built from SeekerBrute. The strip was one pass in component order, and Unity refuses to destroy a component another still requires, so the Brute's Humanoid survived on the costume and on every copy a player wore: the leftover that once broke the hammer for every piece. ModelBorrow.StripBehaviours destroys only what nothing remaining requires through [RequireComponent], round after round, and logs any survivor by name. Used by the Ravager template, by ModelBorrow.Attach and by the Skeleton's rise costume, which had the same single pass. --- JotunnModStub/ModelBorrow.cs | 66 +++++++++++++++++++++++-- JotunnModStub/Skeleton/SkeletonRise.cs | 6 +-- JotunnModStub/Sverm/SvermRavagerForm.cs | 7 ++- 3 files changed, 67 insertions(+), 12 deletions(-) diff --git a/JotunnModStub/ModelBorrow.cs b/JotunnModStub/ModelBorrow.cs index 20b2ded..1bd8fd2 100644 --- a/JotunnModStub/ModelBorrow.cs +++ b/JotunnModStub/ModelBorrow.cs @@ -96,10 +96,7 @@ namespace RacesOfValheim // Everything that is not a Renderer or a Transform. Order matters for the same reason it did // on the Aswid's lights: behaviours first, then the things they hold references to. - foreach (MonoBehaviour behaviour in copy.GetComponentsInChildren(true)) - { - if (behaviour != null) Object.DestroyImmediate(behaviour); - } + StripBehaviours(copy, label); foreach (Collider collider in copy.GetComponentsInChildren(true)) { if (collider != null) Object.DestroyImmediate(collider); @@ -119,6 +116,67 @@ namespace RacesOfValheim return holder; } + /// + /// Destroys every MonoBehaviour under , dependents first. + /// + /// A single pass in component order is not enough, and the log said so: "Can't remove Humanoid + /// (Script) because CharacterDrop (Script) depends on it". Unity refuses to destroy a component + /// another one still requires through [RequireComponent], so the pass that reached Humanoid + /// before CharacterDrop left a live Humanoid on the Sverm's Ravager costume - on every player + /// wearing it - which is the leftover that once broke the hammer for every piece (see + /// SvermHive.MouthCandidates). Each round here destroys only what nothing remaining requires, + /// and rounds repeat until nothing is left or nothing more can go. + /// + public static void StripBehaviours(GameObject root, string label) + { + if (root == null) return; + + for (int round = 0; round < 16; round++) + { + MonoBehaviour[] left = root.GetComponentsInChildren(true); + if (left.Length == 0) return; + + int destroyed = 0; + foreach (MonoBehaviour behaviour in left) + { + if (behaviour == null || IsRequired(behaviour)) continue; + Object.DestroyImmediate(behaviour); + destroyed++; + } + if (destroyed == 0) break; + } + + foreach (MonoBehaviour survivor in root.GetComponentsInChildren(true)) + { + if (survivor != null) + { + Jotunn.Logger.LogWarning($"[{label}] '{survivor.GetType().Name}' on '{survivor.name}' could not be stripped from a borrowed model."); + } + } + } + + /// True if another component on the same GameObject names this one's type in a + /// [RequireComponent]. + private static bool IsRequired(Component target) + { + System.Type type = target.GetType(); + foreach (Component other in target.GetComponents()) + { + if (other == null || other == target) continue; + foreach (object attribute in other.GetType().GetCustomAttributes(typeof(RequireComponent), true)) + { + RequireComponent require = (RequireComponent)attribute; + if (Requires(require.m_Type0, type) || Requires(require.m_Type1, type) || Requires(require.m_Type2, type)) + { + return true; + } + } + } + return false; + } + + private static bool Requires(System.Type required, System.Type type) => required != null && required.IsAssignableFrom(type); + /// /// How tall the borrowed model actually turned out, in the holder's parent's space. Used to stack /// one borrowed model on top of another without a magic offset. diff --git a/JotunnModStub/Skeleton/SkeletonRise.cs b/JotunnModStub/Skeleton/SkeletonRise.cs index d44cd75..7e9827b 100644 --- a/JotunnModStub/Skeleton/SkeletonRise.cs +++ b/JotunnModStub/Skeleton/SkeletonRise.cs @@ -125,10 +125,8 @@ namespace RacesOfValheim // Everything that is not a Renderer, a Transform or the Animator. Animator is a Behaviour, // not a MonoBehaviour, so the first loop never touches it. - foreach (MonoBehaviour behaviour in copy.GetComponentsInChildren(true)) - { - if (behaviour != null) Object.DestroyImmediate(behaviour); - } + // Dependents first, so a Humanoid held down by CharacterDrop cannot survive on the copy. + ModelBorrow.StripBehaviours(copy, "Skeleton"); foreach (Collider collider in copy.GetComponentsInChildren(true)) { if (collider != null) Object.DestroyImmediate(collider); diff --git a/JotunnModStub/Sverm/SvermRavagerForm.cs b/JotunnModStub/Sverm/SvermRavagerForm.cs index f41b7f0..d9b21a7 100644 --- a/JotunnModStub/Sverm/SvermRavagerForm.cs +++ b/JotunnModStub/Sverm/SvermRavagerForm.cs @@ -103,10 +103,9 @@ namespace RacesOfValheim // Everything that is not a Renderer or a Transform. Animator is a Behaviour, not a // MonoBehaviour, so it is never touched by the first loop and survives on purpose - // it is the one live thing this costume is allowed to keep. - foreach (MonoBehaviour behaviour in copy.GetComponentsInChildren(true)) - { - if (behaviour != null) Object.DestroyImmediate(behaviour); - } + // Dependents first: a single pass left the Brute's Humanoid on the costume, because + // CharacterDrop requires it and came later. See ModelBorrow.StripBehaviours. + ModelBorrow.StripBehaviours(copy, "Sverm"); foreach (Collider collider in copy.GetComponentsInChildren(true)) { if (collider != null) Object.DestroyImmediate(collider); From 1c2da77603fd619e1c69d57c7a2ee0c621c65bb5 Mon Sep 17 00:00:00 2001 From: kanym Date: Sat, 17 Oct 2026 19:51:33 +0200 Subject: [PATCH 038/163] fix(sverm): the Ravager stands still to attack and its slam digs The hidden player kept walking under the costume, so every swing slid toward whatever WASD held. A SetControls prefix holds it still while an attack runs, as Fenrir and the True Form troll do. The middle-click slam now digs a crater on bare terrain (digg_v3), never inside a ward without access, behind a new Ground Slam Crater option. --- JotunnModStub/Sverm/SvermConfigManagement.cs | 6 ++ JotunnModStub/Sverm/SvermRavagerForm.cs | 63 ++++++++++++++++++-- 2 files changed, 64 insertions(+), 5 deletions(-) diff --git a/JotunnModStub/Sverm/SvermConfigManagement.cs b/JotunnModStub/Sverm/SvermConfigManagement.cs index a2627f8..a25aec9 100644 --- a/JotunnModStub/Sverm/SvermConfigManagement.cs +++ b/JotunnModStub/Sverm/SvermConfigManagement.cs @@ -45,6 +45,7 @@ namespace RacesOfValheim public static ConfigEntry RavagerScaleMultiplier; public static ConfigEntry RavagerYawDegrees; public static ConfigEntry RavagerAttackOffsetValue; + public static ConfigEntry RavagerSlamCraterValue; // ─── Colony caps ───────────────────────────────────────────────────── // Every ceiling on how many things the colony can have alive at once, in one section, so @@ -226,6 +227,10 @@ namespace RacesOfValheim "Raise it if a swing visibly connects short of the model's mouth/claws; lower it " + "if it connects well past them."); + RavagerSlamCraterValue = config.Bind(ravager, "Ground Slam Crater", true, + "The middle-click slam digs into the ground where it lands, like a pickaxe blow. " + + "Never inside a ward you have no access to."); + EmberGlowStrength = config.Bind(ember, "Glow Strength", SvermConfig.EmberGlowStrength, "How hot the chitin burns at Fader. This multiplies an HDR colour and it is applied " + "to the chest, the legs and the helmet at once, so it goes a very long way. Settled " + @@ -358,6 +363,7 @@ namespace RacesOfValheim public static float RavagerScale => RavagerScaleMultiplier?.Value ?? 1f; public static float RavagerYaw => RavagerYawDegrees?.Value ?? 0f; public static float RavagerAttackOffset => RavagerAttackOffsetValue?.Value ?? 1.5f; + public static bool RavagerSlamCrater => RavagerSlamCraterValue?.Value ?? true; public static bool Spines => SpinesEnabled?.Value ?? false; public static float SizeSmall => SpineSizeSmall?.Value ?? SvermConfig.SpineSizeSmall; diff --git a/JotunnModStub/Sverm/SvermRavagerForm.cs b/JotunnModStub/Sverm/SvermRavagerForm.cs index d9b21a7..68caf14 100644 --- a/JotunnModStub/Sverm/SvermRavagerForm.cs +++ b/JotunnModStub/Sverm/SvermRavagerForm.cs @@ -28,6 +28,10 @@ namespace RacesOfValheim { public static bool IsActive { get; private set; } + /// True while the local Brute is inside a swing or the roar. + /// Sverm_RavagerHoldStill_Patch holds the player still for exactly that long. + public static bool LocalAttacking { get; set; } + // Read by Sverm_RavagerRemoteVisuals_Patch (SvermPatches.cs) so every other client can // tell the form is up at all - without this the whole thing was local-only, exactly like // DrakeFormBehavior's flight flag and Fenrir's own form key, and other players saw nothing @@ -302,6 +306,7 @@ namespace RacesOfValheim private static void Exit(Player player, bool spendCooldown) { IsActive = false; + LocalAttacking = false; ZNetView exitNview = player.GetComponent(); if (exitNview != null && exitNview.IsValid()) exitNview.GetZDO().Set(ActiveKey, false); @@ -471,6 +476,30 @@ namespace RacesOfValheim /// equipped never swings and never deals damage while this is up; RavagerFormBehavior's /// own coroutines are the only thing that can land a hit. /// + /// + /// Holds the Brute still through its attack clips, the way Fenrir_FormHoldStill_Patch and + /// Trol_TrueFormHoldStill_Patch do for their forms. The hidden player kept walking under the + /// costume, so a bite or a slam slid toward whatever WASD held. + /// + [HarmonyPatch(typeof(Player), "SetControls")] + public static class Sverm_RavagerHoldStill_Patch + { + public static void Prefix(Player __instance, ref Vector3 __0, ref bool jump, ref bool crouch, ref bool dodge) + { + if (__instance != Player.m_localPlayer || !LocalAttacking) return; + if (!IsActive) + { + LocalAttacking = false; + return; + } + + __0 = Vector3.zero; + jump = false; + crouch = false; + dodge = false; + } + } + [HarmonyPatch(typeof(Humanoid), "StartAttack")] public static class Sverm_RavagerBlockNativeAttack_Patch { @@ -545,7 +574,8 @@ namespace RacesOfValheim // gate FenrirFormBehavior's own isAttacking flag uses, and the direct answer to "the // animation has to finish before the Brute can move": nothing here can start moving the // model again, or start a second attack, until the coroutine below clears it. - private bool isAttacking; + private bool isAttacking { get => attacking; set { attacking = value; SvermRavagerForm.LocalAttacking = value; } } + private bool attacking; // The taunt's own cooldown - short, and tracked separately from the other three, which // have no cooldown of their own beyond their own lock duration. @@ -655,15 +685,15 @@ namespace RacesOfValheim // be the only reliable option. if (RaceInput.AttackDown(1)) { - StartCoroutine(AttackRoutine(SvermRavagerAttacks.Ram, 2f, 0.3f, 0.7f)); + StartCoroutine(AttackRoutine(SvermRavagerAttacks.Ram, 2f, 0.3f, 0.7f, false)); } else if (RaceInput.AttackDown(0)) { - StartCoroutine(AttackRoutine(SvermRavagerAttacks.Bite, 2f, 0.3f, 0.6f)); + StartCoroutine(AttackRoutine(SvermRavagerAttacks.Bite, 2f, 0.3f, 0.6f, false)); } else if (RaceInput.AttackDown(2)) { - StartCoroutine(AttackRoutine(SvermRavagerAttacks.Slam, 1.2f, 0.4f, 1.0f)); + StartCoroutine(AttackRoutine(SvermRavagerAttacks.Slam, 1.2f, 0.4f, 1.0f, true)); } else if ((SvermConfigManagement.RavagerKey.Value.IsDown() || RaceInput.ConsumePress(SvermConfigManagement.RavagerKey.Value)) && Time.time >= nextTauntAt) @@ -680,7 +710,7 @@ namespace RacesOfValheim /// (SvermRavagerAttacks) instead of one tuned float. /// private System.Collections.IEnumerator AttackRoutine(SvermRavagerAttacks.Profile profile, float radius, - float hitDelay, float lockDuration) + float hitDelay, float lockDuration, bool digs) { isAttacking = true; @@ -695,6 +725,7 @@ namespace RacesOfValheim yield return new WaitForSeconds(hitDelay); ExecuteDamage(profile, radius); + if (digs) DigCrater(); float remaining = lockDuration - hitDelay; if (remaining > 0f) yield return new WaitForSeconds(remaining); @@ -768,6 +799,28 @@ namespace RacesOfValheim ApplyDamageInSphere(attackPoint, radius, profile.Damage); } + private const string CraterPrefab = "digg_v3"; + private static readonly int GroundMask = LayerMask.GetMask("terrain", "Default", "static_solid", "piece"); + + /// + /// The slam digs where it lands, the way the True Form troll's does (TrolTrueFormBehavior.Slam): + /// a pickaxe's dig on bare terrain only. TerrainOp does not check wards on its own, so the + /// ward check is done here. + /// + private static void DigCrater() + { + Player player = Player.m_localPlayer; + if (player == null || !SvermConfigManagement.RavagerSlamCrater) return; + + Vector3 impact = player.transform.position + player.transform.forward * SvermConfigManagement.RavagerAttackOffset; + if (!Physics.Raycast(impact + Vector3.up * 3f, Vector3.down, out RaycastHit ground, 8f, GroundMask)) return; + if (ground.collider == null || ground.collider.GetComponent() == null) return; + if (!PrivateArea.CheckAccess(ground.point, 0f, false)) return; + + GameObject crater = Jotunn.Managers.PrefabManager.Cache.GetPrefab(CraterPrefab); + if (crater != null) Object.Instantiate(crater, ground.point, Quaternion.identity); + } + /// /// The actual sweep, shared by every attack this form has (the three forward swings and /// the taunt's own AoE) - only the sphere's centre and radius differ between them. From 61a74320c5bfccf7b6e5bfc1c94be1055d28aed7 Mon Sep 17 00:00:00 2001 From: kanym Date: Sat, 17 Oct 2026 20:05:36 +0200 Subject: [PATCH 039/163] fix(sverm): Ravager attacks follow the Brute's clips; the slam hits once per claw Hits land on the clip's own Hit events and the hold-still lasts until the animator leaves the attack state, instead of fixed delays. The slam has two Hit events, one per claw: each one hits and digs under the claw that came down. --- JotunnModStub/Sverm/SvermRavagerForm.cs | 219 +++++++++++++++++++----- 1 file changed, 176 insertions(+), 43 deletions(-) diff --git a/JotunnModStub/Sverm/SvermRavagerForm.cs b/JotunnModStub/Sverm/SvermRavagerForm.cs index 68caf14..01ad562 100644 --- a/JotunnModStub/Sverm/SvermRavagerForm.cs +++ b/JotunnModStub/Sverm/SvermRavagerForm.cs @@ -585,8 +585,19 @@ namespace RacesOfValheim // present, so PlayAttack does not pass a name to SetTrigger the controller cannot use. private readonly System.Collections.Generic.HashSet knownTriggers = new System.Collections.Generic.HashSet(); + // The two front claws (bone names read from the SeekerBrute prefab with UnityPy). The slam + // brings one down, then the other; each Hit lands under whichever claw just came down. + private Transform leftClaw; + private Transform rightClaw; + private void Start() { + foreach (Transform bone in GetComponentsInChildren(true)) + { + if (bone.name == "l.frontfoot") leftClaw = bone; + else if (bone.name == "r.frontfoot") rightClaw = bone; + } + anim = GetComponentInChildren(); if (anim == null || anim.runtimeAnimatorController == null) return; @@ -685,15 +696,15 @@ namespace RacesOfValheim // be the only reliable option. if (RaceInput.AttackDown(1)) { - StartCoroutine(AttackRoutine(SvermRavagerAttacks.Ram, 2f, 0.3f, 0.7f, false)); + StartCoroutine(AttackRoutine(SvermRavagerAttacks.Ram, "Attack Ram", 2f, false)); } else if (RaceInput.AttackDown(0)) { - StartCoroutine(AttackRoutine(SvermRavagerAttacks.Bite, 2f, 0.3f, 0.6f, false)); + StartCoroutine(AttackRoutine(SvermRavagerAttacks.Bite, "Attack Bite", 2f, false)); } else if (RaceInput.AttackDown(2)) { - StartCoroutine(AttackRoutine(SvermRavagerAttacks.Slam, 1.2f, 0.4f, 1.0f, true)); + StartCoroutine(AttackRoutine(SvermRavagerAttacks.Slam, "Attack Slam", 1.2f, true)); } else if ((SvermConfigManagement.RavagerKey.Value.IsDown() || RaceInput.ConsumePress(SvermConfigManagement.RavagerKey.Value)) && Time.time >= nextTauntAt) @@ -704,31 +715,33 @@ namespace RacesOfValheim } /// - /// One swing: play the clip, wait for the moment it should land, hit whatever is there, - /// then hold isAttacking until the swing is fully spent. FenrirFormBehavior.ClawRoutine in - /// every particular except the damage itself, which here is the Brute's own real numbers - /// (SvermRavagerAttacks) instead of one tuned float. + /// One swing, timed by the clip itself instead of by fixed delays. Each "Hit" animation + /// event in the clip is a hit here, at the same point of the clip (the bite and the ram + /// have one, the slam has two, one per claw). The player is held still until the + /// animator starts blending out of the attack state, which is when the real Brute can + /// move again. /// - private System.Collections.IEnumerator AttackRoutine(SvermRavagerAttacks.Profile profile, float radius, - float hitDelay, float lockDuration, bool digs) + private System.Collections.IEnumerator AttackRoutine(SvermRavagerAttacks.Profile profile, string stateName, + float radius, bool slam) { isAttacking = true; + bool played = StartAttackState(profile); - if (hasForwardSpeed) anim.SetFloat("forward_speed", 0f); + int dropSamples = 0; + float[] leftY = new float[ClawHistory]; + float[] rightY = new float[ClawHistory]; - if (!string.IsNullOrEmpty(profile.Trigger) && knownTriggers.Contains(profile.Trigger)) + yield return FollowAttackState(stateName, played, 0f, () => { - anim.SetTrigger(profile.Trigger); - SvermRavagerForm.PublishAttackTrigger(Player.m_localPlayer, profile.Trigger); - } - - yield return new WaitForSeconds(hitDelay); - - ExecuteDamage(profile, radius); - if (digs) DigCrater(); - - float remaining = lockDuration - hitDelay; - if (remaining > 0f) yield return new WaitForSeconds(remaining); + if (slam) Slam(profile, radius, leftY, rightY, dropSamples); + else ExecuteDamage(profile, radius); + }, () => + { + if (leftClaw == null || rightClaw == null) return; + leftY[dropSamples % ClawHistory] = leftClaw.position.y; + rightY[dropSamples % ClawHistory] = rightClaw.position.y; + dropSamples++; + }); isAttacking = false; } @@ -738,37 +751,159 @@ namespace RacesOfValheim /// swing - the roar reaches out in every direction, so the sphere is centred on the /// player instead of offset ahead of them the way AttackRoutine's three do. Deliberately /// silent: no message, no status effect, nothing in a corner of the screen - just the - /// animation, the sound if one resolves, and the hit. + /// animation, the sound if one resolves, and the hit. The clip has no Hit event, so the + /// roar lands at TauntHitPoint of the clip. /// private System.Collections.IEnumerator TauntRoutine() { isAttacking = true; SvermRavagerAttacks.Profile profile = SvermRavagerAttacks.Taunt; - - if (hasForwardSpeed) anim.SetFloat("forward_speed", 0f); - - if (!string.IsNullOrEmpty(profile.Trigger) && knownTriggers.Contains(profile.Trigger)) - { - anim.SetTrigger(profile.Trigger); - SvermRavagerForm.PublishAttackTrigger(Player.m_localPlayer, profile.Trigger); - } + bool played = StartAttackState(profile); PlaySound(SvermConfig.RavagerTauntSoundEffects); - yield return new WaitForSeconds(0.3f); - - Player player = Player.m_localPlayer; - if (player != null) + yield return FollowAttackState("Taunt", played, TauntHitPoint, () => { - ApplyDamageInSphere(player.transform.position + Vector3.up, SvermConfig.RavagerTauntRadius, profile.Damage); - } - - yield return new WaitForSeconds(0.4f); + Player player = Player.m_localPlayer; + if (player != null) + ApplyDamageInSphere(player.transform.position + Vector3.up, SvermConfig.RavagerTauntRadius, profile.Damage); + }, null); isAttacking = false; } + // 0.3 s into the 2.67 s taunt clip, where the old fixed delay put the roar's hit. + private const float TauntHitPoint = 0.11f; + + // Frames of claw height kept to tell which claw just came down (about 0.2 s at 60 fps). + private const int ClawHistory = 12; + + private bool StartAttackState(SvermRavagerAttacks.Profile profile) + { + if (hasForwardSpeed) anim.SetFloat("forward_speed", 0f); + + if (string.IsNullOrEmpty(profile.Trigger) || !knownTriggers.Contains(profile.Trigger)) return false; + + anim.SetTrigger(profile.Trigger); + SvermRavagerForm.PublishAttackTrigger(Player.m_localPlayer, profile.Trigger); + return true; + } + + /// + /// Waits out one attack state frame by frame. Calls onHit at every Hit event of the + /// state's clip (or once at fallbackHit, a 0-1 point of the clip, when the clip has + /// none), and returns once the animator starts leaving the state. If the state never + /// starts (trigger missing), it hits once and returns, so the attack still works. + /// + private System.Collections.IEnumerator FollowAttackState(string stateName, bool played, float fallbackHit, + System.Action onHit, System.Action eachFrame) + { + float startedAt = Time.time; + bool entered = false; + float[] hits = null; + int nextHit = 0; + + while (played && Time.time - startedAt < 8f) + { + eachFrame?.Invoke(); + + AnimatorStateInfo state; + AnimatorClipInfo[] clips; + bool leaving; + if (!TryGetAttackState(stateName, out state, out clips, out leaving)) + { + if (entered || Time.time - startedAt > 0.5f) break; + yield return null; + continue; + } + + entered = true; + if (hits == null) hits = ReadHitPoints(clips, fallbackHit); + + while (nextHit < hits.Length && state.normalizedTime >= hits[nextHit]) + { + onHit(); + nextHit++; + } + + if (leaving) break; + yield return null; + } + + if (!entered) onHit(); + } + + private bool TryGetAttackState(string stateName, out AnimatorStateInfo state, out AnimatorClipInfo[] clips, out bool leaving) + { + state = anim.GetCurrentAnimatorStateInfo(0); + if (state.IsName(stateName)) + { + clips = anim.GetCurrentAnimatorClipInfo(0); + leaving = anim.IsInTransition(0); + return true; + } + + leaving = false; + if (anim.IsInTransition(0)) + { + state = anim.GetNextAnimatorStateInfo(0); + if (state.IsName(stateName)) + { + clips = anim.GetNextAnimatorClipInfo(0); + return true; + } + } + + clips = null; + return false; + } + + private static float[] ReadHitPoints(AnimatorClipInfo[] clips, float fallbackHit) + { + var points = new System.Collections.Generic.List(); + if (clips != null && clips.Length > 0 && clips[0].clip != null && clips[0].clip.length > 0f) + { + AnimationClip clip = clips[0].clip; + foreach (AnimationEvent ev in clip.events) + if (ev.functionName == "Hit") points.Add(ev.time / clip.length); + } + + if (points.Count == 0) points.Add(fallbackHit); + points.Sort(); + return points.ToArray(); + } + + /// + /// One claw of the slam landing: the claw that dropped the most over the last few frames + /// is the one that just struck. Damage and crater go under it, not at a fixed point ahead. + /// + private void Slam(SvermRavagerAttacks.Profile profile, float radius, float[] leftY, float[] rightY, int samples) + { + Transform claw = StrikingClaw(leftY, rightY, samples); + if (claw == null) + { + ExecuteDamage(profile, radius); + Player player = Player.m_localPlayer; + if (player != null) + DigCrater(player.transform.position + player.transform.forward * SvermConfigManagement.RavagerAttackOffset); + return; + } + + ApplyDamageInSphere(claw.position + Vector3.up * 0.5f, radius, profile.Damage); + DigCrater(claw.position); + } + + private Transform StrikingClaw(float[] leftY, float[] rightY, int samples) + { + if (leftClaw == null || rightClaw == null || samples == 0) return null; + + int oldest = samples < ClawHistory ? 0 : samples % ClawHistory; + float leftDrop = leftY[oldest] - leftClaw.position.y; + float rightDrop = rightY[oldest] - rightClaw.position.y; + return leftDrop >= rightDrop ? leftClaw : rightClaw; + } + /// Tries each candidate in order and plays the first that resolves, same as SvermRavagerForm.PlayEffect. private static void PlaySound(string[] candidates) { @@ -807,12 +942,10 @@ namespace RacesOfValheim /// a pickaxe's dig on bare terrain only. TerrainOp does not check wards on its own, so the /// ward check is done here. /// - private static void DigCrater() + private static void DigCrater(Vector3 impact) { - Player player = Player.m_localPlayer; - if (player == null || !SvermConfigManagement.RavagerSlamCrater) return; + if (Player.m_localPlayer == null || !SvermConfigManagement.RavagerSlamCrater) return; - Vector3 impact = player.transform.position + player.transform.forward * SvermConfigManagement.RavagerAttackOffset; if (!Physics.Raycast(impact + Vector3.up * 3f, Vector3.down, out RaycastHit ground, 8f, GroundMask)) return; if (ground.collider == null || ground.collider.GetComponent() == null) return; if (!PrivateArea.CheckAccess(ground.point, 0f, false)) return; From d05cea7f083ef7482afa8056935ff8ce56f3d916 Mon Sep 17 00:00:00 2001 From: kanym Date: Sat, 17 Oct 2026 20:24:43 +0200 Subject: [PATCH 040/163] fix(warvulture): strip dependents first, no more Can't remove Humanoid at startup The startup error came from WarVultureVisual.BuildTemplate, not from the Ravager costume: its passes tried Humanoid before CharacterDrop. Components another one still requires now wait for a later pass. --- JotunnModStub/ModelBorrow.cs | 2 +- JotunnModStub/WarVulture/WarVultureItem.cs | 1 + JotunnModStub/WarVulture/WarVultureVisual.cs | 9 +++++++++ 3 files changed, 11 insertions(+), 1 deletion(-) diff --git a/JotunnModStub/ModelBorrow.cs b/JotunnModStub/ModelBorrow.cs index 1bd8fd2..08a777b 100644 --- a/JotunnModStub/ModelBorrow.cs +++ b/JotunnModStub/ModelBorrow.cs @@ -157,7 +157,7 @@ namespace RacesOfValheim /// True if another component on the same GameObject names this one's type in a /// [RequireComponent]. - private static bool IsRequired(Component target) + public static bool IsRequired(Component target) { System.Type type = target.GetType(); foreach (Component other in target.GetComponents()) diff --git a/JotunnModStub/WarVulture/WarVultureItem.cs b/JotunnModStub/WarVulture/WarVultureItem.cs index 7b735fa..74fc487 100644 --- a/JotunnModStub/WarVulture/WarVultureItem.cs +++ b/JotunnModStub/WarVulture/WarVultureItem.cs @@ -229,6 +229,7 @@ namespace RacesOfValheim if (component is MeshFilter) continue; if (component is MeshRenderer) continue; if (component is SkinnedMeshRenderer) continue; + if (ModelBorrow.IsRequired(component)) continue; // a later pass, once its dependent is gone Object.DestroyImmediate(component); diff --git a/JotunnModStub/WarVulture/WarVultureVisual.cs b/JotunnModStub/WarVulture/WarVultureVisual.cs index cf42a91..1a944f9 100644 --- a/JotunnModStub/WarVulture/WarVultureVisual.cs +++ b/JotunnModStub/WarVulture/WarVultureVisual.cs @@ -118,6 +118,15 @@ namespace RacesOfValheim if (component == null) continue; if (IsKept(component)) continue; + // Not yet if something still requires it: Unity would refuse and log an error + // ("Can't remove Humanoid because CharacterDrop depends on it"). It goes on a + // later pass, once its dependent is gone. + if (ModelBorrow.IsRequired(component)) + { + stubborn++; + continue; + } + Object.DestroyImmediate(component); if (component == null) destroyedSomething = true; From 63e252d9e94e08ffe2a6468fca01a7e0efd9f376 Mon Sep 17 00:00:00 2001 From: kanym Date: Sat, 17 Oct 2026 20:24:43 +0200 Subject: [PATCH 041/163] feat(sverm): the Ravager's ram lunges with the clip's root motion Vanilla only takes root motion during a native attack, which this form never starts, so a relay on the costume's Animator collects it and a prefix on Character.ApplyRootMotion applies it to the player the same way (x55). --- JotunnModStub/Sverm/SvermRavagerForm.cs | 69 +++++++++++++++++++++++-- 1 file changed, 64 insertions(+), 5 deletions(-) diff --git a/JotunnModStub/Sverm/SvermRavagerForm.cs b/JotunnModStub/Sverm/SvermRavagerForm.cs index 01ad562..bee58bb 100644 --- a/JotunnModStub/Sverm/SvermRavagerForm.cs +++ b/JotunnModStub/Sverm/SvermRavagerForm.cs @@ -500,6 +500,37 @@ namespace RacesOfValheim } } + /// The ram clip's own forward motion, collected by RavagerRootMotionRelay and + /// spent by Sverm_RavagerRootMotion_Patch. + public static Vector3 PendingRootMotion; + + /// + /// Moves the player by the ram clip's root motion, the way vanilla moves a charging Brute. + /// Vanilla's own path (CharacterAnimEvent.OnAnimatorMove into Character.AddRootMotion) only + /// takes motion while Character.InAttack(), and this form never starts a native attack, so + /// the motion comes in here instead and is applied exactly as Character.ApplyRootMotion + /// applies it: delta times 55, used when it is faster than the walk velocity. + /// + [HarmonyPatch(typeof(Character), "ApplyRootMotion")] + public static class Sverm_RavagerRootMotion_Patch + { + public static void Prefix(Character __instance, ref Vector3 vel) + { + if (__instance != Player.m_localPlayer) return; + + Vector3 motion = PendingRootMotion; + PendingRootMotion = Vector3.zero; + if (!IsActive || !LocalAttacking) return; + + Vector3 push = motion * 55f; + push.y = 0f; + if (push.magnitude > new Vector3(vel.x, 0f, vel.z).magnitude) + { + vel = new Vector3(push.x, vel.y, push.z); + } + } + } + [HarmonyPatch(typeof(Humanoid), "StartAttack")] public static class Sverm_RavagerBlockNativeAttack_Patch { @@ -546,6 +577,23 @@ namespace RacesOfValheim } } + /// + /// Sits on the costume's Animator object. Unity calls OnAnimatorMove there instead of moving + /// the costume itself; while Active (the ram), the clip's motion is handed to the player + /// through SvermRavagerForm.PendingRootMotion. Otherwise it is dropped, so the costume stays + /// where the player is. + /// + public class RavagerRootMotionRelay : MonoBehaviour + { + public Animator Animator; + public bool Active; + + private void OnAnimatorMove() + { + if (Active && Animator != null) SvermRavagerForm.PendingRootMotion += Animator.deltaPosition; + } + } + /// /// Locomotion AND combat, both held on every frame while the form is up - built on the same /// method FenrirFormBehavior and DrakeFormBehavior already use for their own transformations, @@ -590,6 +638,8 @@ namespace RacesOfValheim private Transform leftClaw; private Transform rightClaw; + private RavagerRootMotionRelay rootMotion; + private void Start() { foreach (Transform bone in GetComponentsInChildren(true)) @@ -615,6 +665,13 @@ namespace RacesOfValheim anim.fireEvents = false; anim.cullingMode = AnimatorCullingMode.AlwaysAnimate; + // The ram is the exception: its clip's motion moves the PLAYER (see + // Sverm_RavagerRootMotion_Patch). With an OnAnimatorMove receiver on the Animator's + // object, Unity computes the motion and hands it over instead of moving the costume. + rootMotion = anim.gameObject.AddComponent(); + rootMotion.Animator = anim; + anim.applyRootMotion = true; + foreach (AnimatorControllerParameter param in anim.parameters) { if (param.type == AnimatorControllerParameterType.Float && param.name == "forward_speed") @@ -696,15 +753,15 @@ namespace RacesOfValheim // be the only reliable option. if (RaceInput.AttackDown(1)) { - StartCoroutine(AttackRoutine(SvermRavagerAttacks.Ram, "Attack Ram", 2f, false)); + StartCoroutine(AttackRoutine(SvermRavagerAttacks.Ram, "Attack Ram", 2f, false, true)); } else if (RaceInput.AttackDown(0)) { - StartCoroutine(AttackRoutine(SvermRavagerAttacks.Bite, "Attack Bite", 2f, false)); + StartCoroutine(AttackRoutine(SvermRavagerAttacks.Bite, "Attack Bite", 2f, false, false)); } else if (RaceInput.AttackDown(2)) { - StartCoroutine(AttackRoutine(SvermRavagerAttacks.Slam, "Attack Slam", 1.2f, true)); + StartCoroutine(AttackRoutine(SvermRavagerAttacks.Slam, "Attack Slam", 1.2f, true, false)); } else if ((SvermConfigManagement.RavagerKey.Value.IsDown() || RaceInput.ConsumePress(SvermConfigManagement.RavagerKey.Value)) && Time.time >= nextTauntAt) @@ -719,13 +776,14 @@ namespace RacesOfValheim /// event in the clip is a hit here, at the same point of the clip (the bite and the ram /// have one, the slam has two, one per claw). The player is held still until the /// animator starts blending out of the attack state, which is when the real Brute can - /// move again. + /// move again. With lunge, the clip's own root motion carries the player forward (the ram). /// private System.Collections.IEnumerator AttackRoutine(SvermRavagerAttacks.Profile profile, string stateName, - float radius, bool slam) + float radius, bool slam, bool lunge) { isAttacking = true; bool played = StartAttackState(profile); + if (rootMotion != null) rootMotion.Active = lunge; int dropSamples = 0; float[] leftY = new float[ClawHistory]; @@ -743,6 +801,7 @@ namespace RacesOfValheim dropSamples++; }); + if (rootMotion != null) rootMotion.Active = false; isAttacking = false; } From f1d00f6eff46470b58295394fcb30ac26fc0ed98 Mon Sep 17 00:00:00 2001 From: kanym Date: Sat, 17 Oct 2026 20:30:37 +0200 Subject: [PATCH 042/163] chore(release): v1.5.11 - True Form troll, race stations, Ravager attacks Trol True Form wears the vanilla forest troll, with a per-player Legacy switch for model mods. Race stations show and require their race and go on floors and in caves. Fenrir forms sneak and stand still to attack; the Ulv sleeps when the player sits. The Ravager attacks on the Brute's own clips. Fixes: ResetRace, troll cave collapse, [msg_] texts, build-mode attacks, War Vulture startup error. README: New in block, changelog entry, Trol/Fenrir/Sverm feature lines and the stations section. --- JotunnModStub/Package/manifest.json | 2 +- JotunnModStub/RacesOfValheim.cs | 2 +- README.md | 27 +++++++++++++++++++++------ manifest.json | 2 +- 4 files changed, 24 insertions(+), 9 deletions(-) diff --git a/JotunnModStub/Package/manifest.json b/JotunnModStub/Package/manifest.json index 47424f1..0c5a46e 100644 --- a/JotunnModStub/Package/manifest.json +++ b/JotunnModStub/Package/manifest.json @@ -1,7 +1,7 @@ { "name": "RacesOfValheim", "description": "A Valheim mod that adds ten custom playable races (Aswid, Draugh, Dvergar, Fenrir, Furling, Skadi, Skeleton, Sverm, Trenta, Trol) each with unique abilities, traits, race stations and a deep boss-driven progression system.", - "version_number": "1.5.10", + "version_number": "1.5.11", "website_url": "", "dependencies": [ "denikson-BepInExPack_Valheim-5.4.2333", diff --git a/JotunnModStub/RacesOfValheim.cs b/JotunnModStub/RacesOfValheim.cs index 0702646..2a6b881 100644 --- a/JotunnModStub/RacesOfValheim.cs +++ b/JotunnModStub/RacesOfValheim.cs @@ -16,7 +16,7 @@ namespace RacesOfValheim { public const string PluginGUID = "com.nandor.racesofvalheim"; public const string PluginName = "Races Of Valheim"; - public const string PluginVersion = "1.5.10"; + public const string PluginVersion = "1.5.11"; private readonly Harmony harmony = new Harmony(PluginGUID); diff --git a/README.md b/README.md index 68d1e8d..ee6039c 100644 --- a/README.md +++ b/README.md @@ -15,9 +15,9 @@ Support the mod: [Patreon — NandorTheModder](https://www.patreon.com/c/NandorT --- -## New in v1.5.10 +## New in v1.5.11 -Using a player model mod such as EnhancedValheimVRM? Turn off `Skeleton - Visuals` → `Body Model Enabled` and Skeletons keep the vanilla body, so no bones clip through your model. Trols can pick their own skin and hair colour under `Trol - Appearance`. Full details in the [changelog](#v1510). +The Trol's True Form now wears Valheim's own forest troll, with its punches, ground slam and log swings; players with a model mod can keep the old True Form with `Trol - True Form` → `Legacy True Form`. The Sverm's Ravager attacks on the Seeker Brute's own animations: the ram lunges and the slam strikes with both claws. Race stations show and require their race in the build panel, and most of them now go on floors and inside caves. The Ulv sleeps when you sit. Full details in the [changelog](#v1511). --- @@ -47,6 +47,7 @@ Using a player model mod such as EnhancedValheimVRM? Turn off `Skeleton - Visual - **Beast Form:** Transform into a wolf-like beast. - **Cultist Form:** Transform into a Cultist. Its claws cost nothing, but the **fire breath (hold Right Mouse) runs on eitr** — 12.5 per second — and eitr comes from the Mistlands, so the form unlocks at Yagluth with its flames still out of reach. Holding the button with an empty pool now says so. - **Cursed Claws:** The wolf's hands, kept on in the man's shape — see [Claws](#claws). +- **Sneak and Sleep:** Forms sneak at a walk when you crouch and stand still to attack. Sit down as an Ulv and it curls up asleep. - **A Pack of Your Own:** The Pack Trough keeps a standing pack of wolves, ulvs and, late, fenrir — see [Race Stations](#race-stations--companions). - **Progression:** Forms grow as you defeat bosses, unlocking new powers and reducing cooldowns. Immune to fall damage. @@ -71,7 +72,7 @@ Using a player model mod such as EnhancedValheimVRM? Turn off `Skeleton - Visual - **Kindling:** the one drawback — fire lands 50% harder on a Trol than on anyone else, and no armour or resistance changes that. - **Immense Strength:** Increased carry weight; armor scales up as you defeat bosses. - **Rock Throwing:** Hurl huge boulders at enemies. -- **Tree Weaponry:** At higher tiers, True Form lets you rip logs and wield them as weapons or throw them. +- **True Form:** From Moder, become a forest troll: punch, slam the ground, and from the Queen swing or throw a log. Using a player model mod? `Trol - True Form` → `Legacy True Form` keeps your own Trol, grown huge, with weapons in hand. - **Your Own Colours:** pick your skin and hair colour under `Trol - Appearance`. Other players see them too. ### 7. Draugh @@ -102,7 +103,7 @@ Using a player model mod such as EnhancedValheimVRM? Turn off `Skeleton - Visual - **Hive Pheromones:** No invertebrate attacks you — leeches, ticks, deathsquitos, seekers and bees all ignore you, from tier zero. - **Toxin Immunity:** Poison cannot touch you. Blunt and fire hit you 40% harder — until Fader, when the fire weakness burns out and comes back as a resistance. - **The Colony:** After the Elder, a Brood Mound, a Hive Market and a roster of insect troops bought with digested biomass. -- **Ravager Strain:** After Yagluth, become a Seeker Brute — the claws keep fighting, and the carapace is worth double. +- **Ravager Strain:** After Yagluth, become a Seeker Brute, with its own bite, lunging ram and two-claw ground slam that digs the earth. The carapace is worth double. --- @@ -293,10 +294,10 @@ Build a **Brood Mound** with the hammer — no more than two within its density ## Race Stations & Companions -Every race has a buildable station of its own, gated by a reagent bought from its faction's merchant. Stations of the same kind cannot be packed on top of each other — each has its own minimum spacing. Servants raised at any of them share one system: they follow when asked, walk home when dismissed, carry no loot on death, and knit their own wounds shut (ten seconds unhurt, then 2% a second). +Every race has a buildable station of its own, gated by a reagent bought from its faction's merchant. Each one needs its race: the build panel lists the race first and greys the station for anyone else. All of them go on floors, foundations and inside caves, except the living ones (Furling bushes, the Sverm nest and Hive Market, the Trenta's Elder Root), which need bare ground. Stations of the same kind cannot be packed on top of each other — each has its own minimum spacing. Servants raised at any of them share one system: they follow when asked, walk home when dismissed, carry no loot on death, and knit their own wounds shut (ten seconds unhurt, then 2% a second). - **Aswid — Blood Refinery:** refines Blood Essence, Superior Blood Essence and Blood Core. -- **Draugh — Cursed Body Pile:** eats raw flesh and answers with tamed draugr; Draugr and Elite trophies are worth a whole batch. Anyone can build it, but only a Draugh gives the draugr orders — for everyone else it is a grave that defends its own ten meters. +- **Draugh — Cursed Body Pile:** eats raw flesh and answers with tamed draugr; Draugr and Elite trophies are worth a whole batch. Draugh only. - **Furling — Five crops:** Copper, Tin and Iron Flax grow metal out of poisoned soil; Stoneberry and Flintberry bushes give stone and flint. - **Skadi — Crystal Golem & Bone Cook:** a stonecutter-bound guardian on a leash. Skadi (and Trol) may also build inside any troll cave in the world. The Cook is Skadi's own half of the [Bone Servants](#skeleton--skadi--bone-servants). - **Skeleton — Bound Bone Pile, Bound Sentry & Bone Smith:** pay once per slot and that slot refills itself forever, because an army you re-buy after every fight is one nobody takes out of the house. Both the pile and the Sentry can be built on the ground, on floors and on foundations. The Sentry is a bound archer that cannot walk, regenerates when left alone, and hands its parts back when it falls. The Smith is Skeleton and Skadi's shared half of the [Bone Servants](#skeleton--skadi--bone-servants). @@ -449,6 +450,20 @@ Both halves have an off switch under `Factions` in Configuration Manager: **Fact ## Changelog +### v1.5.11 +- **New - Trol True Form wears a real troll:** True Form hides your Trol and puts Valheim's own forest troll in its place, as tall as the old True Form, in your Trol's skin colour. Every player sees it. Weapons are put away while it lasts: left click punches, right click slams the ground, and with a log in hand they become the troll's two log swings. The slam breaks trees and rocks around it and digs into the ground, never inside a ward you have no access to. Throw Rock plays the troll's own throw. You stand still through every attack. Damage is half a real troll's, scaled by your Clubs skill like a club, and the True Form and tier melee bonuses still add on top. New options under `Trol - True Form`: `Troll Model Size`, `Troll Attack Damage`, `Troll Attack Reach`, `Ground Slam Crater`. +- **New - Legacy True Form:** prefer the old True Form, your own Trol grown bigger with weapons in hand? Turn on `Trol - True Form` → `Legacy True Form`. Use it with EnhancedValheimVRM or another player model mod, which needs the player's body to stay visible. Each player picks their own and other players see you the way you picked; a server cannot force it. Thanks to the players who answered the Discord poll. +- **New - race stations ask for their race:** the build panel lists the race a station needs first, before its materials, with the race's icon and name, and it blinks red if you are not of that race, like a missing crafting station. The station is greyed in the menu and a click says the requirements are missing. Seven stations anyone could build before now need their race too: the Cursed Body Pile (Draugh), the Pack Trough (Fenrir), the Bone Pile and Bound Sentry (Skeleton), the Blood Refinery (Aswid), the Composter and the Heartwood Grove (Trenta). Stations already built stay where they are. +- **Change - Fenrir forms sneak and stand still to attack:** crouching in a form no longer slides the creature across the ground in its idle pose: it walks, at sneaking speed. Attacks hold you still the way a human's swing does, instead of sliding toward the direction you hold; the leaps still leap. The True Form troll sneaks the same way. Thanks to the player who suggested it. +- **New - the Ulv sleeps when you sit:** sit down in Ulv form, with the sit key or on a chair, and the Ulv curls up asleep; stand up and it wakes. Every player nearby sees it. On a chair or a bench, every form now settles on the floor in front of the seat instead of standing inside it. The Wolf, the Fenring and the Cultist have no sleeping animation in the game and stay on their feet. +- **Fix - forms attacked while building:** with the hammer, hoe or cultivator in hand, right click (remove) and middle click (snap point) also fired the form's attacks. They no longer do. +- **Fix - forms and cooldowns survived a race reset:** resetting your race (console or Race Menu Ward) while in a form or with a cooldown running could carry it onto the new race: a Trol stayed huge in True Form, a Skadi stayed a drake, an Aswid stayed a bat or mist, and some cooldowns came back with no timer in the bar. The reset now drops every form at once, removes every status effect of the mod, and puts you back at normal size. The console prints what it removed. +- **Fix - pieces built in a troll cave broke while you were away:** the cave's own Troll spared your buildings only while you stood nearby. Walk out and it smashed them, and you came back to the materials on the floor. Creatures of your race's faction now leave alone anything your race built, whether you are home or not, and a blow aimed at something else no longer damages your pieces beside it. Pieces built before the update are covered the next time you load them. A creature you have attacked holds a grudge and does not spare your buildings until it passes. +- **Fix - four messages showed as [msg_...]:** the Trol's "already digesting" and "stomach full" lines, the Aswid's Vae Victis meal and the "not enough coins" line at the Dvergar bank and the Trol totem. The first three now use Valheim's own texts, the last is translated. +- **Fix - no placement ghost for most race stations:** aim anywhere but bare terrain (a floor, a rock, the floor of a troll cave) and the Trol War Totem showed no ghost at all, so you could not tell why it would not go down. The same held for the Cursed Body Pile, the Dvergar Bank, the Rune Barrel, the Pack Trough, the Skadi Golem and the Bone Servants. All of them now show their ghost everywhere and can be built on floors, foundations and inside caves, like the Bone Pile. The living pieces (Furling bushes, the Sverm nest and Hive Market, the Trenta Elder Root) still go on terrain only; elsewhere their ghost now shows red instead of vanishing. The War Totem had a second problem of its own: its ghost was invisible everywhere, terrain included, and now shows like the others. Thanks to the players who reported it. +- **Change - the Ravager's attacks follow its animations:** in Ravager Strain the Brute slid toward whatever direction you held while it bit, rammed, slammed or roared, and its hits landed on fixed timers that didn't match the clips. Each attack now hits at the moment the Seeker Brute's own animation strikes, and the Brute stands still until the animation ends, like the Fenrir forms and the True Form troll. Attacks take as long as the real Brute's: the bite about 1.5 s, the ram about 2.5 s, the slam about 4 s. The right-click ram now lunges a few metres forward, carried by the Seeker Brute's own charge animation. The middle-click slam brings down one claw and then the other, so it hits twice, as the Seeker Brute's does. Each claw digs into the ground where it lands, like the troll's slam, never inside a ward you have no access to. Turn the digging off with `Sverm - Ravager Strain` → `Ground Slam Crater`. **Tell us on Discord** how the new timing, the lunge and the two-claw slam feel. +- **Fix - error at game start:** the BepInEx log showed `Can't remove Humanoid (Script) because CharacterDrop (Script) depends on it` while the mod prepared the War Vulture's model. It was harmless, since the model came out clean on the next pass, but it looked like a crash in every log you sent us. It no longer appears. + ### v1.5.10 - **New - Skeleton body switch for player model mods:** with EnhancedValheimVRM or another model replacer, the skeleton's bones stayed on screen and floated around the new model. Set `Skeleton - Visuals` → `Body Model Enabled` to off and Skeletons keep the vanilla body: no bones, eye lights or skull flames, and the helmet shows. Abilities don't change. The setting is client-side, so it applies to every Skeleton you see and changes nothing for other players. The race strips hair and beard, so the vanilla body is bald, and the auto-resurrection still shows the skeleton for the few seconds it climbs out of the ground. Thanks to the players who reported it and tested the fix. - **New - Trol skin and hair colour:** `Trol - Appearance` has a colour picker for the skin and one for the hair and beard. Each Trol picks their own and every player sees them. The defaults are the old peacock blue and golden blonde, so nobody's Trol changes after the update. For the blue-grey of Valheim's own trolls, try `7FA8C9`. A Trol on an older version of the mod shows the defaults to everyone else. Thanks to the player who suggested it. diff --git a/manifest.json b/manifest.json index 47424f1..0c5a46e 100644 --- a/manifest.json +++ b/manifest.json @@ -1,7 +1,7 @@ { "name": "RacesOfValheim", "description": "A Valheim mod that adds ten custom playable races (Aswid, Draugh, Dvergar, Fenrir, Furling, Skadi, Skeleton, Sverm, Trenta, Trol) each with unique abilities, traits, race stations and a deep boss-driven progression system.", - "version_number": "1.5.10", + "version_number": "1.5.11", "website_url": "", "dependencies": [ "denikson-BepInExPack_Valheim-5.4.2333", From 5dff5e1b8426e83ef8eab859fdc74d2166c48934 Mon Sep 17 00:00:00 2001 From: kanym Date: Sun, 18 Oct 2026 00:09:14 +0200 Subject: [PATCH 043/163] fix(forms): hair comes back after a form with Valkyr Valkyr sets its hair's forceRenderingOff on every visual update. The hider read that flag as "not hidden yet", recorded the hair a second time with enabled already false, and the revert left it off. Track hidden renderers in a set instead of trusting the flag. --- JotunnModStub/PlayerVisualHider.cs | 20 +++++++++++++++++++- 1 file changed, 19 insertions(+), 1 deletion(-) diff --git a/JotunnModStub/PlayerVisualHider.cs b/JotunnModStub/PlayerVisualHider.cs index 6e753e5..d1cda5a 100644 --- a/JotunnModStub/PlayerVisualHider.cs +++ b/JotunnModStub/PlayerVisualHider.cs @@ -33,6 +33,11 @@ namespace RacesOfValheim } private readonly List m_hidden = new List(); + + // What we hid, kept apart from forceRenderingOff. Other mods write that flag too: Valkyr + // sets its hair's forceRenderingOff on every visual update, so the flag alone made the + // rescan record the hair a second time, already disabled, and the revert left it off. + private readonly HashSet m_tracked = new HashSet(); private float m_nextRescan; private float m_nextLog; private string m_context = ""; @@ -107,8 +112,20 @@ namespace RacesOfValheim // the cape along with the body mesh itself. foreach (Renderer r in GetComponentsInChildren(true)) { - if (r == null || r.forceRenderingOff) continue; // already ours + if (r == null) continue; + if (m_tracked.Contains(r)) + { + // Already ours: re-assert in case another mod cleared the flag. + r.forceRenderingOff = true; + continue; + } + + // Hidden by someone else (Valkyr hides the vanilla body and hair this way): leave + // it to them, or the revert would show it. + if (r.forceRenderingOff) continue; + + m_tracked.Add(r); m_hidden.Add(new HiddenRenderer { Renderer = r, WasEnabled = r.enabled }); r.enabled = false; r.forceRenderingOff = true; @@ -132,6 +149,7 @@ namespace RacesOfValheim } m_hidden.Clear(); + m_tracked.Clear(); enabled = false; return restored; } From 9d459fbc996da397b1474380e8c056fc62723d88 Mon Sep 17 00:00:00 2001 From: kanym Date: Sun, 18 Oct 2026 00:18:36 +0200 Subject: [PATCH 044/163] chore(release): v1.5.12 - hair back after a form with Valkyr With the Valkyr body replacer, leaving any monster form brought the body back without its hair. Fixed in PlayerVisualHider. README: New in block and changelog entry. --- JotunnModStub/Package/manifest.json | 2 +- JotunnModStub/RacesOfValheim.cs | 2 +- README.md | 7 +++++-- manifest.json | 2 +- 4 files changed, 8 insertions(+), 5 deletions(-) diff --git a/JotunnModStub/Package/manifest.json b/JotunnModStub/Package/manifest.json index 0c5a46e..6211ee9 100644 --- a/JotunnModStub/Package/manifest.json +++ b/JotunnModStub/Package/manifest.json @@ -1,7 +1,7 @@ { "name": "RacesOfValheim", "description": "A Valheim mod that adds ten custom playable races (Aswid, Draugh, Dvergar, Fenrir, Furling, Skadi, Skeleton, Sverm, Trenta, Trol) each with unique abilities, traits, race stations and a deep boss-driven progression system.", - "version_number": "1.5.11", + "version_number": "1.5.12", "website_url": "", "dependencies": [ "denikson-BepInExPack_Valheim-5.4.2333", diff --git a/JotunnModStub/RacesOfValheim.cs b/JotunnModStub/RacesOfValheim.cs index 2a6b881..2505de8 100644 --- a/JotunnModStub/RacesOfValheim.cs +++ b/JotunnModStub/RacesOfValheim.cs @@ -16,7 +16,7 @@ namespace RacesOfValheim { public const string PluginGUID = "com.nandor.racesofvalheim"; public const string PluginName = "Races Of Valheim"; - public const string PluginVersion = "1.5.11"; + public const string PluginVersion = "1.5.12"; private readonly Harmony harmony = new Harmony(PluginGUID); diff --git a/README.md b/README.md index ee6039c..0c572e8 100644 --- a/README.md +++ b/README.md @@ -15,9 +15,9 @@ Support the mod: [Patreon — NandorTheModder](https://www.patreon.com/c/NandorT --- -## New in v1.5.11 +## New in v1.5.12 -The Trol's True Form now wears Valheim's own forest troll, with its punches, ground slam and log swings; players with a model mod can keep the old True Form with `Trol - True Form` → `Legacy True Form`. The Sverm's Ravager attacks on the Seeker Brute's own animations: the ram lunges and the slam strikes with both claws. Race stations show and require their race in the build panel, and most of them now go on floors and inside caves. The Ulv sleeps when you sit. Full details in the [changelog](#v1511). +Compatibility fix for Valkyr (female body replacer): your hair no longer disappears when you leave a monster form. Full details in the [changelog](#v1512). --- @@ -450,6 +450,9 @@ Both halves have an off switch under `Factions` in Configuration Manager: **Fact ## Changelog +### v1.5.12 +- **Fix - hair gone after a form with Valkyr:** with the Valkyr body replacer, leaving a monster form (Skadi drake, Aswid bat or mist, Fenrir forms, Sverm Ravager, Trol True Form) brought the body back without its hair. Valkyr hides and shows its own hair, and the mod mistook that for a part it still had to hide, so it never turned the hair back on. Your hair now returns with the rest of the body. Thanks to BoredLizard for the report. + ### v1.5.11 - **New - Trol True Form wears a real troll:** True Form hides your Trol and puts Valheim's own forest troll in its place, as tall as the old True Form, in your Trol's skin colour. Every player sees it. Weapons are put away while it lasts: left click punches, right click slams the ground, and with a log in hand they become the troll's two log swings. The slam breaks trees and rocks around it and digs into the ground, never inside a ward you have no access to. Throw Rock plays the troll's own throw. You stand still through every attack. Damage is half a real troll's, scaled by your Clubs skill like a club, and the True Form and tier melee bonuses still add on top. New options under `Trol - True Form`: `Troll Model Size`, `Troll Attack Damage`, `Troll Attack Reach`, `Ground Slam Crater`. - **New - Legacy True Form:** prefer the old True Form, your own Trol grown bigger with weapons in hand? Turn on `Trol - True Form` → `Legacy True Form`. Use it with EnhancedValheimVRM or another player model mod, which needs the player's body to stay visible. Each player picks their own and other players see you the way you picked; a server cannot force it. Thanks to the players who answered the Discord poll. diff --git a/manifest.json b/manifest.json index 0c5a46e..6211ee9 100644 --- a/manifest.json +++ b/manifest.json @@ -1,7 +1,7 @@ { "name": "RacesOfValheim", "description": "A Valheim mod that adds ten custom playable races (Aswid, Draugh, Dvergar, Fenrir, Furling, Skadi, Skeleton, Sverm, Trenta, Trol) each with unique abilities, traits, race stations and a deep boss-driven progression system.", - "version_number": "1.5.11", + "version_number": "1.5.12", "website_url": "", "dependencies": [ "denikson-BepInExPack_Valheim-5.4.2333", From 6d9f07217e371d243e2a29bb79e3b3503627d496 Mon Sep 17 00:00:00 2001 From: kanym Date: Sun, 18 Oct 2026 13:33:21 +0200 Subject: [PATCH 045/163] fix(factions): no AI freeze when a targeted piece is destroyed FactionStaticTargetPatch read m_targetStatic as a boxed object, so the null check missed Unity's destroyed-object state. A piece destroyed while a mob targeted it passed the check, and reading its gameObject threw. The throw escaped into MonoUpdaters.FixedUpdate and stopped every AI after that mob, every frame, until the field changed. Cast to Component and use Unity's null check; clear a dead target. --- JotunnModStub/Factions/FactionHostilityPatch.cs | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/JotunnModStub/Factions/FactionHostilityPatch.cs b/JotunnModStub/Factions/FactionHostilityPatch.cs index b445dbe..7fee617 100644 --- a/JotunnModStub/Factions/FactionHostilityPatch.cs +++ b/JotunnModStub/Factions/FactionHostilityPatch.cs @@ -207,14 +207,23 @@ namespace RacesOfValheim { if (!FactionsConfig.Hostility) return; Traverse targetStatic = Traverse.Create(__instance).Field("m_targetStatic"); - if (targetStatic.GetValue() == null) return; + // GetValue() hands back a plain object, and object == null skips Unity's destroyed + // check: a piece smashed or removed while targeted stays non-null here, and touching + // its gameObject throws. That throw escapes into MonoUpdaters.FixedUpdate and stops + // every AI after this one for the frame, every frame, until the field changes. + Component target = targetStatic.GetValue() as Component; + if (target == null) + { + if (targetStatic.GetValue() != null) targetStatic.SetValue(null); + return; + } Character monster = Traverse.Create(__instance).Field("m_character").Value; if (monster == null) return; // A piece an allied race built is never a target, with or without anyone around. // See FactionPieceTruce. - if (targetStatic.GetValue() is Component target && FactionPieceTruce.Protects(target.gameObject, monster)) + if (FactionPieceTruce.Protects(target.gameObject, monster)) { targetStatic.SetValue(null); return; From 32c49a8af05e4199801abd245f955941d4a677bb Mon Sep 17 00:00:00 2001 From: kanym Date: Mon, 19 Oct 2026 14:20:28 +0200 Subject: [PATCH 046/163] fix(dvergar): build pieces accept the smithing discount The build menu showed the discounted metal cost, but Player.HaveRequirements(Piece) read m_amount directly, so placing a piece still needed the full vanilla amount. It now goes through GetAmount like the rest of the cost path. Piece.DropResources also read m_amount, which would have refunded 10 tin for a cauldron that cost 6. A piece placed by a Dvergar now stores the discount paid, and dismantling it drops that amount. --- JotunnModStub/Dvergar/DvergarPatches.cs | 144 +++++++++++++++++++++--- 1 file changed, 130 insertions(+), 14 deletions(-) diff --git a/JotunnModStub/Dvergar/DvergarPatches.cs b/JotunnModStub/Dvergar/DvergarPatches.cs index de75252..c29fdb0 100644 --- a/JotunnModStub/Dvergar/DvergarPatches.cs +++ b/JotunnModStub/Dvergar/DvergarPatches.cs @@ -1,5 +1,6 @@ using System.Collections.Generic; using System.Reflection; +using System.Reflection.Emit; using HarmonyLib; using UnityEngine; @@ -220,9 +221,13 @@ namespace RacesOfValheim // ─── Smithing and jewelry ──────────────────────────────────────────── /// - /// Metal saved when crafting and upgrading. Requirement.GetAmount is the single point both - /// the crafting panel and Player.ConsumeResources go through, so the figure the player is - /// quoted and the figure they are charged can never drift apart. + /// Metal saved when crafting, upgrading and building. Requirement.GetAmount is what the + /// crafting panel, the build menu and Player.ConsumeResources all read, so the figure the + /// player is quoted and the figure they are charged can never drift apart. + /// + /// Two vanilla paths read m_amount directly and skip GetAmount, both for build pieces: + /// Player.HaveRequirements(Piece) and Piece.DropResources. The two transpilers below route + /// them through the discount too. /// /// Scoped to the metals and gems in DvergarConfig.DiscountedResourceNames, which is what /// keeps this a smithing perk rather than a blanket discount on every wooden wall. @@ -232,26 +237,137 @@ namespace RacesOfValheim { public static void Postfix(Piece.Requirement __instance, ref int __result) { - if (__result <= 1 || Player.m_localPlayer == null) return; + if (Player.m_localPlayer == null) return; + if (!DvergarRace.IsDvergar()) return; + + __result = DiscountedAmount(__instance, __result, DvergarProgression.Current.SmithingDiscount); + } + } + + /// + /// The single rounding rule for the smithing discount. The price a Dvergar pays and the + /// refund their piece drops both go through here, so they can't end up one ingot apart. + /// + internal static int DiscountedAmount(Piece.Requirement requirement, int amount, float discount) + { + if (amount <= 1 || discount <= 0f) return amount; + if (requirement == null || requirement.m_resItem == null) return amount; + if (!IsDiscounted(requirement.m_resItem.gameObject.name)) return amount; + + return Mathf.Max(1, Mathf.RoundToInt(amount * (1f - discount))); + } + + private static bool IsDiscounted(string prefabName) + { + string lower = prefabName.ToLower(); + foreach (string resource in DvergarConfig.DiscountedResourceNames) + { + if (lower == resource || lower.Contains(resource)) return true; + } + return false; + } + + private static readonly FieldInfo RequirementAmountField = + AccessTools.Field(typeof(Piece.Requirement), nameof(Piece.Requirement.m_amount)); + + /// + /// The build check. Vanilla compares the inventory against requirement.m_amount here, so + /// the menu quoted 6 tin for a cauldron while the hammer still refused to place it with + /// fewer than 10. Every m_amount read becomes GetAmount(1), which returns m_amount for + /// everyone else and the discounted figure for a Dvergar. + /// + [HarmonyPatch(typeof(Player), nameof(Player.HaveRequirements), typeof(Piece), typeof(Player.RequirementMode))] + public static class Dvergar_HaveRequirements_Piece_Patch + { + private static readonly MethodInfo GetAmountMethod = + AccessTools.Method(typeof(Piece.Requirement), nameof(Piece.Requirement.GetAmount)); + + public static IEnumerable Transpiler(IEnumerable instructions) + { + int replaced = 0; + foreach (CodeInstruction instruction in instructions) + { + if (instruction.LoadsField(RequirementAmountField)) + { + replaced++; + yield return new CodeInstruction(OpCodes.Ldc_I4_1).MoveLabelsFrom(instruction); + yield return new CodeInstruction(OpCodes.Callvirt, GetAmountMethod); + continue; + } + yield return instruction; + } + if (replaced == 0) + Jotunn.Logger.LogWarning("[Dvergar] HaveRequirements(Piece) no longer reads m_amount; build discount check not patched."); + } + } + + /// + /// ZDO key holding the discount a Dvergar paid for a piece. Stored rather than read off + /// the builder at teardown, because anyone can smash the piece and the builder's discount + /// grows with progression. + /// + private const string PaidDiscountKey = "Dvergar_PaidDiscount"; + + /// + /// Stamps the discount on a piece the local Dvergar just placed. Player.PlacePiece calls + /// SetCreator on the new instance right after spawning it, and ConsumeResources charges + /// the discounted price straight after. + /// + [HarmonyPatch(typeof(Piece), nameof(Piece.SetCreator))] + public static class Dvergar_Piece_SetCreator_Patch + { + public static void Postfix(Piece __instance, long uid) + { + Player player = Player.m_localPlayer; + if (player == null || uid != player.GetPlayerID()) return; if (!DvergarRace.IsDvergar()) return; float discount = DvergarProgression.Current.SmithingDiscount; if (discount <= 0f) return; - if (__instance == null || __instance.m_resItem == null) return; - if (!IsDiscounted(__instance.m_resItem.gameObject.name)) return; + ZNetView nview = __instance.GetComponent(); + if (nview == null || !nview.IsValid() || !nview.IsOwner()) return; + nview.GetZDO().Set(PaidDiscountKey, discount); + } + } - __result = Mathf.Max(1, Mathf.RoundToInt(__result * (1f - discount))); + /// + /// The refund. Vanilla drops requirement.m_amount when a piece is removed or destroyed, + /// which handed a Dvergar back 10 tin for a cauldron that cost 6: build, smash, repeat. + /// The drop now uses the discount stamped on the piece, so it returns what was paid. + /// + [HarmonyPatch(typeof(Piece), nameof(Piece.DropResources))] + public static class Dvergar_Piece_DropResources_Patch + { + private static readonly MethodInfo PaidAmountMethod = + AccessTools.Method(typeof(Dvergar_Piece_DropResources_Patch), nameof(PaidAmount)); + + public static IEnumerable Transpiler(IEnumerable instructions) + { + int replaced = 0; + foreach (CodeInstruction instruction in instructions) + { + if (instruction.LoadsField(RequirementAmountField)) + { + replaced++; + yield return new CodeInstruction(OpCodes.Ldarg_0).MoveLabelsFrom(instruction); + yield return new CodeInstruction(OpCodes.Call, PaidAmountMethod); + continue; + } + yield return instruction; + } + if (replaced == 0) + Jotunn.Logger.LogWarning("[Dvergar] DropResources no longer reads m_amount; build discount refund not patched."); } - private static bool IsDiscounted(string prefabName) + public static int PaidAmount(Piece.Requirement requirement, Piece piece) { - string lower = prefabName.ToLower(); - foreach (string resource in DvergarConfig.DiscountedResourceNames) - { - if (lower == resource || lower.Contains(resource)) return true; - } - return false; + int amount = requirement.m_amount; + ZNetView nview = piece.GetComponent(); + if (nview == null || !nview.IsValid()) return amount; + + float discount = nview.GetZDO().GetFloat(PaidDiscountKey, 0f); + return DiscountedAmount(requirement, amount, discount); } } From 9dd6600287c029ff2a993046f2b73aacfaedc5ab Mon Sep 17 00:00:00 2001 From: kanym Date: Mon, 19 Oct 2026 14:30:35 +0200 Subject: [PATCH 047/163] chore(release): v1.5.13 - no faction AI freeze, Dvergar build discount With factions on, destroying a piece a mob was targeting froze every AI in the area on servers. Dvergar pieces now build at the discounted metal cost the menu shows, and refund what was paid. README: New in block and changelog entry. Compendium: the Dvergar smithing discount also covers building, in English, Italian and Russian. --- JotunnModStub/Package/manifest.json | 2 +- JotunnModStub/RacesOfValheim.cs | 2 +- JotunnModStub/Translations/English/compendium.json | 2 +- JotunnModStub/Translations/Italian/compendium.json | 2 +- JotunnModStub/Translations/Russian/compendium.json | 2 +- README.md | 8 ++++++-- manifest.json | 2 +- 7 files changed, 12 insertions(+), 8 deletions(-) diff --git a/JotunnModStub/Package/manifest.json b/JotunnModStub/Package/manifest.json index 6211ee9..8b1a0cf 100644 --- a/JotunnModStub/Package/manifest.json +++ b/JotunnModStub/Package/manifest.json @@ -1,7 +1,7 @@ { "name": "RacesOfValheim", "description": "A Valheim mod that adds ten custom playable races (Aswid, Draugh, Dvergar, Fenrir, Furling, Skadi, Skeleton, Sverm, Trenta, Trol) each with unique abilities, traits, race stations and a deep boss-driven progression system.", - "version_number": "1.5.12", + "version_number": "1.5.13", "website_url": "", "dependencies": [ "denikson-BepInExPack_Valheim-5.4.2333", diff --git a/JotunnModStub/RacesOfValheim.cs b/JotunnModStub/RacesOfValheim.cs index 2505de8..1bd1c2b 100644 --- a/JotunnModStub/RacesOfValheim.cs +++ b/JotunnModStub/RacesOfValheim.cs @@ -16,7 +16,7 @@ namespace RacesOfValheim { public const string PluginGUID = "com.nandor.racesofvalheim"; public const string PluginName = "Races Of Valheim"; - public const string PluginVersion = "1.5.12"; + public const string PluginVersion = "1.5.13"; private readonly Harmony harmony = new Harmony(PluginGUID); diff --git a/JotunnModStub/Translations/English/compendium.json b/JotunnModStub/Translations/English/compendium.json index 0b27389..96d652b 100644 --- a/JotunnModStub/Translations/English/compendium.json +++ b/JotunnModStub/Translations/English/compendium.json @@ -41,7 +41,7 @@ "rov_compendium_dvergar_runic_ping_key_spend_eitr": "[Yagluth Unlock] Runic Ping ('$1' Key): Spend $2 eitr to send a pulse through the stone. For $3 seconds every ore vein and every hidden enemy within $4 meters is lit for you alone.\n", "rov_compendium_dvergar_runic_spark_runes_blood_earth": "[Base Passive] Runic Spark: The runes in your blood earth themselves through whatever you strike. Every blow you land carries +$1 Lightning damage - a bonus that grows as each boss falls.\n", "rov_compendium_dvergar_small_stubborn_stand_shorter_than": "[Base Passive] Small and Stubborn: You stand $1% shorter than a human and carry $2 less health for it. The dvergr hood never leaves your head - wear whatever helm you please and keep every point of its protection, but the runes will always show you as one of the deep folk.\n", - "rov_compendium_dvergar_smithing_jewelry_passive_waste_nothing": "[Bonemass Unlock] Smithing and Jewelry (Passive): You waste nothing at the anvil. Metal and gems cost you $1% less when crafting and upgrading.\n", + "rov_compendium_dvergar_smithing_jewelry_passive_waste_nothing": "[Bonemass Unlock] Smithing and Jewelry (Passive): You waste nothing at the anvil. Metal and gems cost you $1% less when crafting, upgrading and building.\n", "rov_compendium_dvergar_title": "Dvergar Secrets", "rov_compendium_dvergar_weapon_affinity_passive_blows_struck": "Weapon Affinity (Passive): $1. Blows struck with these land harder and cost less stamina. The saving never grows - a tier only ever hands you another weapon to feel at home with - and your skill rises no faster than anyone else's.\n", "rov_compendium_dvergar_weapon_axe": "Axe", diff --git a/JotunnModStub/Translations/Italian/compendium.json b/JotunnModStub/Translations/Italian/compendium.json index c1c5a56..c761af4 100644 --- a/JotunnModStub/Translations/Italian/compendium.json +++ b/JotunnModStub/Translations/Italian/compendium.json @@ -41,7 +41,7 @@ "rov_compendium_dvergar_runic_ping_key_spend_eitr": "[Sblocco Yagluth] Richiamo runico (tasto '$1'): spendi $2 di eitr per mandare un impulso attraverso la pietra. Per $3 secondi ogni vena di minerale e ogni nemico nascosto entro $4 metri si illumina, solo per te.\n", "rov_compendium_dvergar_runic_spark_runes_blood_earth": "[Passiva base] Scintilla runica: le rune nel tuo sangue si scaricano a terra attraverso ciò che colpisci. Ogni colpo che metti a segno porta +$1 danni da fulmine, un bonus che cresce con la caduta di ogni boss.\n", "rov_compendium_dvergar_small_stubborn_stand_shorter_than": "[Passiva base] Piccolo e testardo: sei il $1% più basso di un umano e per questo hai $2 di salute in meno. Il cappuccio dvergr non ti lascia mai la testa: indossa l'elmo che vuoi e mantieni ogni punto della sua protezione, ma le rune ti mostreranno sempre come uno del popolo del profondo.\n", - "rov_compendium_dvergar_smithing_jewelry_passive_waste_nothing": "[Sblocco Massa d'ossa] Forgia e gioielleria (passiva): all'incudine non sprechi niente. Metalli e gemme ti costano il $1% in meno quando crei e migliori oggetti.\n", + "rov_compendium_dvergar_smithing_jewelry_passive_waste_nothing": "[Sblocco Massa d'ossa] Forgia e gioielleria (passiva): all'incudine non sprechi niente. Metalli e gemme ti costano il $1% in meno quando crei, migliori oggetti e costruisci.\n", "rov_compendium_dvergar_title": "Segreti dei Dvergar", "rov_compendium_dvergar_weapon_affinity_passive_blows_struck": "Affinità con le armi (passiva): $1. I colpi inferti con queste armi arrivano più forti e costano meno stamina. Il risparmio non cresce mai: un tier ti dà solo un'altra arma con cui sentirti a casa, e la tua abilità non sale più in fretta di quella di chiunque altro.\n", "rov_compendium_dvergar_weapon_axe": "Ascia", diff --git a/JotunnModStub/Translations/Russian/compendium.json b/JotunnModStub/Translations/Russian/compendium.json index 6464233..6f11d10 100644 --- a/JotunnModStub/Translations/Russian/compendium.json +++ b/JotunnModStub/Translations/Russian/compendium.json @@ -41,7 +41,7 @@ "rov_compendium_dvergar_runic_ping_key_spend_eitr": "[Награда: Яглут] Рунический эхолокатор (клавиша «$1»): Потратьте $2 эйтра, чтобы послать импульс сквозь толщу камня. На $3 с каждая рудная жила и каждый скрытый враг в радиусе $4 метров подсветятся только для вас.\n", "rov_compendium_dvergar_runic_spark_runes_blood_earth": "[Базовое пассивное] Руническая искра: Руны в вашей крови заземляются через каждую цель, по которой вы бьете. Каждый нанесенный удар несет +$1 урона молнией — этот бонус растет по мере гибели боссов.\n", "rov_compendium_dvergar_small_stubborn_stand_shorter_than": "[Базовое пассивное] Мал да удал: Вы на $1% ниже человека и обладаете базовым запасом здоровья на $2 ед. меньше. Капюшон дверга сросся с вами навечно — надевайте любой шлем и сохраняйте все его показатели защиты, но руны всегда будут выдавать в вас дитя глубин.\n", - "rov_compendium_dvergar_smithing_jewelry_passive_waste_nothing": "[Награда: Масса костей] Кузнечное и ювелирное дело (Пассивное): В вашей наковальне ни крупицы не пропадет даром. Металлы и самоцветы тратятся на $1% экономнее при создании и улучшении предметов.\n", + "rov_compendium_dvergar_smithing_jewelry_passive_waste_nothing": "[Награда: Масса костей] Кузнечное и ювелирное дело (Пассивное): В вашей наковальне ни крупицы не пропадет даром. Металлы и самоцветы тратятся на $1% экономнее при создании и улучшении предметов, а также при строительстве.\n", "rov_compendium_dvergar_title": "Тайны Дверга", "rov_compendium_dvergar_weapon_affinity_passive_blows_struck": "Владение оружием (Пассивное): $1. Удары этим оружием бьют сильнее и расходуют меньше выносливости. Экономия выносливости не увеличивается — открытие уровней лишь расширяет список доступного вам родного оружия, а сам навык растет с обычной скоростью.\n", "rov_compendium_dvergar_weapon_axe": "Топор", diff --git a/README.md b/README.md index 0c572e8..8c1b542 100644 --- a/README.md +++ b/README.md @@ -15,9 +15,9 @@ Support the mod: [Patreon — NandorTheModder](https://www.patreon.com/c/NandorT --- -## New in v1.5.12 +## New in v1.5.13 -Compatibility fix for Valkyr (female body replacer): your hair no longer disappears when you leave a monster form. Full details in the [changelog](#v1512). +Fixes a freeze on servers with factions on: when a building a mob was attacking got destroyed, every creature in the area stopped moving and players slid on the ground. Dvergar now pay the discounted metal cost the build menu shows. Full details in the [changelog](#v1513). --- @@ -450,6 +450,10 @@ Both halves have an off switch under `Factions` in Configuration Manager: **Fact ## Changelog +### v1.5.13 +- **Fix - world freezes with factions on:** since v1.5.11, if a mob was targeting a building piece and the piece got destroyed or removed, the faction check threw an error every frame. On a server this stopped the AI of every creature in the area: players slid on the ground, enemies stood still, and characters sometimes turned invisible. The check now drops the dead target and moves on. Thanks to SCRIMSHAW and GaoVN for the reports, and to SCRIMSHAW for testing the fix on their server. +- **Fix - Dvergar build discount:** the build menu showed the discounted metal cost (a cauldron for 6 tin instead of 10), but the hammer still refused to place the piece unless you carried the full vanilla amount. Pieces now build at the price shown. Dismantling or destroying a piece a Dvergar built returns the metal they paid, not the vanilla amount. Thanks to Balmarog for the report. + ### v1.5.12 - **Fix - hair gone after a form with Valkyr:** with the Valkyr body replacer, leaving a monster form (Skadi drake, Aswid bat or mist, Fenrir forms, Sverm Ravager, Trol True Form) brought the body back without its hair. Valkyr hides and shows its own hair, and the mod mistook that for a part it still had to hide, so it never turned the hair back on. Your hair now returns with the rest of the body. Thanks to BoredLizard for the report. diff --git a/manifest.json b/manifest.json index 6211ee9..8b1a0cf 100644 --- a/manifest.json +++ b/manifest.json @@ -1,7 +1,7 @@ { "name": "RacesOfValheim", "description": "A Valheim mod that adds ten custom playable races (Aswid, Draugh, Dvergar, Fenrir, Furling, Skadi, Skeleton, Sverm, Trenta, Trol) each with unique abilities, traits, race stations and a deep boss-driven progression system.", - "version_number": "1.5.12", + "version_number": "1.5.13", "website_url": "", "dependencies": [ "denikson-BepInExPack_Valheim-5.4.2333", From 691ccc211b666b76dfa2d7af8665d56defc7fe14 Mon Sep 17 00:00:00 2001 From: kanym Date: Tue, 20 Oct 2026 03:17:08 +0200 Subject: [PATCH 048/163] fix(visuals): a resized player's weapon hits as far as it is drawn Attack.DoMeleeAttack and DoAreaAttack measure range and ray width from the unscaled root, so a Legacy True Form Trol at 2.5 still hit at a human's 2 m while the drawn mace reached five. Both now grow by the Visual's world scale (never below 1), the factor HeldItemScaleFix sizes the weapon by. Height stays at the feet so a flat swing does not pass over small enemies. F8 toggles an in-game readout of the stretched numbers and what a cast straight ahead passes through. --- JotunnModStub/RaceMeleeReach.cs | 129 ++++++++++++++++++++++++++++++++ 1 file changed, 129 insertions(+) create mode 100644 JotunnModStub/RaceMeleeReach.cs diff --git a/JotunnModStub/RaceMeleeReach.cs b/JotunnModStub/RaceMeleeReach.cs new file mode 100644 index 0000000..4b2d66b --- /dev/null +++ b/JotunnModStub/RaceMeleeReach.cs @@ -0,0 +1,129 @@ +using System.Collections.Generic; +using HarmonyLib; +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// Makes a resized player's weapon hit as far as the weapon is drawn. + /// + /// Vanilla's melee check (Attack.DoMeleeAttack) fans sphere casts out from the player's ROOT, + /// m_attackHeight above the feet and m_attackRange long, and none of those numbers know the + /// model was resized. Races resize the "Visual" child, never the root (see RaceEyeHeight), so a + /// Legacy True Form Trol at 2.5 swung a mace whose head landed five metres out while the hit + /// still stopped at a human's 2 m. Testers saw it as "hits the first few, then 50/50": the + /// targets close in were inside the human reach, the rest only stood under the drawn weapon. + /// The area attack (sledges, DoAreaAttack) has the same blind spot: its sphere sits a human's + /// range ahead with a human's radius. + /// + /// Range and ray width grow by the model's size, the world scale of the Visual - the same factor + /// HeldItemScaleFix sizes the weapon by, so the hit follows the weapon through tiers, True Form + /// and the grow animation. Never below 1: a Furling or a Dvergar keeps the vanilla reach, for + /// the same reason RaceEyeHeight never shrinks the interact range. + /// + /// The height is left alone on purpose. A horizontal swing is one flat fan at that height, and + /// raised to 2.5 m it passed clean over a Greydwarf's head. Kept at the feet, the wider sphere + /// still covers from the ground to above a human's head, and a troll stands up into it anyway. + /// + /// The troll-model True Form does not swing weapons at all (TrolTrueFormBehavior does its own + /// hits), and a player inside a borrowed form keeps the Visual at 1, so both read as 1 here. + /// Fields are put back in a finalizer: the Attack is a clone per swing, but a throw halfway + /// through must not leave a stretched one behind for the next hit of a chain. + /// + [HarmonyPatch] + internal static class RaceMeleeReach + { + private struct Saved + { + public bool Active; + public float Range; + public float RayWidth; + public float RayWidthCharExtra; + } + + private static IEnumerable TargetMethods() + { + yield return AccessTools.Method(typeof(Attack), "DoMeleeAttack"); + yield return AccessTools.Method(typeof(Attack), "DoAreaAttack"); + } + + private static void Prefix(Attack __instance, Humanoid ___m_character, out Saved __state) + { + __state = default; + if (!(___m_character is Player player)) return; + + float scale = ModelScale(player); + if (scale <= 1.001f) return; + + __state = new Saved + { + Active = true, + Range = __instance.m_attackRange, + RayWidth = __instance.m_attackRayWidth, + RayWidthCharExtra = __instance.m_attackRayWidthCharExtra + }; + __instance.m_attackRange *= scale; + __instance.m_attackRayWidth *= scale; + __instance.m_attackRayWidthCharExtra *= scale; + + if (DebugOn && player == Player.m_localPlayer) Report(__instance, player, scale, __state); + } + + private static void Finalizer(Attack __instance, Saved __state) + { + if (!__state.Active) return; + __instance.m_attackRange = __state.Range; + __instance.m_attackRayWidth = __state.RayWidth; + __instance.m_attackRayWidthCharExtra = __state.RayWidthCharExtra; + } + + private static float ModelScale(Player player) + { + GameObject visual = Traverse.Create(player).Field("m_visual").GetValue(); + if (visual == null) return 1f; + return Mathf.Max(1f, visual.transform.lossyScale.y); + } + + // ---- F8 debug: what the stretched swing reaches, read in game ---- + + internal static bool DebugOn; + + /// One sphere cast straight ahead with the stretched numbers, listing every + /// character it passes through and how far out, next to the vanilla range it replaced. + private static void Report(Attack attack, Player player, float scale, Saved before) + { + Vector3 origin = player.transform.position + Vector3.up * attack.m_attackHeight; + Vector3 dir = player.transform.forward; + float width = Mathf.Max(0.05f, attack.m_attackRayWidth); + RaycastHit[] hits = Physics.SphereCastAll(origin, width, dir, Mathf.Max(0f, attack.m_attackRange - width), + LayerMask.GetMask("character", "character_net", "character_ghost", "hitbox", "character_noenv"), + QueryTriggerInteraction.Ignore); + + var names = new List(); + foreach (RaycastHit hit in hits) + { + GameObject go = Projectile.FindHitObject(hit.collider); + if (go == null || go == player.gameObject) continue; + names.Add($"{go.name.Replace("(Clone)", "")} {hit.distance:0.0}m"); + } + + string line = $"[RoV reach] x{scale:0.00} {attack.m_attackType} range {before.Range:0.0}->{attack.m_attackRange:0.0} " + + $"width {before.RayWidth:0.00}->{attack.m_attackRayWidth:0.00} height {attack.m_attackHeight:0.0} | " + + (names.Count > 0 ? string.Join(", ", names) : "no character ahead"); + Debug.Log(line); + player.Message(MessageHud.MessageType.TopLeft, line); + } + } + + /// F8 turns the reach readout on and off. + [HarmonyPatch(typeof(Player), "Update")] + internal static class RaceMeleeReachDebugKey + { + private static void Postfix(Player __instance) + { + if (__instance != Player.m_localPlayer || !Input.GetKeyDown(KeyCode.F8)) return; + RaceMeleeReach.DebugOn = !RaceMeleeReach.DebugOn; + __instance.Message(MessageHud.MessageType.TopLeft, $"[RoV reach] debug {(RaceMeleeReach.DebugOn ? "on" : "off")}"); + } + } +} From 95c8a7b1b621dbf447df1d87ff3ac64e26589128 Mon Sep 17 00:00:00 2001 From: kanym Date: Fri, 23 Oct 2026 19:03:58 +0200 Subject: [PATCH 049/163] fix(furling): other players see a Furling at Furling size The 0.81 scale was applied from a Player.Update postfix that returned for anyone but the local player and read the race from the local m_customData. Scale is not replicated, so a Furling was small only on their own screen. The postfix now sizes every player, with the race read off the ZDO the way the Dvergar and the Trol already do it. --- JotunnModStub/Furling/FurlingPatches.cs | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/JotunnModStub/Furling/FurlingPatches.cs b/JotunnModStub/Furling/FurlingPatches.cs index 01bb0d3..7efb827 100644 --- a/JotunnModStub/Furling/FurlingPatches.cs +++ b/JotunnModStub/Furling/FurlingPatches.cs @@ -11,9 +11,13 @@ namespace RacesOfValheim { public static void Postfix(Player __instance) { - if (__instance == null || __instance != Player.m_localPlayer) return; - - if (FurlingRace.IsFurling()) + if (__instance == null) return; + + // Every player, not only the local one, with the race read off the ZDO. Scale is not + // replicated: each client sizes the characters it draws. When this sized only the + // local player from its own m_customData, a Furling was small on their own screen + // and full height on everybody else's. + if (DvergarVisuals.GetPlayerRace(__instance) == "Furling") { // Scale player visuals down by 19% (0.9 * 0.9 = 0.81) GameObject visual = Traverse.Create(__instance).Field("m_visual").GetValue(); From eba537fa0739d1cd7429b7ca56d33a1f5a519ba0 Mon Sep 17 00:00:00 2001 From: kanym Date: Fri, 23 Oct 2026 19:18:53 +0200 Subject: [PATCH 050/163] fix(food): race foods replace a worn-down meal when the stomach is full Trenta seeds, Draugh raw flesh and Aswid meals each go through an EatFood prefix that, with three slots full and none holding the same food, answered false. Vanilla would replace the most depleted meal past half its time. The UseItem callers also never showed why: EatFood says nothing on a refusal, so the click did nothing at all. That is the Reddit report of a Trenta who could not eat any seeds. The prefixes now hand that case to native EatFood, the Aswid's CanConsumeItem postfix keeps vanilla's answer instead of forcing false, and the Trenta and Draugh callers ask CanEat(item, true) for vanilla's own message when a meal is refused. --- JotunnModStub/Aswid/AswidPatches.cs | 19 ++++++++----------- JotunnModStub/Draugh/DraughFoodPatches.cs | 12 +++++++++--- JotunnModStub/Trenta/TrentaFoodPatches.cs | 13 +++++++++++-- 3 files changed, 28 insertions(+), 16 deletions(-) diff --git a/JotunnModStub/Aswid/AswidPatches.cs b/JotunnModStub/Aswid/AswidPatches.cs index 6931d80..6e1609e 100644 --- a/JotunnModStub/Aswid/AswidPatches.cs +++ b/JotunnModStub/Aswid/AswidPatches.cs @@ -341,14 +341,11 @@ namespace RacesOfValheim } } - if (canRefresh) - { - __result = true; - } - else - { - __result = false; // Nessuno spazio disponibile, cibo si disintegra - } + // Otherwise vanilla's answer stands: it already allows replacing the + // most depleted meal past half its time, and already showed its "too + // full" message when it refused. Forcing false here used to block + // that replacement, silently. + if (canRefresh) __result = true; } } else @@ -426,9 +423,9 @@ namespace RacesOfValheim return false; } - // Se pieno e senza 4° slot disponibile, fallisce e disintegra - __result = false; - return false; + // Full, no fourth slot free, no slot holding this meal. Native EatFood + // replaces the most depleted meal past half its time, or refuses. + return true; } else { diff --git a/JotunnModStub/Draugh/DraughFoodPatches.cs b/JotunnModStub/Draugh/DraughFoodPatches.cs index f4a9ce2..ea56d5c 100644 --- a/JotunnModStub/Draugh/DraughFoodPatches.cs +++ b/JotunnModStub/Draugh/DraughFoodPatches.cs @@ -90,6 +90,11 @@ namespace RacesOfValheim var zanim = Traverse.Create(player).Field("m_zanim").GetValue(); if (zanim != null) zanim.SetTrigger("eat"); } + else + { + // Vanilla's refusal message, which EatFood never shows by itself + player.CanEat(customItemDrop.m_itemData, true); + } return false; // Skip native UseItem } } @@ -154,9 +159,10 @@ namespace RacesOfValheim return false; // Skip native EatFood } - // Inventory full - __result = false; - return false; + // Full, and no slot holds this flesh. Native EatFood replaces the most + // depleted meal past half its time, or refuses - vanilla's own rule. This + // used to refuse outright, with no message. + return true; } else { diff --git a/JotunnModStub/Trenta/TrentaFoodPatches.cs b/JotunnModStub/Trenta/TrentaFoodPatches.cs index bc17d19..43bd5c5 100644 --- a/JotunnModStub/Trenta/TrentaFoodPatches.cs +++ b/JotunnModStub/Trenta/TrentaFoodPatches.cs @@ -71,6 +71,12 @@ namespace RacesOfValheim var zanim = Traverse.Create(player).Field("m_zanim").GetValue(); if (zanim != null) zanim.SetTrigger("eat"); } + else + { + // Vanilla's "can't eat more" / "too full" message, from vanilla's own + // check. EatFood itself never says why it refused. + player.CanEat(customDrop.m_itemData, true); + } return false; // Skip native UseItem either way } @@ -172,8 +178,11 @@ namespace RacesOfValheim } } - __result = false; // Full, and nothing in it worth topping up: the seed stays. - return false; + // Full, and no slot holds this seed. Native EatFood takes it from here with + // vanilla's own rule: it replaces the most depleted meal past half its time, + // or refuses. This used to refuse outright, so a Trenta with three meals going + // could not eat a seed at all, and saw no message saying why. + return true; } // Temporarily hide any existing slot with the same name to force native EatFood From f1597dd6462a7049753643929b769dbba13eca04 Mon Sep 17 00:00:00 2001 From: kanym Date: Fri, 23 Oct 2026 19:22:31 +0200 Subject: [PATCH 051/163] fix(hud): the stamina bar comes back after leaving the Aswid or the Draugh Both races hide the stamina bar root from a Hud.UpdateStamina prefix. Vanilla activates that root once, when the HUD is built, so after a race change the bar stayed hidden until relog. The prefix now switches it back on for every other race. --- JotunnModStub/Aswid/AswidPatches.cs | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/JotunnModStub/Aswid/AswidPatches.cs b/JotunnModStub/Aswid/AswidPatches.cs index 6931d80..58ea170 100644 --- a/JotunnModStub/Aswid/AswidPatches.cs +++ b/JotunnModStub/Aswid/AswidPatches.cs @@ -508,6 +508,14 @@ namespace RacesOfValheim } return false; } + + // Vanilla switches the bar on once, when the HUD is built, and never again. Without + // this a player who left the Aswid or the Draugh had no stamina bar until relog. + if (player == Player.m_localPlayer && __instance.m_staminaBar2Root != null + && !__instance.m_staminaBar2Root.gameObject.activeSelf) + { + __instance.m_staminaBar2Root.gameObject.SetActive(true); + } return true; } } From d1f328a496c5e84b968df63d755114149fdc2027 Mon Sep 17 00:00:00 2001 From: kanym Date: Fri, 23 Oct 2026 19:33:00 +0200 Subject: [PATCH 052/163] feat(fenrir): eyes glow at night, bright when a form is ready A community suggestion: an indicator on the character instead of the "
is Ready!" text. FenrirVisuals borrows the Skeleton's eye_l and eye_r the way AswidVisuals does, with the Aswid's playtested placement, and tints them with the Fenring's own emission colour (2.0, 0.372, 0), read from bundle c4210710. Dark by day and in a beast form. At night they glow faintly, and brightly while one of the three keys would transform. That uses the same gates as TryTransformWithRules: tier, night, sun sickness, cooldown. The owner writes it to the ZDO only on a change, so remote players see the same. New local section "Fenrir - Appearance": Ready Message (on by default), Eye Glow, and the night and ready strengths. --- JotunnModStub/ConfigSync.cs | 1 + JotunnModStub/Fenrir/FenrirConfig.cs | 17 ++ JotunnModStub/Fenrir/FenrirRace.cs | 29 +++ JotunnModStub/Fenrir/FenrirStatusEffects.cs | 2 +- JotunnModStub/Fenrir/FenrirVisuals.cs | 256 ++++++++++++++++++++ 5 files changed, 304 insertions(+), 1 deletion(-) create mode 100644 JotunnModStub/Fenrir/FenrirVisuals.cs diff --git a/JotunnModStub/ConfigSync.cs b/JotunnModStub/ConfigSync.cs index f743b4c..0281af6 100644 --- a/JotunnModStub/ConfigSync.cs +++ b/JotunnModStub/ConfigSync.cs @@ -28,6 +28,7 @@ namespace RacesOfValheim { "Aswid - Claws", "Aswid - Eyes", + "Fenrir - Appearance", "Skeleton - Visuals", "Sverm - Dorsal Spines", "Sverm - Emberform", diff --git a/JotunnModStub/Fenrir/FenrirConfig.cs b/JotunnModStub/Fenrir/FenrirConfig.cs index 74795e5..68e9a97 100644 --- a/JotunnModStub/Fenrir/FenrirConfig.cs +++ b/JotunnModStub/Fenrir/FenrirConfig.cs @@ -85,6 +85,12 @@ namespace RacesOfValheim // ─── Debug ───────────────────────────────────────────────────────────── public static ConfigEntry DebugFormHits; + // ─── Appearance (per player, never synced) ────────────────────────────── + public static ConfigEntry ReadyMessage; + public static ConfigEntry EyeGlow; + public static ConfigEntry EyeNightStrength; + public static ConfigEntry EyeReadyStrength; + public static void Bind(ConfigFile config) { const string keybinds = "Fenrir - Keybinds"; @@ -188,6 +194,17 @@ namespace RacesOfValheim UlvPushForce = config.Bind(ulv, "Push Force", 25f, new ConfigDescription("Knockback applied on a hit.", new AcceptableValueRange(0f, 100f))); + // The whole section stays local - see ConfigSync.LocalSections. + const string appearance = "Fenrir - Appearance"; + ReadyMessage = config.Bind(appearance, "Ready Message", true, + new ConfigDescription("Shows \" is Ready!\" when a form's cooldown ends. The eyes say the same thing; turn this off if they are enough.")); + EyeGlow = config.Bind(appearance, "Eye Glow", true, + new ConfigDescription("Fenrir eyes glow at night in the Fenring's own orange: faint while no form can be taken, bright when one can. Off hides them on every Fenrir you see.")); + EyeNightStrength = config.Bind(appearance, "Eye Night Strength", 0.35f, + new ConfigDescription("Glow at night while no form is ready.", new AcceptableValueRange(0f, 3f))); + EyeReadyStrength = config.Bind(appearance, "Eye Ready Strength", 1.2f, + new ConfigDescription("Glow at night while a form is ready.", new AcceptableValueRange(0f, 3f))); + // "debug" in the key keeps it local - see ConfigSync. DebugFormHits = config.Bind("Fenrir - Debug", "Debug: Log Form Hits", false, new ConfigDescription("Writes one log line per claw or bite: what was in reach, what it hit, and why anything was skipped. For bug reports about attacks that do no damage.")); diff --git a/JotunnModStub/Fenrir/FenrirRace.cs b/JotunnModStub/Fenrir/FenrirRace.cs index 655cb86..9feeb51 100644 --- a/JotunnModStub/Fenrir/FenrirRace.cs +++ b/JotunnModStub/Fenrir/FenrirRace.cs @@ -150,6 +150,8 @@ namespace RacesOfValheim { } wasNight = isNight; + FenrirVisuals.SetReady(Player.m_localPlayer, CanTakeAnyForm()); + if (isTransformed) { bool hasAnyForm = Player.m_localPlayer.GetSEMan().HaveStatusEffect("SE_FenrirForm".GetStableHashCode()) || @@ -171,6 +173,33 @@ namespace RacesOfValheim { if (FenrirConfig.CultistFormKey.Value.IsDownIgnoringHeldKeys()) { TryTransformWithRules(FenrirProgression.GetJKeyRules(state)); return; } } + /// + /// Whether one of the three keys would transform right now. The same gates as + /// TryTransformWithRules below, without its messages: this feeds the eye glow. + /// + private bool CanTakeAnyForm() + { + if (isTransformed) return false; + + int state = BossProgressionManager.GetCurrentProgressionState(); + return CanTake(FenrirProgression.GetGKeyRules(state)) + || CanTake(FenrirProgression.GetHKeyRules(state)) + || CanTake(FenrirProgression.GetJKeyRules(state)); + } + + private bool CanTake(FenrirProgression.FormRules rules) + { + if (rules == null || rules.Form == FenrirProgression.FormType.None) return false; + if (rules.NeedsNight && (sunSicknessTimer > 0f || !EnvMan.IsNight())) return false; + + if (rules.CooldownMinutes > 0) + { + string cdName = rules.Form == FenrirProgression.FormType.Cultist ? "SE_CultistCooldown" : "SE_FenrirCooldown"; + if (Player.m_localPlayer.GetSEMan().HaveStatusEffect(cdName.GetStableHashCode())) return false; + } + return true; + } + private void TryTransformWithRules(FenrirProgression.FormRules rules) { if (rules == null || rules.Form == FenrirProgression.FormType.None) return; diff --git a/JotunnModStub/Fenrir/FenrirStatusEffects.cs b/JotunnModStub/Fenrir/FenrirStatusEffects.cs index 43de139..f08ae33 100644 --- a/JotunnModStub/Fenrir/FenrirStatusEffects.cs +++ b/JotunnModStub/Fenrir/FenrirStatusEffects.cs @@ -15,7 +15,7 @@ namespace RacesOfValheim public override void Stop() { base.Stop(); - if (Player.m_localPlayer != null) + if (Player.m_localPlayer != null && FenrirConfig.ReadyMessage.Value) { Player.m_localPlayer.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_fenrir_ready", m_name)); } diff --git a/JotunnModStub/Fenrir/FenrirVisuals.cs b/JotunnModStub/Fenrir/FenrirVisuals.cs new file mode 100644 index 0000000..7b901c0 --- /dev/null +++ b/JotunnModStub/Fenrir/FenrirVisuals.cs @@ -0,0 +1,256 @@ +using System.Collections.Generic; +using HarmonyLib; +using Jotunn.Managers; +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// The Fenrir's eyes catch the light at night, the way a wolf's do: a faint glow while no form + /// can be taken, a bright one when a key would transform right now. Dark by day and while in a + /// beast form, whose own eyes take over. A community suggestion (lexsonn), meant to say what + /// the "Ready!" text says without the text. + /// + /// Built the way AswidVisuals builds the Aswid's eyes, which is where the long story lives: the + /// vanilla Skeleton's eye_l/eye_r borrowed for mesh and material, placed on the head bone the + /// body mesh is skinned to, sized from the source's world scale. The placement numbers are the + /// Aswid's playtested defaults, fixed here rather than exposed again. + /// + /// The colour is the Fenring's own: its body material's _EmissionColor, (2.0, 0.372, 0.0) in + /// bundle c4210710, read offline with UnityPy rather than picked by eye. + /// + /// Runs for remote players too. Night is the same for everyone; whether a form is ready is + /// only known to the owner, who writes it to the ZDO (SetReady) for everyone else to read. + /// + public static class FenrirVisuals + { + public const string RaceId = "Fenrir"; + public const string ReadyKey = "RacesOfValheim_FenrirReady"; + private const string FormKey = "RacesOfValheim_FenrirForm"; + private const string EyesName = "FenrirEyes"; + private const string SourceModel = "Skeleton"; + private static readonly string[] SourceEyeNames = { "eye_l", "eye_r" }; + + private static readonly Color FenringGlow = new Color(2.0f, 0.372f, 0f, 1f); + + // AswidVisuals' base placement plus its Configuration Manager defaults, which are what + // playtesting settled on for this same pair of eyes on this same rig. + private const float EyeForward = 0.081f + 0.013f; + private const float EyeHeight = 0.181f + 0.004f; + private const float EyeSeparation = 0.032f + 0.007f; + private const float EyeSize = 1.1f; + private const float EyeYaw = 22.068f; + private const float EyeRoll = -180f; + + /// Owner only, and only on a change: one ZDO write per transition, not per frame. + public static void SetReady(Player player, bool ready) + { + ZNetView nview = player != null ? player.GetComponent() : null; + if (nview == null || !nview.IsValid() || !nview.IsOwner()) return; + + ZDO zdo = nview.GetZDO(); + if (zdo.GetBool(ReadyKey, false) != ready) zdo.Set(ReadyKey, ready); + } + + /// + /// Keeps the eyes on a living Fenrir and takes them off anyone else. Called from + /// VisEquipment.UpdateColors, which is what notices a race change; the ticker below then + /// follows night, readiness and forms frame by frame. + /// + public static void ApplyEyes(Player player) + { + if (player == null) return; + + Transform headBone = FindHeadBone(player); + if (headBone == null) return; // rig not up yet; the ticker or the next refresh retries + + Transform eyes = headBone.Find(EyesName); + + if (DvergarVisuals.GetPlayerRace(player) != RaceId || player.IsDead()) + { + if (eyes != null) + { + // Renamed first: Destroy waits for the end of the frame. + eyes.name = EyesName + "_Removed"; + Object.Destroy(eyes.gameObject); + } + EyeTicker ticker = player.GetComponent(); + if (ticker != null) Object.Destroy(ticker); + return; + } + + if (player.GetComponent() == null) player.gameObject.AddComponent(); + + float strength = GetGlowStrength(player); + if (strength <= 0f) + { + if (eyes != null && eyes.gameObject.activeSelf) eyes.gameObject.SetActive(false); + return; + } + + if (eyes == null) + { + // The skull's facing is measured once, at build time. A head turned by sitting, + // an attack or sleep would measure wrong; see AswidVisuals.ApplyEyes. + if (player.IsAttached() || player.IsAttachedToShip() || player.InAttack() || player.IsSleeping()) return; + eyes = BuildEyes(player, headBone); + if (eyes == null) return; + } + + if (!eyes.gameObject.activeSelf) eyes.gameObject.SetActive(true); + PaintEyes(eyes, FenringGlow * strength); + } + + /// 0 means dark: day, a beast form, or the viewer turned the glow off. + private static float GetGlowStrength(Player player) + { + if (!FenrirConfig.EyeGlow.Value) return 0f; + if (EnvMan.instance == null || !EnvMan.IsNight()) return 0f; + + ZNetView nview = player.GetComponent(); + if (nview == null || !nview.IsValid()) return 0f; + + ZDO zdo = nview.GetZDO(); + if (!string.IsNullOrEmpty(zdo.GetString(FormKey, ""))) return 0f; + + return zdo.GetBool(ReadyKey, false) + ? FenrirConfig.EyeReadyStrength.Value + : FenrirConfig.EyeNightStrength.Value; + } + + public class EyeTicker : MonoBehaviour + { + private Player m_player; + + private void Awake() => m_player = GetComponent(); + + private void LateUpdate() + { + if (m_player == null) { Destroy(this); return; } + ApplyEyes(m_player); + } + } + + /// The body mesh's own Head bone, never the Animator's. See AswidVisuals.FindHeadBone. + private static Transform FindHeadBone(Player player) + { + VisEquipment visEq = player.GetComponent(); + if (visEq == null || visEq.m_bodyModel == null || visEq.m_bodyModel.bones == null) return null; + + foreach (Transform bone in visEq.m_bodyModel.bones) + { + if (bone != null && bone.name == AswidVisuals.PlayerHeadBoneName) return bone; + } + return null; + } + + private static Transform BuildEyes(Player player, Transform headBone) + { + List sources = FindSourceEyes(); + if (sources.Count == 0) return null; + + float lossy = headBone.lossyScale.x; + if (Mathf.Abs(lossy) < 0.0001f) return null; // rig still coming up + float toLocal = 1f / lossy; + + GameObject holder = new GameObject(EyesName); + holder.transform.SetParent(headBone, false); + + RigBindPose.MeasureHeadFrame(player, headBone, RaceId, + out Vector3 forward, out Vector3 up, out Vector3 right); + Quaternion facing = Quaternion.LookRotation(forward, up); + + // The player's own scale cancels the rig's, as in AswidVisuals.PlaceEyes. + float scale = player.transform.localScale.x * toLocal; + + foreach (Transform source in sources) + { + GameObject eye = Object.Instantiate(source.gameObject, holder.transform); + eye.name = source.name; + + float side = source.name.ToLowerInvariant().Contains("_l") ? -1f : 1f; + + eye.transform.localPosition = forward * (EyeForward * scale) + + up * (EyeHeight * scale) + + right * (side * EyeSeparation * scale); + // Yaw mirrored per eye so the pair turns in towards the nose together. + eye.transform.localRotation = Quaternion.Euler(0f, EyeYaw * side, EyeRoll) * facing; + eye.transform.localScale = source.lossyScale * toLocal * EyeSize; + + // Allowlist: whatever else rode along on the skeleton goes. + foreach (Component comp in eye.GetComponentsInChildren(true)) + { + if (comp is Transform || comp is MeshRenderer || comp is MeshFilter) continue; + if (comp is ParticleSystem || comp is ParticleSystemRenderer) + { + // The skeleton's eye smoke, on a child of the eye: too loud for a reflection. + if (comp.gameObject != eye) comp.gameObject.SetActive(false); + continue; + } + Object.Destroy(comp); + } + + foreach (Renderer renderer in eye.GetComponentsInChildren(true)) + { + renderer.enabled = true; + renderer.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off; + renderer.receiveShadows = false; + } + + eye.SetActive(true); + } + + return holder.transform; + } + + /// Every colour property the borrowed material has; see AswidVisuals.PaintEyes. + private static void PaintEyes(Transform holder, Color glow) + { + glow.a = 1f; + foreach (Renderer renderer in holder.GetComponentsInChildren(true)) + { + Material material = renderer.material; + if (material == null) continue; + + if (material.HasProperty("_Color")) material.SetColor("_Color", glow); + if (material.HasProperty("_TintColor")) material.SetColor("_TintColor", glow); + if (material.HasProperty("_BaseColor")) material.SetColor("_BaseColor", glow); + if (material.HasProperty("_EmissionColor")) material.SetColor("_EmissionColor", glow); + } + } + + private static bool warnedSource; + + private static List FindSourceEyes() + { + List found = new List(); + + GameObject prefab = PrefabManager.Cache.GetPrefab(SourceModel); + if (prefab != null) + { + foreach (Transform t in prefab.GetComponentsInChildren(true)) + { + string lower = t.name.ToLower(); + if (lower == SourceEyeNames[0] || lower == SourceEyeNames[1]) found.Add(t); + } + } + + if (found.Count == 0 && !warnedSource) + { + warnedSource = true; + Jotunn.Logger.LogWarning($"[Fenrir] No eye_l/eye_r found on '{SourceModel}' - the eyes stay dark."); + } + return found; + } + } + + [HarmonyPatch(typeof(VisEquipment), "UpdateColors")] + public static class FenrirEyesPatch + { + public static void Postfix(VisEquipment __instance) + { + if (!__instance.m_isPlayer) return; + FenrirVisuals.ApplyEyes(__instance.GetComponent()); + } + } +} From 2becb81b6ffe2e44950cd906bfdb62ea349697f7 Mon Sep 17 00:00:00 2001 From: kanym Date: Fri, 23 Oct 2026 19:58:35 +0200 Subject: [PATCH 053/163] fix(fenrir): the faint night glow is bright enough to see At 0.35 the red channel stayed under 1, so bloom never picked it up and a Fenrir with no form ready looked like it had no glow at all. 0.6 puts it just over. --- JotunnModStub/Fenrir/FenrirConfig.cs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/JotunnModStub/Fenrir/FenrirConfig.cs b/JotunnModStub/Fenrir/FenrirConfig.cs index 68e9a97..67f695a 100644 --- a/JotunnModStub/Fenrir/FenrirConfig.cs +++ b/JotunnModStub/Fenrir/FenrirConfig.cs @@ -200,7 +200,9 @@ namespace RacesOfValheim new ConfigDescription("Shows \" is Ready!\" when a form's cooldown ends. The eyes say the same thing; turn this off if they are enough.")); EyeGlow = config.Bind(appearance, "Eye Glow", true, new ConfigDescription("Fenrir eyes glow at night in the Fenring's own orange: faint while no form can be taken, bright when one can. Off hides them on every Fenrir you see.")); - EyeNightStrength = config.Bind(appearance, "Eye Night Strength", 0.35f, + // Above 0.5 so the red channel (2.0 x strength) passes 1 and the bloom pass picks it + // up: at 0.35 the faint state read as no glow at all. + EyeNightStrength = config.Bind(appearance, "Eye Night Strength", 0.6f, new ConfigDescription("Glow at night while no form is ready.", new AcceptableValueRange(0f, 3f))); EyeReadyStrength = config.Bind(appearance, "Eye Ready Strength", 1.2f, new ConfigDescription("Glow at night while a form is ready.", new AcceptableValueRange(0f, 3f))); From c2bc73b3a095f738d94e15997699e4fa7881812d Mon Sep 17 00:00:00 2001 From: kanym Date: Fri, 23 Oct 2026 20:06:49 +0200 Subject: [PATCH 054/163] feat(fenrir): eyes turn the Cultist's yellow when it is back from cooldown The ready flag becomes an int: none, a form, or the Cultist. The Cultist wins only while its rules give it a cooldown (Yagluth and Queen), since that is the one return worth announcing. Its body shares the Fenring's material and its breath is white flame tinted by texture, so the colour comes from its death effect: FlameRoundYellowParticle's emission, (2.691, 1.797, 0.455), bundle c4210710. --- JotunnModStub/Fenrir/FenrirConfig.cs | 2 +- JotunnModStub/Fenrir/FenrirRace.cs | 23 ++++++++++----- JotunnModStub/Fenrir/FenrirVisuals.cs | 41 ++++++++++++++++++++------- 3 files changed, 48 insertions(+), 18 deletions(-) diff --git a/JotunnModStub/Fenrir/FenrirConfig.cs b/JotunnModStub/Fenrir/FenrirConfig.cs index 67f695a..17a26cd 100644 --- a/JotunnModStub/Fenrir/FenrirConfig.cs +++ b/JotunnModStub/Fenrir/FenrirConfig.cs @@ -199,7 +199,7 @@ namespace RacesOfValheim ReadyMessage = config.Bind(appearance, "Ready Message", true, new ConfigDescription("Shows \" is Ready!\" when a form's cooldown ends. The eyes say the same thing; turn this off if they are enough.")); EyeGlow = config.Bind(appearance, "Eye Glow", true, - new ConfigDescription("Fenrir eyes glow at night in the Fenring's own orange: faint while no form can be taken, bright when one can. Off hides them on every Fenrir you see.")); + new ConfigDescription("Fenrir eyes glow at night in the Fenring's own orange: faint while no form can be taken, bright when one can, yellow when the Cultist is back from its cooldown. Off hides them on every Fenrir you see.")); // Above 0.5 so the red channel (2.0 x strength) passes 1 and the bloom pass picks it // up: at 0.35 the faint state read as no glow at all. EyeNightStrength = config.Bind(appearance, "Eye Night Strength", 0.6f, diff --git a/JotunnModStub/Fenrir/FenrirRace.cs b/JotunnModStub/Fenrir/FenrirRace.cs index 9feeb51..963737b 100644 --- a/JotunnModStub/Fenrir/FenrirRace.cs +++ b/JotunnModStub/Fenrir/FenrirRace.cs @@ -150,7 +150,7 @@ namespace RacesOfValheim { } wasNight = isNight; - FenrirVisuals.SetReady(Player.m_localPlayer, CanTakeAnyForm()); + FenrirVisuals.SetReady(Player.m_localPlayer, GetReadyState()); if (isTransformed) { @@ -174,17 +174,26 @@ namespace RacesOfValheim { } /// - /// Whether one of the three keys would transform right now. The same gates as - /// TryTransformWithRules below, without its messages: this feeds the eye glow. + /// What the eyes should say right now, using the same gates as TryTransformWithRules + /// below without its messages. The Cultist wins over the other forms only while its rules + /// give it a cooldown: that is the one form whose return is worth announcing. /// - private bool CanTakeAnyForm() + private FenrirVisuals.ReadyState GetReadyState() { - if (isTransformed) return false; + if (isTransformed) return FenrirVisuals.ReadyState.None; int state = BossProgressionManager.GetCurrentProgressionState(); - return CanTake(FenrirProgression.GetGKeyRules(state)) + FenrirProgression.FormRules cultist = FenrirProgression.GetJKeyRules(state); + + if (CanTake(cultist) && cultist.CooldownMinutes > 0) return FenrirVisuals.ReadyState.Cultist; + + if (CanTake(FenrirProgression.GetGKeyRules(state)) || CanTake(FenrirProgression.GetHKeyRules(state)) - || CanTake(FenrirProgression.GetJKeyRules(state)); + || CanTake(cultist)) + { + return FenrirVisuals.ReadyState.Form; + } + return FenrirVisuals.ReadyState.None; } private bool CanTake(FenrirProgression.FormRules rules) diff --git a/JotunnModStub/Fenrir/FenrirVisuals.cs b/JotunnModStub/Fenrir/FenrirVisuals.cs index 7b901c0..fd0836b 100644 --- a/JotunnModStub/Fenrir/FenrirVisuals.cs +++ b/JotunnModStub/Fenrir/FenrirVisuals.cs @@ -7,7 +7,8 @@ namespace RacesOfValheim { /// /// The Fenrir's eyes catch the light at night, the way a wolf's do: a faint glow while no form - /// can be taken, a bright one when a key would transform right now. Dark by day and while in a + /// can be taken, a bright one when a key would transform right now, and the Cultist's yellow + /// when that form is back from its cooldown. Dark by day and while in a /// beast form, whose own eyes take over. A community suggestion (lexsonn), meant to say what /// the "Ready!" text says without the text. /// @@ -26,6 +27,14 @@ namespace RacesOfValheim { public const string RaceId = "Fenrir"; public const string ReadyKey = "RacesOfValheim_FenrirReady"; + + /// Written to the ZDO as an int, so the values are part of the network contract. + public enum ReadyState + { + None = 0, + Form = 1, + Cultist = 2, + } private const string FormKey = "RacesOfValheim_FenrirForm"; private const string EyesName = "FenrirEyes"; private const string SourceModel = "Skeleton"; @@ -33,6 +42,11 @@ namespace RacesOfValheim private static readonly Color FenringGlow = new Color(2.0f, 0.372f, 0f, 1f); + // The Cultist's body is the Fenring's material and its breath is white flame tinted by + // texture, so neither tells it apart. Its own death effect (vfx_fenring_cultist_death) + // does: FlameRoundYellowParticle's _EmissionColor, same bundle. + private static readonly Color CultistGlow = new Color(2.691f, 1.797f, 0.455f, 1f); + // AswidVisuals' base placement plus its Configuration Manager defaults, which are what // playtesting settled on for this same pair of eyes on this same rig. private const float EyeForward = 0.081f + 0.013f; @@ -43,13 +57,13 @@ namespace RacesOfValheim private const float EyeRoll = -180f; /// Owner only, and only on a change: one ZDO write per transition, not per frame. - public static void SetReady(Player player, bool ready) + public static void SetReady(Player player, ReadyState ready) { ZNetView nview = player != null ? player.GetComponent() : null; if (nview == null || !nview.IsValid() || !nview.IsOwner()) return; ZDO zdo = nview.GetZDO(); - if (zdo.GetBool(ReadyKey, false) != ready) zdo.Set(ReadyKey, ready); + if (zdo.GetInt(ReadyKey, 0) != (int)ready) zdo.Set(ReadyKey, (int)ready); } /// @@ -81,7 +95,7 @@ namespace RacesOfValheim if (player.GetComponent() == null) player.gameObject.AddComponent(); - float strength = GetGlowStrength(player); + float strength = GetGlowStrength(player, out Color hue); if (strength <= 0f) { if (eyes != null && eyes.gameObject.activeSelf) eyes.gameObject.SetActive(false); @@ -98,12 +112,17 @@ namespace RacesOfValheim } if (!eyes.gameObject.activeSelf) eyes.gameObject.SetActive(true); - PaintEyes(eyes, FenringGlow * strength); + PaintEyes(eyes, hue * strength); } - /// 0 means dark: day, a beast form, or the viewer turned the glow off. - private static float GetGlowStrength(Player player) + /// + /// 0 means dark: day, a beast form, or the viewer turned the glow off. Otherwise faint + /// orange with nothing ready, bright orange with a form ready, bright yellow when the + /// Cultist is back from its cooldown. + /// + private static float GetGlowStrength(Player player, out Color hue) { + hue = FenringGlow; if (!FenrirConfig.EyeGlow.Value) return 0f; if (EnvMan.instance == null || !EnvMan.IsNight()) return 0f; @@ -113,9 +132,11 @@ namespace RacesOfValheim ZDO zdo = nview.GetZDO(); if (!string.IsNullOrEmpty(zdo.GetString(FormKey, ""))) return 0f; - return zdo.GetBool(ReadyKey, false) - ? FenrirConfig.EyeReadyStrength.Value - : FenrirConfig.EyeNightStrength.Value; + ReadyState ready = (ReadyState)zdo.GetInt(ReadyKey, 0); + if (ready == ReadyState.None) return FenrirConfig.EyeNightStrength.Value; + + if (ready == ReadyState.Cultist) hue = CultistGlow; + return FenrirConfig.EyeReadyStrength.Value; } public class EyeTicker : MonoBehaviour From 418d2462bdb34c7394c8f1de59b1dc81eecb6e88 Mon Sep 17 00:00:00 2001 From: kanym Date: Fri, 23 Oct 2026 20:12:30 +0200 Subject: [PATCH 055/163] fix(fenrir): a softer ready glow 1.2 read too strong in game; 0.9 by default. The faint glow stays at 0.6. --- JotunnModStub/Fenrir/FenrirConfig.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/JotunnModStub/Fenrir/FenrirConfig.cs b/JotunnModStub/Fenrir/FenrirConfig.cs index 17a26cd..4a95c89 100644 --- a/JotunnModStub/Fenrir/FenrirConfig.cs +++ b/JotunnModStub/Fenrir/FenrirConfig.cs @@ -204,7 +204,8 @@ namespace RacesOfValheim // up: at 0.35 the faint state read as no glow at all. EyeNightStrength = config.Bind(appearance, "Eye Night Strength", 0.6f, new ConfigDescription("Glow at night while no form is ready.", new AcceptableValueRange(0f, 3f))); - EyeReadyStrength = config.Bind(appearance, "Eye Ready Strength", 1.2f, + // Tried at 1.2 in game: the orange was too strong. + EyeReadyStrength = config.Bind(appearance, "Eye Ready Strength", 0.9f, new ConfigDescription("Glow at night while a form is ready.", new AcceptableValueRange(0f, 3f))); // "debug" in the key keeps it local - see ConfigSync. From 8b7e88e0770502b4adb1151435a738987b3feb7c Mon Sep 17 00:00:00 2001 From: kanym Date: Fri, 23 Oct 2026 22:08:05 +0200 Subject: [PATCH 056/163] fix(fenrir): faint night glow at 0.675, as tuned in game --- JotunnModStub/Fenrir/FenrirConfig.cs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/JotunnModStub/Fenrir/FenrirConfig.cs b/JotunnModStub/Fenrir/FenrirConfig.cs index 4a95c89..e9dd6e5 100644 --- a/JotunnModStub/Fenrir/FenrirConfig.cs +++ b/JotunnModStub/Fenrir/FenrirConfig.cs @@ -201,10 +201,10 @@ namespace RacesOfValheim EyeGlow = config.Bind(appearance, "Eye Glow", true, new ConfigDescription("Fenrir eyes glow at night in the Fenring's own orange: faint while no form can be taken, bright when one can, yellow when the Cultist is back from its cooldown. Off hides them on every Fenrir you see.")); // Above 0.5 so the red channel (2.0 x strength) passes 1 and the bloom pass picks it - // up: at 0.35 the faint state read as no glow at all. - EyeNightStrength = config.Bind(appearance, "Eye Night Strength", 0.6f, + // up: at 0.35 the faint state read as no glow at all. 0.675 is what looked right in game. + EyeNightStrength = config.Bind(appearance, "Eye Night Strength", 0.675f, new ConfigDescription("Glow at night while no form is ready.", new AcceptableValueRange(0f, 3f))); - // Tried at 1.2 in game: the orange was too strong. + // Tried at 1.2 in game: the orange was too strong. 0.9 checked and kept. EyeReadyStrength = config.Bind(appearance, "Eye Ready Strength", 0.9f, new ConfigDescription("Glow at night while a form is ready.", new AcceptableValueRange(0f, 3f))); From d8dcecb573381e4b8b5fe603a62adeb3970bc085 Mon Sep 17 00:00:00 2001 From: kanym Date: Fri, 23 Oct 2026 22:17:17 +0200 Subject: [PATCH 057/163] fix(fenrir): form hits build adrenaline like a weapon hit Vanilla grants a hit's adrenaline inside Attack. The forms skip Attack and call Damage directly, so only the stagger bonus in Character.Damage reached the player: meadow mobs, quick to stagger, filled the bar, while Lox, Tar, Brutes and Furlings gave nothing until staggered. FormMelee.GrantAdrenaline adds the player's unarmed attack adrenaline times the target's multiplier after each claw or bite, and a fifth of it per 0.2s tick of the Cultist's fire. --- JotunnModStub/Fenrir/FenrirBehaviors.cs | 5 +++++ JotunnModStub/Fenrir/FenrirFormShared.cs | 20 ++++++++++++++++++++ 2 files changed, 25 insertions(+) diff --git a/JotunnModStub/Fenrir/FenrirBehaviors.cs b/JotunnModStub/Fenrir/FenrirBehaviors.cs index 2b0783d..e1df615 100644 --- a/JotunnModStub/Fenrir/FenrirBehaviors.cs +++ b/JotunnModStub/Fenrir/FenrirBehaviors.cs @@ -752,6 +752,7 @@ namespace RacesOfValheim if (targetObj != null) hitObjects.Add(targetObj); FormMelee.LogHit(FormLabel, target, totalDamage); target.Damage(hitData); + FormMelee.GrantAdrenaline(target); } } } @@ -1012,6 +1013,7 @@ namespace RacesOfValheim if (targetObj != null) hitObjects.Add(targetObj); FormMelee.LogHit(FormLabel, target, totalDamage); target.Damage(hitData); + FormMelee.GrantAdrenaline(target, 0.2f); // one 0.2s tick: a full hit per second of breath if (ZNetScene.instance != null) { @@ -1141,6 +1143,7 @@ namespace RacesOfValheim if (targetObj != null) hitObjects.Add(targetObj); FormMelee.LogHit(FormLabel, target, totalDamage); target.Damage(hitData); + FormMelee.GrantAdrenaline(target); } } } @@ -1355,6 +1358,7 @@ namespace RacesOfValheim if (targetObj != null) hitObjects.Add(targetObj); FormMelee.LogHit(FormLabel, target, totalDamage); target.Damage(hitData); + FormMelee.GrantAdrenaline(target); } } } @@ -1562,6 +1566,7 @@ namespace RacesOfValheim if (targetObj != null) hitObjects.Add(targetObj); FormMelee.LogHit(FormLabel, target, totalDamage); target.Damage(hitData); + FormMelee.GrantAdrenaline(target); } } } diff --git a/JotunnModStub/Fenrir/FenrirFormShared.cs b/JotunnModStub/Fenrir/FenrirFormShared.cs index 6fafc2e..84dc78a 100644 --- a/JotunnModStub/Fenrir/FenrirFormShared.cs +++ b/JotunnModStub/Fenrir/FenrirFormShared.cs @@ -336,6 +336,26 @@ namespace RacesOfValheim Jotunn.Logger.LogInfo($"[FenrirForm] {form} swing skipped '{hit.name}' (layer {LayerMask.LayerToName(hit.gameObject.layer)}): {reason}."); } + /// + /// The adrenaline vanilla gives for a weapon hit, which a form's hit never got. Vanilla + /// grants it inside Attack (m_attackAdrenaline x the enemy's m_enemyAdrenalineMultiplier); + /// the forms skip Attack and call Damage directly, so only the stagger bonus inside + /// Character.Damage reached the player. That is the report: easy-to-stagger meadow mobs + /// filled the bar, Lox, Tar, Brutes and Furlings only did when staggered. + /// + /// The per-hit amount is the player's own unarmed attack's, since the forms fight + /// unarmed. scale lets a damage-over-time tick pay a fraction of a hit. + /// + public static void GrantAdrenaline(IDestructible target, float scale = 1f) + { + Player player = Player.m_localPlayer; + if (player == null || !(target is Character character) || character == player) return; + + ItemDrop unarmed = player.m_unarmedWeapon; + float perHit = unarmed != null ? unarmed.m_itemData.m_shared.m_attack.m_attackAdrenaline : 1f; + player.AddAdrenaline(perHit * character.m_enemyAdrenalineMultiplier * scale); + } + public static void LogHit(string form, IDestructible target, float damage) { if (!FenrirConfig.DebugFormHits.Value) return; From 7411680553abdba17a0ccea4afcd0cb0b35caa5a Mon Sep 17 00:00:00 2001 From: kanym Date: Fri, 23 Oct 2026 22:27:26 +0200 Subject: [PATCH 058/163] chore(release): v1.5.14 - Fenrir night eyes, form adrenaline, full-stomach eating Fenrir eyes glow at night, brighter when a form is ready and yellow when the Cultist is back. Form hits build adrenaline like a weapon hit. Race foods replace a worn-down meal when the stomach is full. The stamina bar comes back after leaving Aswid or Draugh. Other players see a Furling at Furling size, and a Legacy True Form Trol hits as far as it reaches. README: New in block, Fenrir night eyes, changelog entry, new Discord link (also in the old JotunnModStub README). --- JotunnModStub/Package/manifest.json | 2 +- JotunnModStub/README.md | 2 +- JotunnModStub/RacesOfValheim.cs | 2 +- README.md | 16 +++++++++++++--- manifest.json | 2 +- 5 files changed, 17 insertions(+), 7 deletions(-) diff --git a/JotunnModStub/Package/manifest.json b/JotunnModStub/Package/manifest.json index 8b1a0cf..6c5a7ef 100644 --- a/JotunnModStub/Package/manifest.json +++ b/JotunnModStub/Package/manifest.json @@ -1,7 +1,7 @@ { "name": "RacesOfValheim", "description": "A Valheim mod that adds ten custom playable races (Aswid, Draugh, Dvergar, Fenrir, Furling, Skadi, Skeleton, Sverm, Trenta, Trol) each with unique abilities, traits, race stations and a deep boss-driven progression system.", - "version_number": "1.5.13", + "version_number": "1.5.14", "website_url": "", "dependencies": [ "denikson-BepInExPack_Valheim-5.4.2333", diff --git a/JotunnModStub/README.md b/JotunnModStub/README.md index e9389e3..343bba3 100644 --- a/JotunnModStub/README.md +++ b/JotunnModStub/README.md @@ -109,7 +109,7 @@ This mod currently introduces 6 custom races: 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** +Please write to us on my Discord server: **https://discord.gg/dW72ch6Sw5** ## Changelog diff --git a/JotunnModStub/RacesOfValheim.cs b/JotunnModStub/RacesOfValheim.cs index 1bd1c2b..4ff8ec9 100644 --- a/JotunnModStub/RacesOfValheim.cs +++ b/JotunnModStub/RacesOfValheim.cs @@ -16,7 +16,7 @@ namespace RacesOfValheim { public const string PluginGUID = "com.nandor.racesofvalheim"; public const string PluginName = "Races Of Valheim"; - public const string PluginVersion = "1.5.13"; + public const string PluginVersion = "1.5.14"; private readonly Harmony harmony = new Harmony(PluginGUID); diff --git a/README.md b/README.md index 8c1b542..9e09880 100644 --- a/README.md +++ b/README.md @@ -10,14 +10,14 @@ A comprehensive Valheim mod allowing you to play as unique races, each providing This is a stable release, but more races and refinements are planned! Wiki: [https://wiki.aledanidev.ovh/](https://wiki.aledanidev.ovh/) -Bug reports, feedback, ideas: [https://discord.gg/jJzuKBZNC](https://discord.gg/jJzuKBZNC) +Bug reports, feedback, ideas: [https://discord.gg/dW72ch6Sw5](https://discord.gg/dW72ch6Sw5) Support the mod: [Patreon — NandorTheModder](https://www.patreon.com/c/NandorTheModder) --- -## New in v1.5.13 +## New in v1.5.14 -Fixes a freeze on servers with factions on: when a building a mob was attacking got destroyed, every creature in the area stopped moving and players slid on the ground. Dvergar now pay the discounted metal cost the build menu shows. Full details in the [changelog](#v1513). +A Fenrir's eyes now glow at night, brighter when a form is ready and yellow when the Cultist is back. Fenrir forms build adrenaline on every hit, Trenta can eat seeds with a full stomach, and the stamina bar comes back after leaving Aswid or Draugh. Full details in the [changelog](#v1514). --- @@ -47,6 +47,7 @@ Fixes a freeze on servers with factions on: when a building a mob was attacking - **Beast Form:** Transform into a wolf-like beast. - **Cultist Form:** Transform into a Cultist. Its claws cost nothing, but the **fire breath (hold Right Mouse) runs on eitr** — 12.5 per second — and eitr comes from the Mistlands, so the form unlocks at Yagluth with its flames still out of reach. Holding the button with an empty pool now says so. - **Cursed Claws:** The wolf's hands, kept on in the man's shape — see [Claws](#claws). +- **Night Eyes:** At night your eyes glow in the Fenring's orange: faintly while no form is ready, brightly when one is, and yellow when the Cultist is back from its cooldown. Other players see it too. Turn it off, or the "Ready!" message, under `Fenrir - Appearance`. - **Sneak and Sleep:** Forms sneak at a walk when you crouch and stand still to attack. Sit down as an Ulv and it curls up asleep. - **A Pack of Your Own:** The Pack Trough keeps a standing pack of wolves, ulvs and, late, fenrir — see [Race Stations](#race-stations--companions). - **Progression:** Forms grow as you defeat bosses, unlocking new powers and reducing cooldowns. Immune to fall damage. @@ -450,6 +451,15 @@ Both halves have an off switch under `Factions` in Configuration Manager: **Fact ## Changelog +### v1.5.14 +- **New - Fenrir night eyes:** at night a Fenrir's eyes glow in the Fenring's orange, the way a wolf's eyes catch the light. Faint while no form is ready, bright when one is, and yellow when the Cultist is back from its cooldown. Other players see it too. Under `Fenrir - Appearance` each player can turn off the glow or the "Ready!" message for themselves. Thanks to lexsonn for the idea. +- **Fix - Fenrir forms and adrenaline:** in Wolf, Ulv, Fenring and Cultist form, hits now build adrenaline the way a weapon does. Before, only staggering an enemy did, so Lox, Tar, Brutes and Furlings gave almost none. The Cultist's fire breath builds it too, about one hit's worth per second. Thanks to lexsonn for the report. +- **Fix - eating with a full stomach:** with all three food slots full, a Trenta couldn't eat seeds, and a Draugh's raw flesh or an Aswid's meals could get stuck the same way. Nothing happened and no message said why. They now follow the normal rule: they replace the meal that has worn down the most, once it's past half its time, and otherwise show the usual "too full" message. Thanks to ExpensiveMouse1700 for the report. +- **Fix - stamina bar after Aswid or Draugh:** switching from Aswid or Draugh to a race with stamina no longer leaves you without a stamina bar until you log out. Thanks to frogneel for the report. +- **Fix - Furling size for other players:** other players now see a Furling at Furling size. The shrink was only applied on the Furling's own screen, so everyone else saw them at full height. +- **Fix - Legacy True Form reach:** a big Trol's weapons now hit as far as they reach. Vanilla measured every swing at a human's range, so in Legacy True Form only the closest targets got hit. Melee range and swing width now grow with the model's size, for every race that grows. +- **Change - new Discord link:** [https://discord.gg/dW72ch6Sw5](https://discord.gg/dW72ch6Sw5). + ### v1.5.13 - **Fix - world freezes with factions on:** since v1.5.11, if a mob was targeting a building piece and the piece got destroyed or removed, the faction check threw an error every frame. On a server this stopped the AI of every creature in the area: players slid on the ground, enemies stood still, and characters sometimes turned invisible. The check now drops the dead target and moves on. Thanks to SCRIMSHAW and GaoVN for the reports, and to SCRIMSHAW for testing the fix on their server. - **Fix - Dvergar build discount:** the build menu showed the discounted metal cost (a cauldron for 6 tin instead of 10), but the hammer still refused to place the piece unless you carried the full vanilla amount. Pieces now build at the price shown. Dismantling or destroying a piece a Dvergar built returns the metal they paid, not the vanilla amount. Thanks to Balmarog for the report. diff --git a/manifest.json b/manifest.json index 8b1a0cf..6c5a7ef 100644 --- a/manifest.json +++ b/manifest.json @@ -1,7 +1,7 @@ { "name": "RacesOfValheim", "description": "A Valheim mod that adds ten custom playable races (Aswid, Draugh, Dvergar, Fenrir, Furling, Skadi, Skeleton, Sverm, Trenta, Trol) each with unique abilities, traits, race stations and a deep boss-driven progression system.", - "version_number": "1.5.13", + "version_number": "1.5.14", "website_url": "", "dependencies": [ "denikson-BepInExPack_Valheim-5.4.2333", From 53f6fb71a2dee8427da8f8e96accd2b765e34be3 Mon Sep 17 00:00:00 2001 From: kanym Date: Sat, 24 Oct 2026 15:28:04 +0200 Subject: [PATCH 059/163] fix(skeleton): Auto-Resurrect on the real deathblow; Summon on Kill toggle Auto-Resurrect was decided in the Character.Damage prefix on the raw hit: before armour, blocking and resistances, with poison and fire counted in full. With good armour it fired on almost any hit. Damage also runs on the attacker's owner, so on a dedicated server a mob owned by the server or another player skipped the check entirely. It now runs in an ApplyDamage prefix, on the victim's own client, against the damage that is about to land. The rising-from-the-ground immunity is checked there too. Summon on Kill gets a toggle key (G, Skeleton - Keybinds) and a gamepad radial entry. The choice is saved on the character, on by default. A "Raise the Dead" status icon with the Dead Raiser's picture shows while it is on. Texts in English, Italian and Russian. --- JotunnModStub/RaceRadial.cs | 3 + JotunnModStub/Skeleton/SkeletonConfig.cs | 9 ++ JotunnModStub/Skeleton/SkeletonPatches.cs | 84 ++++++++++++------- JotunnModStub/Skeleton/SkeletonRace.cs | 70 ++++++++++++++++ .../Translations/English/messages.json | 5 +- .../Translations/English/status_effects.json | 4 +- .../Translations/Italian/messages.json | 5 +- .../Translations/Italian/status_effects.json | 4 +- .../Translations/Russian/messages.json | 5 +- .../Translations/Russian/status_effects.json | 4 +- 10 files changed, 158 insertions(+), 35 deletions(-) diff --git a/JotunnModStub/RaceRadial.cs b/JotunnModStub/RaceRadial.cs index 3e4e0da..a3dfc6b 100644 --- a/JotunnModStub/RaceRadial.cs +++ b/JotunnModStub/RaceRadial.cs @@ -72,6 +72,9 @@ namespace RacesOfValheim new Entry { Race = "Sverm", Label = "Ravager Strain", Key = () => SvermConfigManagement.RavagerKey, Icon = "TrophySeekerBrute" }, + new Entry { Race = "Skeleton", Label = "Summon on Kill", Key = () => SkeletonConfig.SummonToggleKey, Icon = "StaffSkeleton", + Available = player => SkeletonProgression.GetRules(BossProgressionManager.GetCurrentProgressionState()).SummonOnKill }, + // Any race: shown to whoever RaceClawSet has claws for. new Entry { Race = null, Label = "Grow Claws", Key = () => RaceClawsConfig.ActivateKey, Icon = "TrophyWolf", Available = player => RaceClawSet.For(player) != null }, diff --git a/JotunnModStub/Skeleton/SkeletonConfig.cs b/JotunnModStub/Skeleton/SkeletonConfig.cs index c6b8ba6..c5a9abf 100644 --- a/JotunnModStub/Skeleton/SkeletonConfig.cs +++ b/JotunnModStub/Skeleton/SkeletonConfig.cs @@ -1,4 +1,5 @@ using BepInEx.Configuration; +using UnityEngine; namespace RacesOfValheim { @@ -39,6 +40,9 @@ namespace RacesOfValheim // ─── Resurrection (tier 6+) ──────────────────────────────────────────── public static ConfigEntry ResurrectionCooldown; + // ─── Keybinds ────────────────────────────────────────────────────────── + public static ConfigEntry SummonToggleKey; + // ─── Visuals ─────────────────────────────────────────────────────────── public static ConfigEntry HeadFireVFXEnabled; public static ConfigEntry BodyModelEnabled; @@ -65,6 +69,11 @@ namespace RacesOfValheim FireAuraTickInterval = config.Bind(aura, "Tick Interval", 1f, new ConfigDescription("Seconds between aura damage ticks.", new AcceptableValueRange(0.1f, 5f))); + // G is the first ability key of every race that has one; the Skeleton had none. + const string keybinds = "Skeleton - Keybinds"; + SummonToggleKey = config.Bind(keybinds, "Toggle Summon on Kill", new KeyboardShortcut(KeyCode.G), + "Turns raising a skeleton from each kill on and off (The Queen and later). The Dead Raiser icon shows while it is on."); + const string resurrection = "Skeleton - Resurrection"; ResurrectionCooldown = config.Bind(resurrection, "Cooldown", 300f, new ConfigDescription("Seconds between auto-resurrections, tier 6+.", new AcceptableValueRange(0f, 3600f))); diff --git a/JotunnModStub/Skeleton/SkeletonPatches.cs b/JotunnModStub/Skeleton/SkeletonPatches.cs index 461fa75..8bfab05 100644 --- a/JotunnModStub/Skeleton/SkeletonPatches.cs +++ b/JotunnModStub/Skeleton/SkeletonPatches.cs @@ -597,6 +597,58 @@ namespace RacesOfValheim } } + /// + /// Auto-Resurrect, decided on the hit that would actually kill. + /// + /// It used to be decided in the Character.Damage prefix below, on hit.GetTotalDamage(), + /// and that number is the raw hit: before armour, blocking and resistances, and with the + /// hit's poison and fire counted in full although vanilla splits those off and lands them + /// over time. Any hit whose raw size beat the current health raised the Skeleton, so with + /// good armour it fired on "just about any damage" (akira's report). Damage also runs on + /// whoever owns the attacker, so on a dedicated server a mob owned by the server or by + /// another player never reached this check at all, and a real deathblow went through. + /// + /// ApplyDamage is what RPC_Damage calls on the victim's owner, after armour, blocking and + /// resistances, with poison, fire and spirit already moved out into their status effects. + /// Those effects come back through here on each tick, so a lethal tick still counts. The + /// one scaling left inside ApplyDamage for a player is the damage-taken rate. + /// + [HarmonyPatch(typeof(Character), nameof(Character.ApplyDamage))] + public static class Skeleton_ApplyDamage_Patch + { + private static readonly int CooldownHash = "SE_SkeletonResurrectCooldown".GetStableHashCode(); + + public static bool Prefix(Character __instance, HitData hit) + { + Player player = Player.m_localPlayer; + if (player == null || __instance != player) return true; + + // Here as well as in the Damage prefix, which only sees hits thrown from this client. + if (SkeletonRise.IsRising(player)) return false; + + if (!SkeletonRace.IsSkeleton() || player.IsDead()) return true; + if (!SkeletonProgression.GetRules(BossProgressionManager.GetCurrentProgressionState()).AutoResurrect) return true; + + float damage = hit.GetTotalDamage() * Game.m_localDamgeTakenRate; + if (damage < player.GetHealth()) return true; + if (player.GetSEMan().HaveStatusEffect(CooldownHash)) return true; + + player.Heal(player.GetMaxHealth(), true); + player.GetSEMan().AddStatusEffect(CooldownHash, true); + + // Confirmed real via 'listprefabs'; see SummonOnKill below. + GameObject vfx = PrefabManager.Cache.GetPrefab("fx_summon_skeleton_spawn") ?? + PrefabManager.Cache.GetPrefab("fx_summon_skeleton"); + if (vfx != null) UnityEngine.Object.Instantiate(vfx, player.transform.position, Quaternion.identity); + + // The body climbs out of the ground the way a crypt skeleton does. + SkeletonRise.Begin(player); + + player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_skeleton_have_been_resurrected_by_dark")); + return false; // the lethal hit never lands + } + } + [HarmonyPatch(typeof(Character), "Damage")] public static class Character_Damage_Patch { @@ -624,34 +676,8 @@ namespace RacesOfValheim // Half in the ground: nothing lands on a Skeleton while it climbs back out. if (__instance == Player.m_localPlayer && SkeletonRise.IsRising(Player.m_localPlayer)) return false; - // Auto-Resurrect check - if (__instance == Player.m_localPlayer && SkeletonRace.IsSkeleton() && rules.AutoResurrect) - { - if (hit.GetTotalDamage() >= __instance.GetHealth()) - { - if (!Player.m_localPlayer.GetSEMan().HaveStatusEffect("SE_SkeletonResurrectCooldown".GetStableHashCode())) - { - // Cancel death! - Player.m_localPlayer.Heal(Player.m_localPlayer.GetMaxHealth(), true); - Player.m_localPlayer.GetSEMan().AddStatusEffect("SE_SkeletonResurrectCooldown".GetStableHashCode(), true); - - // Spawn VFX - confirmed real via 'listprefabs'; see SummonOnKill below - // for how the previous two guesses here were caught and replaced. - GameObject vfx = PrefabManager.Cache.GetPrefab("fx_summon_skeleton_spawn") ?? - PrefabManager.Cache.GetPrefab("fx_summon_skeleton"); - if (vfx != null) - { - UnityEngine.Object.Instantiate(vfx, Player.m_localPlayer.transform.position, Quaternion.identity); - } - - // The body climbs out of the ground the way a crypt skeleton does. - SkeletonRise.Begin(Player.m_localPlayer); - - Player.m_localPlayer.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_skeleton_have_been_resurrected_by_dark")); - return false; // Skip applying this lethal damage - } - } - } + // The Auto-Resurrect check used to live here and is now in + // Skeleton_ApplyDamage_Patch below; see there for why. // Outgoing damage (Lifesteal, Poison, Stun) Character attacker = hit.GetAttacker(); @@ -740,7 +766,7 @@ namespace RacesOfValheim int state = BossProgressionManager.GetCurrentProgressionState(); var rules = SkeletonProgression.GetRules(state); - if (rules.SummonOnKill && !string.IsNullOrEmpty(rules.SummonPrefab)) + if (rules.SummonOnKill && SkeletonRace.SummonOnKillEnabled && !string.IsNullOrEmpty(rules.SummonPrefab)) { // Clean up dead minions activeMinions.RemoveAll(m => m == null || m.IsDead()); diff --git a/JotunnModStub/Skeleton/SkeletonRace.cs b/JotunnModStub/Skeleton/SkeletonRace.cs index 1895ed5..8a80c7e 100644 --- a/JotunnModStub/Skeleton/SkeletonRace.cs +++ b/JotunnModStub/Skeleton/SkeletonRace.cs @@ -48,6 +48,73 @@ namespace RacesOfValheim resurrectSE.name = "SE_SkeletonResurrectCooldown"; CustomStatusEffect customResurrectSE = new CustomStatusEffect(resurrectSE, fixReference: false); ItemManager.Instance.AddStatusEffect(customResurrectSE); + + // The "Summon on Kill is on" icon. The Dead Raiser's, since the Skeleton trophy is + // already Undead Fortitude's and this is the staff that raises skeletons in vanilla. + var raiseSE = ScriptableObject.CreateInstance(); + raiseSE.name = RaiseDeadEffectName; + raiseSE.m_name = "$rov_se_skeleton_raisedead_name"; + raiseSE.m_tooltip = "$rov_se_skeleton_raisedead_tooltip"; + raiseSE.m_icon = PrefabManager.Cache.GetPrefab("StaffSkeleton")?.m_itemData.GetIcon() + ?? PrefabManager.Cache.GetPrefab("TrophySkeleton")?.m_itemData.GetIcon(); + ItemManager.Instance.AddStatusEffect(new CustomStatusEffect(raiseSE, fixReference: false)); + } + + // ─── Summon on Kill switch ────────────────────────────────────────── + + private const string RaiseDeadEffectName = "SE_SkeletonRaiseDead"; + private static readonly int RaiseDeadEffectHash = RaiseDeadEffectName.GetStableHashCode(); + + // Stored as "off" on the character, so a character that never pressed the key - every + // existing one - keeps the perk on. + private const string SummonOffKey = "RacesOfValheim_SkeletonSummonOff"; + + /// Whether this character wants a skeleton raised from each kill. Per character, saved with it. + public static bool SummonOnKillEnabled + { + get + { + Player player = Player.m_localPlayer; + return player == null || player.m_customData == null || !player.m_customData.ContainsKey(SummonOffKey); + } + set + { + Player player = Player.m_localPlayer; + if (player == null || player.m_customData == null) return; + if (value) player.m_customData.Remove(SummonOffKey); + else player.m_customData[SummonOffKey] = "1"; + } + } + + /// + /// The toggle key, and the icon that says the perk is on. The icon is put back whenever it + /// is missing, because status effects do not survive death or a relog. + /// + private static void TickSummonToggle(Player player, SkeletonProgression.SkeletonRules rules) + { + if (RaceInput.Allowed && SkeletonConfig.SummonToggleKey.Value.IsDownIgnoringHeldKeys()) + { + if (!rules.SummonOnKill) + { + player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_skeleton_summon_locked")); + } + else + { + SummonOnKillEnabled = !SummonOnKillEnabled; + player.Message(MessageHud.MessageType.Center, + ModText.Get(SummonOnKillEnabled ? "rov_msg_skeleton_summon_on" : "rov_msg_skeleton_summon_off")); + } + } + + SetRaiseDeadIcon(player, rules.SummonOnKill && SummonOnKillEnabled); + } + + private static void SetRaiseDeadIcon(Player player, bool on) + { + SEMan seman = player.GetSEMan(); + bool has = seman.HaveStatusEffect(RaiseDeadEffectHash); + if (on && !has) seman.AddStatusEffect(RaiseDeadEffectHash, true); + else if (!on && has) seman.RemoveStatusEffect(RaiseDeadEffectHash, true); } public static bool IsSkeleton() @@ -272,6 +339,7 @@ namespace RacesOfValheim SkeletonVisuals.EnsureFireAura(Player.m_localPlayer, false, ref fireAuraVFX); headFlame.Apply(Player.m_localPlayer, false); RestoreJawBone(); + SetRaiseDeadIcon(Player.m_localPlayer, false); if (Player.m_localPlayer.transform.localScale != Vector3.one) { @@ -319,6 +387,8 @@ namespace RacesOfValheim int state = BossProgressionManager.GetCurrentProgressionState(); var rules = SkeletonProgression.GetRules(state); + TickSummonToggle(Player.m_localPlayer, rules); + // Continuously adjust equipment VisEquipment currentVis = Player.m_localPlayer.GetComponent(); if (currentVis != null) diff --git a/JotunnModStub/Translations/English/messages.json b/JotunnModStub/Translations/English/messages.json index 8f7c7fa..92fd052 100644 --- a/JotunnModStub/Translations/English/messages.json +++ b/JotunnModStub/Translations/English/messages.json @@ -202,5 +202,8 @@ "rov_msg_warvulture_vulture_settles_into_glide": "The vulture settles into a glide.", "rov_msg_warvulture_vulture_spirals_down": "The vulture spirals down.", "rov_msg_boneship_no_shore": "No shore in reach. They stay at the oars.", - "rov_msg_boneship_sunk": "The ship goes down, and $1 go with it." + "rov_msg_boneship_sunk": "The ship goes down, and $1 go with it.", + "rov_msg_skeleton_summon_on": "Summon on Kill: on. The dead will rise for you.", + "rov_msg_skeleton_summon_off": "Summon on Kill: off. The dead stay down.", + "rov_msg_skeleton_summon_locked": "Summon on Kill awakens once The Queen falls." } diff --git a/JotunnModStub/Translations/English/status_effects.json b/JotunnModStub/Translations/English/status_effects.json index ba0b959..dd86c98 100644 --- a/JotunnModStub/Translations/English/status_effects.json +++ b/JotunnModStub/Translations/English/status_effects.json @@ -58,5 +58,7 @@ "rov_se_trol_trueform_name": "True Form", "rov_se_trol_trueform_tooltip": "You have unleashed your inner troll!", "rov_se_trol_trueformcd_name": "True Form Cooldown", - "rov_se_trol_trueformcd_tooltip": "You are exhausted from your True Form." + "rov_se_trol_trueformcd_tooltip": "You are exhausted from your True Form.", + "rov_se_skeleton_raisedead_name": "Raise the Dead", + "rov_se_skeleton_raisedead_tooltip": "Each kill raises a skeleton to fight for you. Press the Summon on Kill key to turn it off." } diff --git a/JotunnModStub/Translations/Italian/messages.json b/JotunnModStub/Translations/Italian/messages.json index f0e20bb..1e1ee27 100644 --- a/JotunnModStub/Translations/Italian/messages.json +++ b/JotunnModStub/Translations/Italian/messages.json @@ -202,5 +202,8 @@ "rov_msg_warvulture_vulture_settles_into_glide": "L'avvoltoio si mette a planare.", "rov_msg_warvulture_vulture_spirals_down": "L'avvoltoio scende a spirale.", "rov_msg_boneship_no_shore": "Nessuna riva a portata. Restano ai remi.", - "rov_msg_boneship_sunk": "La nave affonda, e con lei $1." + "rov_msg_boneship_sunk": "La nave affonda, e con lei $1.", + "rov_msg_skeleton_summon_on": "Evoca all'uccisione: attiva. I morti si alzeranno per te.", + "rov_msg_skeleton_summon_off": "Evoca all'uccisione: disattiva. I morti restano a terra.", + "rov_msg_skeleton_summon_locked": "Evoca all'uccisione si risveglia quando cade la Regina." } diff --git a/JotunnModStub/Translations/Italian/status_effects.json b/JotunnModStub/Translations/Italian/status_effects.json index e4e391c..ed8a813 100644 --- a/JotunnModStub/Translations/Italian/status_effects.json +++ b/JotunnModStub/Translations/Italian/status_effects.json @@ -58,5 +58,7 @@ "rov_se_trol_trueform_name": "Vera forma", "rov_se_trol_trueform_tooltip": "Hai scatenato il troll che è in te!", "rov_se_trol_trueformcd_name": "Ricarica vera forma", - "rov_se_trol_trueformcd_tooltip": "Sei esausto dopo la tua vera forma." + "rov_se_trol_trueformcd_tooltip": "Sei esausto dopo la tua vera forma.", + "rov_se_skeleton_raisedead_name": "Risveglio dei morti", + "rov_se_skeleton_raisedead_tooltip": "Ogni uccisione fa risorgere uno scheletro che combatte per te. Premi il tasto di Evoca all'uccisione per disattivarlo." } diff --git a/JotunnModStub/Translations/Russian/messages.json b/JotunnModStub/Translations/Russian/messages.json index 3ef6918..128bd9a 100644 --- a/JotunnModStub/Translations/Russian/messages.json +++ b/JotunnModStub/Translations/Russian/messages.json @@ -202,5 +202,8 @@ "rov_msg_warvulture_vulture_settles_into_glide": "Стервятник переходит в планирующий полет.", "rov_msg_warvulture_vulture_spirals_down": "Стервятник кружит, спускаясь по спирали.", "rov_msg_boneship_no_shore": "Берега не видно. Они остаются на веслах.", - "rov_msg_boneship_sunk": "Корабль идет ко дну, и $1 вместе с ним." + "rov_msg_boneship_sunk": "Корабль идет ко дну, и $1 вместе с ним.", + "rov_msg_skeleton_summon_on": "Призыв при убийстве: включён. Мёртвые восстанут ради тебя.", + "rov_msg_skeleton_summon_off": "Призыв при убийстве: выключен. Мёртвые остаются лежать.", + "rov_msg_skeleton_summon_locked": "Призыв при убийстве пробудится, когда падёт Королева." } diff --git a/JotunnModStub/Translations/Russian/status_effects.json b/JotunnModStub/Translations/Russian/status_effects.json index f1f2d58..d38df6e 100644 --- a/JotunnModStub/Translations/Russian/status_effects.json +++ b/JotunnModStub/Translations/Russian/status_effects.json @@ -58,5 +58,7 @@ "rov_se_trol_trueform_name": "Истинный облик", "rov_se_trol_trueform_tooltip": "Вы выпустили своего внутреннего тролля на свободу!", "rov_se_trol_trueformcd_name": "Перезарядка истинного облика", - "rov_se_trol_trueformcd_tooltip": "Вы истощены после пребывания в Истинном облике." + "rov_se_trol_trueformcd_tooltip": "Вы истощены после пребывания в Истинном облике.", + "rov_se_skeleton_raisedead_name": "Восстание мёртвых", + "rov_se_skeleton_raisedead_tooltip": "Каждое убийство поднимает скелета, который сражается за тебя. Нажми клавишу призыва при убийстве, чтобы выключить." } From 98b1a1b5f3318ca78289d3fd05b5a89335e5f5c9 Mon Sep 17 00:00:00 2001 From: kanym Date: Sat, 24 Oct 2026 15:38:42 +0200 Subject: [PATCH 060/163] feat(skeleton): dark aura while Summon on Kill is on, archaic toggle messages Beside the Raise the Dead icon, a faint near-black smoke now rises off the whole body while Summon on Kill is on: the Draugr's looping smoke, borrowed like the Draugh aura, emitted from a body-sized box in world space. The owner writes the switch to the ZDO, so other players see it. "Raise the Dead Icon" and "Raise the Dead Aura" under Skeleton - Visuals let each player keep either or both, for a community vote. The toggle now says "Thy dead shall rise again." / "Raising... nevermore.", in English, Italian and Russian. --- JotunnModStub/Skeleton/SkeletonConfig.cs | 8 +- JotunnModStub/Skeleton/SkeletonRace.cs | 19 ++- JotunnModStub/Skeleton/SkeletonVisuals.cs | 109 ++++++++++++++++++ .../Translations/English/messages.json | 4 +- .../Translations/Italian/messages.json | 4 +- .../Translations/Russian/messages.json | 4 +- JotunnModStub/ZdoVisualSync.cs | 3 + 7 files changed, 143 insertions(+), 8 deletions(-) diff --git a/JotunnModStub/Skeleton/SkeletonConfig.cs b/JotunnModStub/Skeleton/SkeletonConfig.cs index c5a9abf..7b4a2b9 100644 --- a/JotunnModStub/Skeleton/SkeletonConfig.cs +++ b/JotunnModStub/Skeleton/SkeletonConfig.cs @@ -46,6 +46,8 @@ namespace RacesOfValheim // ─── Visuals ─────────────────────────────────────────────────────────── public static ConfigEntry HeadFireVFXEnabled; public static ConfigEntry BodyModelEnabled; + public static ConfigEntry RaiseDeadIcon; + public static ConfigEntry RaiseDeadAura; public static void Bind(ConfigFile config) { @@ -72,7 +74,7 @@ namespace RacesOfValheim // G is the first ability key of every race that has one; the Skeleton had none. const string keybinds = "Skeleton - Keybinds"; SummonToggleKey = config.Bind(keybinds, "Toggle Summon on Kill", new KeyboardShortcut(KeyCode.G), - "Turns raising a skeleton from each kill on and off (The Queen and later). The Dead Raiser icon shows while it is on."); + "Turns raising a skeleton from each kill on and off (The Queen and later). While it is on, the Raise the Dead icon and a faint dark aura show it (see Skeleton - Visuals)."); const string resurrection = "Skeleton - Resurrection"; ResurrectionCooldown = config.Bind(resurrection, "Cooldown", 300f, @@ -83,6 +85,10 @@ namespace RacesOfValheim new ConfigDescription("Whether the burning-skull effect (worn from tier 5+) renders at all. A client-side preference: disabling it stops you from seeing it on yourself and on every other skeleton you look at, but does not change what other players see.")); BodyModelEnabled = config.Bind(visuals, "Body Model Enabled", true, new ConfigDescription("Whether Skeleton players wear the skeleton body. Turn it off if you use a player model mod (EnhancedValheimVRM and the like): Skeletons then keep the vanilla viking body, so the replacement model shows without bones clipping through it. Abilities are unchanged. Client-side, like the option above: it applies to every Skeleton you see, yourself included, and changes nothing for other players.")); + RaiseDeadIcon = config.Bind(visuals, "Raise the Dead Icon", true, + new ConfigDescription("Shows the Raise the Dead status icon while your Summon on Kill is on.")); + RaiseDeadAura = config.Bind(visuals, "Raise the Dead Aura", true, + new ConfigDescription("A faint dark smoke rises off a Skeleton whose Summon on Kill is on. Client-side: turning it off hides it on yourself and on every other Skeleton you see.")); } } } diff --git a/JotunnModStub/Skeleton/SkeletonRace.cs b/JotunnModStub/Skeleton/SkeletonRace.cs index 8a80c7e..b5fb170 100644 --- a/JotunnModStub/Skeleton/SkeletonRace.cs +++ b/JotunnModStub/Skeleton/SkeletonRace.cs @@ -106,7 +106,22 @@ namespace RacesOfValheim } } - SetRaiseDeadIcon(player, rules.SummonOnKill && SummonOnKillEnabled); + bool on = rules.SummonOnKill && SummonOnKillEnabled; + SetRaiseDeadIcon(player, on && SkeletonConfig.RaiseDeadIcon.Value); + Instance?.raisingAura.Apply(player, on && SkeletonConfig.RaiseDeadAura.Value); + SetRaisingFlag(player, on); + } + + private readonly SkeletonVisuals.RaisingAura raisingAura = new SkeletonVisuals.RaisingAura(); + + /// Owner only, and only on a change, so other clients can draw the aura. + private static void SetRaisingFlag(Player player, bool on) + { + ZNetView nview = player.GetComponent(); + if (nview == null || !nview.IsValid() || !nview.IsOwner()) return; + + ZDO zdo = nview.GetZDO(); + if (zdo.GetBool(SkeletonVisuals.RaisingZdoKey, false) != on) zdo.Set(SkeletonVisuals.RaisingZdoKey, on); } private static void SetRaiseDeadIcon(Player player, bool on) @@ -340,6 +355,8 @@ namespace RacesOfValheim headFlame.Apply(Player.m_localPlayer, false); RestoreJawBone(); SetRaiseDeadIcon(Player.m_localPlayer, false); + raisingAura.Apply(Player.m_localPlayer, false); + SetRaisingFlag(Player.m_localPlayer, false); if (Player.m_localPlayer.transform.localScale != Vector3.one) { diff --git a/JotunnModStub/Skeleton/SkeletonVisuals.cs b/JotunnModStub/Skeleton/SkeletonVisuals.cs index e91963c..aa22629 100644 --- a/JotunnModStub/Skeleton/SkeletonVisuals.cs +++ b/JotunnModStub/Skeleton/SkeletonVisuals.cs @@ -434,6 +434,115 @@ namespace RacesOfValheim aura = null; } + /// The owner's Summon on Kill switch, for every other client to read. + public const string RaisingZdoKey = "RacesOfValheim_SkeletonRaising"; + + /// + /// A faint dark smoke rising off the whole body while Summon on Kill is on: the other half + /// of the indicator, beside the Raise the Dead icon, so the community can pick either or + /// both. Cosmetic only. + /// + /// The smoke is the Draugr's own looping one, the same particle DraughVisuals.BuildAura + /// borrows, cloned through BorrowEffect and tinted near-black. It emits from a box the + /// size of the body rather than from one point, so it comes off the arms and legs too. + /// A mesh-shaped emitter would hug the body closer, but only works on a readable mesh. + /// + /// Held per player, like HeadFlame. Call Apply every frame; it builds once. + /// + public class RaisingAura + { + private static readonly Color Smoke = new Color(0.06f, 0.06f, 0.07f, 0.35f); + private static readonly Vector3 BodyBox = new Vector3(0.55f, 1.7f, 0.35f); + private const float BodyCentre = 0.95f; + + private GameObject m_instance; + + public void Apply(Player player, bool enable) + { + if (!enable || player == null) + { + if (m_instance != null && m_instance.activeSelf) m_instance.SetActive(false); + return; + } + + if (m_instance == null && !Build(player)) return; + if (!m_instance.activeSelf) m_instance.SetActive(true); + } + + private static bool warned; + + private bool Build(Player player) + { + GameObject draugr = PrefabManager.Cache.GetPrefab("Draugr"); + ParticleSystem source = null; + if (draugr != null) + { + foreach (ParticleSystem ps in draugr.GetComponentsInChildren(true)) + { + string name = ps.gameObject.name.ToLower(); + if (!ps.main.loop || name.Contains("flies") || name.Contains("drip") || name.Contains("drop") || + name.Contains("rain") || name.Contains("splash")) continue; + source = ps; + break; + } + } + + if (source == null) + { + if (!warned) + { + warned = true; + Jotunn.Logger.LogWarning("[Skeleton] No looping smoke found on 'Draugr'; the Summon on Kill aura stays off."); + } + return false; + } + + m_instance = BorrowEffect(source.gameObject, player.transform, "SkeletonRaisingAura", false, "Skeleton"); + if (m_instance == null) return false; + + m_instance.transform.localPosition = new Vector3(0f, BodyCentre, 0f); + m_instance.transform.localRotation = Quaternion.identity; + m_instance.transform.localScale = Vector3.one; + + foreach (ParticleSystem ps in m_instance.GetComponentsInChildren(true)) + { + ParticleSystem.MainModule main = ps.main; + main.startColor = new ParticleSystem.MinMaxGradient(Smoke); + // World space, so the smoke stays behind as the body moves, like a trail. + main.simulationSpace = ParticleSystemSimulationSpace.World; + main.scalingMode = ParticleSystemScalingMode.Hierarchy; + + ParticleSystem.ShapeModule shape = ps.shape; + shape.enabled = true; + shape.shapeType = ParticleSystemShapeType.Box; + shape.scale = BodyBox; + shape.position = Vector3.zero; + shape.rotation = Vector3.zero; + + // The Draugr's tint over a particle's life would put its green back; keep the + // fade (alpha) and drop the colour. + ParticleSystem.ColorOverLifetimeModule col = ps.colorOverLifetime; + if (col.enabled) + { + Gradient faded = new Gradient(); + faded.SetKeys(new[] { new GradientColorKey(Color.white, 0f), new GradientColorKey(Color.white, 1f) }, + col.color.gradient != null ? col.color.gradient.alphaKeys + : new[] { new GradientAlphaKey(1f, 0f), new GradientAlphaKey(0f, 1f) }); + col.color = new ParticleSystem.MinMaxGradient(faded); + } + } + + // The shader decides whether a dark tint can show at all: an additive one adds + // nothing for black. If the aura is invisible in game, this line says why. + Renderer smokeRenderer = m_instance.GetComponentInChildren(true); + Material smokeMaterial = smokeRenderer != null ? smokeRenderer.sharedMaterial : null; + Jotunn.Logger.LogInfo($"[Skeleton] Summon on Kill aura built from 'Draugr/{source.gameObject.name}', " + + $"material '{(smokeMaterial != null ? smokeMaterial.name : "none")}', " + + $"shader '{(smokeMaterial != null && smokeMaterial.shader != null ? smokeMaterial.shader.name : "none")}'."); + return true; + } + } + /// /// One player's burning skull. Cosmetic only - it deals nothing and blocks nothing. /// diff --git a/JotunnModStub/Translations/English/messages.json b/JotunnModStub/Translations/English/messages.json index 92fd052..1edf32c 100644 --- a/JotunnModStub/Translations/English/messages.json +++ b/JotunnModStub/Translations/English/messages.json @@ -203,7 +203,7 @@ "rov_msg_warvulture_vulture_spirals_down": "The vulture spirals down.", "rov_msg_boneship_no_shore": "No shore in reach. They stay at the oars.", "rov_msg_boneship_sunk": "The ship goes down, and $1 go with it.", - "rov_msg_skeleton_summon_on": "Summon on Kill: on. The dead will rise for you.", - "rov_msg_skeleton_summon_off": "Summon on Kill: off. The dead stay down.", + "rov_msg_skeleton_summon_on": "Thy dead shall rise again.", + "rov_msg_skeleton_summon_off": "Raising... nevermore.", "rov_msg_skeleton_summon_locked": "Summon on Kill awakens once The Queen falls." } diff --git a/JotunnModStub/Translations/Italian/messages.json b/JotunnModStub/Translations/Italian/messages.json index 1e1ee27..20caf0b 100644 --- a/JotunnModStub/Translations/Italian/messages.json +++ b/JotunnModStub/Translations/Italian/messages.json @@ -203,7 +203,7 @@ "rov_msg_warvulture_vulture_spirals_down": "L'avvoltoio scende a spirale.", "rov_msg_boneship_no_shore": "Nessuna riva a portata. Restano ai remi.", "rov_msg_boneship_sunk": "La nave affonda, e con lei $1.", - "rov_msg_skeleton_summon_on": "Evoca all'uccisione: attiva. I morti si alzeranno per te.", - "rov_msg_skeleton_summon_off": "Evoca all'uccisione: disattiva. I morti restano a terra.", + "rov_msg_skeleton_summon_on": "I tuoi morti risorgeranno ancora.", + "rov_msg_skeleton_summon_off": "Risorgere... mai più.", "rov_msg_skeleton_summon_locked": "Evoca all'uccisione si risveglia quando cade la Regina." } diff --git a/JotunnModStub/Translations/Russian/messages.json b/JotunnModStub/Translations/Russian/messages.json index 128bd9a..5b0f03e 100644 --- a/JotunnModStub/Translations/Russian/messages.json +++ b/JotunnModStub/Translations/Russian/messages.json @@ -203,7 +203,7 @@ "rov_msg_warvulture_vulture_spirals_down": "Стервятник кружит, спускаясь по спирали.", "rov_msg_boneship_no_shore": "Берега не видно. Они остаются на веслах.", "rov_msg_boneship_sunk": "Корабль идет ко дну, и $1 вместе с ним.", - "rov_msg_skeleton_summon_on": "Призыв при убийстве: включён. Мёртвые восстанут ради тебя.", - "rov_msg_skeleton_summon_off": "Призыв при убийстве: выключен. Мёртвые остаются лежать.", + "rov_msg_skeleton_summon_on": "Твои мёртвые вновь восстанут.", + "rov_msg_skeleton_summon_off": "Восстание... никогда более.", "rov_msg_skeleton_summon_locked": "Призыв при убийстве пробудится, когда падёт Королева." } diff --git a/JotunnModStub/ZdoVisualSync.cs b/JotunnModStub/ZdoVisualSync.cs index 4f1326f..241de90 100644 --- a/JotunnModStub/ZdoVisualSync.cs +++ b/JotunnModStub/ZdoVisualSync.cs @@ -41,6 +41,7 @@ namespace RacesOfValheim private GameObject m_fireAuraVFX = null; private GameObject m_draughAuraVFX = null; private readonly SkeletonVisuals.HeadFlame m_skeletonHeadFlame = new SkeletonVisuals.HeadFlame(); + private readonly SkeletonVisuals.RaisingAura m_skeletonRaisingAura = new SkeletonVisuals.RaisingAura(); private void Awake() { @@ -169,6 +170,7 @@ namespace RacesOfValheim // The burning skull, grown locally for whoever we are looking at. The tier is on the // ZDO, so this client can work out for itself whether they should be alight. m_skeletonHeadFlame.Apply(m_player, SkeletonConfig.HeadFireVFXEnabled.Value && SkeletonConfig.BodyModelEnabled.Value && SkeletonVisuals.GetModel(m_player, state) == SkeletonProgression.FireModel); + m_skeletonRaisingAura.Apply(m_player, SkeletonConfig.RaiseDeadAura.Value && nview.GetZDO().GetBool(SkeletonVisuals.RaisingZdoKey, false)); // Apply Scale Vector3 targetScale = rules.ScaleMultiplier; @@ -273,6 +275,7 @@ namespace RacesOfValheim SkeletonVisuals.EnsureFireAura(m_player, false, ref m_fireAuraVFX); DraughVisuals.EnsureAura(m_player, false, ref m_draughAuraVFX); m_skeletonHeadFlame.Apply(m_player, false); + m_skeletonRaisingAura.Apply(m_player, false); // Takes the crown off a Trenta who has died or changed race; a no-op for everyone else. TrentaVisuals.ApplyCrown(m_player); From 3591b7e375d071654a40e1de5c63572dca02e2e3 Mon Sep 17 00:00:00 2001 From: kanym Date: Sat, 24 Oct 2026 15:44:16 +0200 Subject: [PATCH 061/163] fix(skeleton): the Summon on Kill aura borrows the torch smoke The Draugr's evil_smoke is on 'Lux Lit Particles/ Bumped' and showed nothing in game once tinted dark. The torch's own Smoke, from the prefab the head flame burns from, is the grey everyone sees above a torch; darkened to (0.08, 0.08, 0.09) at 0.45 alpha. --- JotunnModStub/Skeleton/SkeletonVisuals.cs | 32 ++++++++++++----------- 1 file changed, 17 insertions(+), 15 deletions(-) diff --git a/JotunnModStub/Skeleton/SkeletonVisuals.cs b/JotunnModStub/Skeleton/SkeletonVisuals.cs index aa22629..ba7faee 100644 --- a/JotunnModStub/Skeleton/SkeletonVisuals.cs +++ b/JotunnModStub/Skeleton/SkeletonVisuals.cs @@ -442,8 +442,8 @@ namespace RacesOfValheim /// of the indicator, beside the Raise the Dead icon, so the community can pick either or /// both. Cosmetic only. /// - /// The smoke is the Draugr's own looping one, the same particle DraughVisuals.BuildAura - /// borrows, cloned through BorrowEffect and tinted near-black. It emits from a box the + /// The smoke is the torch's own (see Build for why not the Draugr's), cloned through + /// BorrowEffect and tinted near-black. It emits from a box the /// size of the body rather than from one point, so it comes off the arms and legs too. /// A mesh-shaped emitter would hug the body closer, but only works on a readable mesh. /// @@ -451,7 +451,8 @@ namespace RacesOfValheim /// public class RaisingAura { - private static readonly Color Smoke = new Color(0.06f, 0.06f, 0.07f, 0.35f); + // The torch smoke is (0.35, 0.35, 0.35, 0.21); darker and a little thicker than that. + private static readonly Color Smoke = new Color(0.08f, 0.08f, 0.09f, 0.45f); private static readonly Vector3 BodyBox = new Vector3(0.55f, 1.7f, 0.35f); private const float BodyCentre = 0.95f; @@ -473,17 +474,18 @@ namespace RacesOfValheim private bool Build(Player player) { - GameObject draugr = PrefabManager.Cache.GetPrefab("Draugr"); + // The torch's own 'Smoke', from the same prefab the head flame burns from. The + // Draugr's evil_smoke was tried first: its material is on 'Lux Lit Particles/ + // Bumped', which takes its look from the material and the scene light, so a dark + // tint on it showed nothing in game. The torch smoke is the grey everyone sees + // above a torch, so darkening it has something to darken. + GameObject torch = ResolveFlameSource(); ParticleSystem source = null; - if (draugr != null) + if (torch != null) { - foreach (ParticleSystem ps in draugr.GetComponentsInChildren(true)) + foreach (ParticleSystem ps in torch.GetComponentsInChildren(true)) { - string name = ps.gameObject.name.ToLower(); - if (!ps.main.loop || name.Contains("flies") || name.Contains("drip") || name.Contains("drop") || - name.Contains("rain") || name.Contains("splash")) continue; - source = ps; - break; + if (ps.gameObject.name.ToLower().Contains("smoke")) { source = ps; break; } } } @@ -492,7 +494,7 @@ namespace RacesOfValheim if (!warned) { warned = true; - Jotunn.Logger.LogWarning("[Skeleton] No looping smoke found on 'Draugr'; the Summon on Kill aura stays off."); + Jotunn.Logger.LogWarning("[Skeleton] No 'Smoke' particle on the torch; the Summon on Kill aura stays off."); } return false; } @@ -519,8 +521,8 @@ namespace RacesOfValheim shape.position = Vector3.zero; shape.rotation = Vector3.zero; - // The Draugr's tint over a particle's life would put its green back; keep the - // fade (alpha) and drop the colour. + // A tint over the particle's life would put the source's own colour back; keep + // the fade (alpha) and drop the colour. ParticleSystem.ColorOverLifetimeModule col = ps.colorOverLifetime; if (col.enabled) { @@ -536,7 +538,7 @@ namespace RacesOfValheim // nothing for black. If the aura is invisible in game, this line says why. Renderer smokeRenderer = m_instance.GetComponentInChildren(true); Material smokeMaterial = smokeRenderer != null ? smokeRenderer.sharedMaterial : null; - Jotunn.Logger.LogInfo($"[Skeleton] Summon on Kill aura built from 'Draugr/{source.gameObject.name}', " + + Jotunn.Logger.LogInfo($"[Skeleton] Summon on Kill aura built from '{torch.name}/{source.gameObject.name}', " + $"material '{(smokeMaterial != null ? smokeMaterial.name : "none")}', " + $"shader '{(smokeMaterial != null && smokeMaterial.shader != null ? smokeMaterial.shader.name : "none")}'."); return true; From e41f7b610e2dbe0789204620f2fa12f3bbd8ba56 Mon Sep 17 00:00:00 2001 From: kanym Date: Sat, 24 Oct 2026 15:50:05 +0200 Subject: [PATCH 062/163] revert(skeleton): drop the Summon on Kill aura, keep the icon Neither the Draugr's evil_smoke nor the torch smoke showed in game once tinted dark. The Raise the Dead icon stays, with its per-player switch. --- JotunnModStub/Skeleton/SkeletonConfig.cs | 5 +- JotunnModStub/Skeleton/SkeletonRace.cs | 16 ---- JotunnModStub/Skeleton/SkeletonVisuals.cs | 111 ---------------------- JotunnModStub/ZdoVisualSync.cs | 3 - 4 files changed, 1 insertion(+), 134 deletions(-) diff --git a/JotunnModStub/Skeleton/SkeletonConfig.cs b/JotunnModStub/Skeleton/SkeletonConfig.cs index 7b4a2b9..62c01fc 100644 --- a/JotunnModStub/Skeleton/SkeletonConfig.cs +++ b/JotunnModStub/Skeleton/SkeletonConfig.cs @@ -47,7 +47,6 @@ namespace RacesOfValheim public static ConfigEntry HeadFireVFXEnabled; public static ConfigEntry BodyModelEnabled; public static ConfigEntry RaiseDeadIcon; - public static ConfigEntry RaiseDeadAura; public static void Bind(ConfigFile config) { @@ -74,7 +73,7 @@ namespace RacesOfValheim // G is the first ability key of every race that has one; the Skeleton had none. const string keybinds = "Skeleton - Keybinds"; SummonToggleKey = config.Bind(keybinds, "Toggle Summon on Kill", new KeyboardShortcut(KeyCode.G), - "Turns raising a skeleton from each kill on and off (The Queen and later). While it is on, the Raise the Dead icon and a faint dark aura show it (see Skeleton - Visuals)."); + "Turns raising a skeleton from each kill on and off (The Queen and later). The Raise the Dead icon shows while it is on."); const string resurrection = "Skeleton - Resurrection"; ResurrectionCooldown = config.Bind(resurrection, "Cooldown", 300f, @@ -87,8 +86,6 @@ namespace RacesOfValheim new ConfigDescription("Whether Skeleton players wear the skeleton body. Turn it off if you use a player model mod (EnhancedValheimVRM and the like): Skeletons then keep the vanilla viking body, so the replacement model shows without bones clipping through it. Abilities are unchanged. Client-side, like the option above: it applies to every Skeleton you see, yourself included, and changes nothing for other players.")); RaiseDeadIcon = config.Bind(visuals, "Raise the Dead Icon", true, new ConfigDescription("Shows the Raise the Dead status icon while your Summon on Kill is on.")); - RaiseDeadAura = config.Bind(visuals, "Raise the Dead Aura", true, - new ConfigDescription("A faint dark smoke rises off a Skeleton whose Summon on Kill is on. Client-side: turning it off hides it on yourself and on every other Skeleton you see.")); } } } diff --git a/JotunnModStub/Skeleton/SkeletonRace.cs b/JotunnModStub/Skeleton/SkeletonRace.cs index b5fb170..69e8712 100644 --- a/JotunnModStub/Skeleton/SkeletonRace.cs +++ b/JotunnModStub/Skeleton/SkeletonRace.cs @@ -108,20 +108,6 @@ namespace RacesOfValheim bool on = rules.SummonOnKill && SummonOnKillEnabled; SetRaiseDeadIcon(player, on && SkeletonConfig.RaiseDeadIcon.Value); - Instance?.raisingAura.Apply(player, on && SkeletonConfig.RaiseDeadAura.Value); - SetRaisingFlag(player, on); - } - - private readonly SkeletonVisuals.RaisingAura raisingAura = new SkeletonVisuals.RaisingAura(); - - /// Owner only, and only on a change, so other clients can draw the aura. - private static void SetRaisingFlag(Player player, bool on) - { - ZNetView nview = player.GetComponent(); - if (nview == null || !nview.IsValid() || !nview.IsOwner()) return; - - ZDO zdo = nview.GetZDO(); - if (zdo.GetBool(SkeletonVisuals.RaisingZdoKey, false) != on) zdo.Set(SkeletonVisuals.RaisingZdoKey, on); } private static void SetRaiseDeadIcon(Player player, bool on) @@ -355,8 +341,6 @@ namespace RacesOfValheim headFlame.Apply(Player.m_localPlayer, false); RestoreJawBone(); SetRaiseDeadIcon(Player.m_localPlayer, false); - raisingAura.Apply(Player.m_localPlayer, false); - SetRaisingFlag(Player.m_localPlayer, false); if (Player.m_localPlayer.transform.localScale != Vector3.one) { diff --git a/JotunnModStub/Skeleton/SkeletonVisuals.cs b/JotunnModStub/Skeleton/SkeletonVisuals.cs index ba7faee..e91963c 100644 --- a/JotunnModStub/Skeleton/SkeletonVisuals.cs +++ b/JotunnModStub/Skeleton/SkeletonVisuals.cs @@ -434,117 +434,6 @@ namespace RacesOfValheim aura = null; } - /// The owner's Summon on Kill switch, for every other client to read. - public const string RaisingZdoKey = "RacesOfValheim_SkeletonRaising"; - - /// - /// A faint dark smoke rising off the whole body while Summon on Kill is on: the other half - /// of the indicator, beside the Raise the Dead icon, so the community can pick either or - /// both. Cosmetic only. - /// - /// The smoke is the torch's own (see Build for why not the Draugr's), cloned through - /// BorrowEffect and tinted near-black. It emits from a box the - /// size of the body rather than from one point, so it comes off the arms and legs too. - /// A mesh-shaped emitter would hug the body closer, but only works on a readable mesh. - /// - /// Held per player, like HeadFlame. Call Apply every frame; it builds once. - /// - public class RaisingAura - { - // The torch smoke is (0.35, 0.35, 0.35, 0.21); darker and a little thicker than that. - private static readonly Color Smoke = new Color(0.08f, 0.08f, 0.09f, 0.45f); - private static readonly Vector3 BodyBox = new Vector3(0.55f, 1.7f, 0.35f); - private const float BodyCentre = 0.95f; - - private GameObject m_instance; - - public void Apply(Player player, bool enable) - { - if (!enable || player == null) - { - if (m_instance != null && m_instance.activeSelf) m_instance.SetActive(false); - return; - } - - if (m_instance == null && !Build(player)) return; - if (!m_instance.activeSelf) m_instance.SetActive(true); - } - - private static bool warned; - - private bool Build(Player player) - { - // The torch's own 'Smoke', from the same prefab the head flame burns from. The - // Draugr's evil_smoke was tried first: its material is on 'Lux Lit Particles/ - // Bumped', which takes its look from the material and the scene light, so a dark - // tint on it showed nothing in game. The torch smoke is the grey everyone sees - // above a torch, so darkening it has something to darken. - GameObject torch = ResolveFlameSource(); - ParticleSystem source = null; - if (torch != null) - { - foreach (ParticleSystem ps in torch.GetComponentsInChildren(true)) - { - if (ps.gameObject.name.ToLower().Contains("smoke")) { source = ps; break; } - } - } - - if (source == null) - { - if (!warned) - { - warned = true; - Jotunn.Logger.LogWarning("[Skeleton] No 'Smoke' particle on the torch; the Summon on Kill aura stays off."); - } - return false; - } - - m_instance = BorrowEffect(source.gameObject, player.transform, "SkeletonRaisingAura", false, "Skeleton"); - if (m_instance == null) return false; - - m_instance.transform.localPosition = new Vector3(0f, BodyCentre, 0f); - m_instance.transform.localRotation = Quaternion.identity; - m_instance.transform.localScale = Vector3.one; - - foreach (ParticleSystem ps in m_instance.GetComponentsInChildren(true)) - { - ParticleSystem.MainModule main = ps.main; - main.startColor = new ParticleSystem.MinMaxGradient(Smoke); - // World space, so the smoke stays behind as the body moves, like a trail. - main.simulationSpace = ParticleSystemSimulationSpace.World; - main.scalingMode = ParticleSystemScalingMode.Hierarchy; - - ParticleSystem.ShapeModule shape = ps.shape; - shape.enabled = true; - shape.shapeType = ParticleSystemShapeType.Box; - shape.scale = BodyBox; - shape.position = Vector3.zero; - shape.rotation = Vector3.zero; - - // A tint over the particle's life would put the source's own colour back; keep - // the fade (alpha) and drop the colour. - ParticleSystem.ColorOverLifetimeModule col = ps.colorOverLifetime; - if (col.enabled) - { - Gradient faded = new Gradient(); - faded.SetKeys(new[] { new GradientColorKey(Color.white, 0f), new GradientColorKey(Color.white, 1f) }, - col.color.gradient != null ? col.color.gradient.alphaKeys - : new[] { new GradientAlphaKey(1f, 0f), new GradientAlphaKey(0f, 1f) }); - col.color = new ParticleSystem.MinMaxGradient(faded); - } - } - - // The shader decides whether a dark tint can show at all: an additive one adds - // nothing for black. If the aura is invisible in game, this line says why. - Renderer smokeRenderer = m_instance.GetComponentInChildren(true); - Material smokeMaterial = smokeRenderer != null ? smokeRenderer.sharedMaterial : null; - Jotunn.Logger.LogInfo($"[Skeleton] Summon on Kill aura built from '{torch.name}/{source.gameObject.name}', " + - $"material '{(smokeMaterial != null ? smokeMaterial.name : "none")}', " + - $"shader '{(smokeMaterial != null && smokeMaterial.shader != null ? smokeMaterial.shader.name : "none")}'."); - return true; - } - } - /// /// One player's burning skull. Cosmetic only - it deals nothing and blocks nothing. /// diff --git a/JotunnModStub/ZdoVisualSync.cs b/JotunnModStub/ZdoVisualSync.cs index 241de90..4f1326f 100644 --- a/JotunnModStub/ZdoVisualSync.cs +++ b/JotunnModStub/ZdoVisualSync.cs @@ -41,7 +41,6 @@ namespace RacesOfValheim private GameObject m_fireAuraVFX = null; private GameObject m_draughAuraVFX = null; private readonly SkeletonVisuals.HeadFlame m_skeletonHeadFlame = new SkeletonVisuals.HeadFlame(); - private readonly SkeletonVisuals.RaisingAura m_skeletonRaisingAura = new SkeletonVisuals.RaisingAura(); private void Awake() { @@ -170,7 +169,6 @@ namespace RacesOfValheim // The burning skull, grown locally for whoever we are looking at. The tier is on the // ZDO, so this client can work out for itself whether they should be alight. m_skeletonHeadFlame.Apply(m_player, SkeletonConfig.HeadFireVFXEnabled.Value && SkeletonConfig.BodyModelEnabled.Value && SkeletonVisuals.GetModel(m_player, state) == SkeletonProgression.FireModel); - m_skeletonRaisingAura.Apply(m_player, SkeletonConfig.RaiseDeadAura.Value && nview.GetZDO().GetBool(SkeletonVisuals.RaisingZdoKey, false)); // Apply Scale Vector3 targetScale = rules.ScaleMultiplier; @@ -275,7 +273,6 @@ namespace RacesOfValheim SkeletonVisuals.EnsureFireAura(m_player, false, ref m_fireAuraVFX); DraughVisuals.EnsureAura(m_player, false, ref m_draughAuraVFX); m_skeletonHeadFlame.Apply(m_player, false); - m_skeletonRaisingAura.Apply(m_player, false); // Takes the crown off a Trenta who has died or changed race; a no-op for everyone else. TrentaVisuals.ApplyCrown(m_player); From 18593ae1d365af7e88434032b27870b80470e994 Mon Sep 17 00:00:00 2001 From: kanym Date: Sat, 24 Oct 2026 16:36:52 +0200 Subject: [PATCH 063/163] balance(skeleton): lower max-health bonus in the early and middle game +25/+45/+65/+90/+125/+165/+215/+275 from no bosses to Fader, was +50/+80/+110/+140/+170/+200/+230/+275. A fresh Skeleton starts at 50 max health instead of 75; Fader stays at 300. Asked for by several players over three months, last by Jondar Korric. A Skeleton never eats and never spends stamina, so it ran well ahead of a fed viking. The hidden foods that carry its regeneration are picked to match the new totals, so early-tier regen drops with them. README progression updated; the compendium reads the value from code. --- JotunnModStub/Skeleton/SkeletonProgression.cs | 16 ++++++++-------- README.md | 14 +++++++------- 2 files changed, 15 insertions(+), 15 deletions(-) diff --git a/JotunnModStub/Skeleton/SkeletonProgression.cs b/JotunnModStub/Skeleton/SkeletonProgression.cs index 0045033..8d9b11f 100644 --- a/JotunnModStub/Skeleton/SkeletonProgression.cs +++ b/JotunnModStub/Skeleton/SkeletonProgression.cs @@ -7,15 +7,15 @@ namespace RacesOfValheim public static float GetMaxHealthBonus(int state) { if (state == 0) return 0f; - if (state == 1) return 50f; - if (state == 2) return 80f; - if (state == 3) return 110f; - if (state == 4) return 140f; - if (state == 5) return 170f; - if (state == 6) return 200f; - if (state == 7) return 230f; + if (state == 1) return 25f; + if (state == 2) return 45f; + if (state == 3) return 65f; + if (state == 4) return 90f; + if (state == 5) return 125f; + if (state == 6) return 165f; + if (state == 7) return 215f; if (state >= 8) return 275f; - return 50f; + return 25f; } public struct SkeletonRules diff --git a/README.md b/README.md index 9e09880..9332cc9 100644 --- a/README.md +++ b/README.md @@ -235,13 +235,13 @@ Right Mouse toggles flight. Glide towards aim, W = forward/climb, Shift+W = use
Skeleton Progression -- **Base:** +50 Max Health. Undead Diet (cannot eat normal food, no stamina bar). Lit eye sockets, in the colour of whichever skeleton your tier wears. -- **Eikthyr:** Poison Skeleton model, poison immunity, 5% lifesteal, +80 Max Health. -- **Elder:** 10% lifesteal, auto-stun 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. -- **Queen:** 30% lifesteal, summon on kill (max 3 skeletons), +230 Max Health. +- **Base:** +25 Max Health. Undead Diet (cannot eat normal food, no stamina bar). Lit eye sockets, in the colour of whichever skeleton your tier wears. +- **Eikthyr:** Poison Skeleton model, poison immunity, 5% lifesteal, +45 Max Health. +- **Elder:** 10% lifesteal, auto-stun first hit, +65 Max Health. +- **Bonemass:** 15% lifesteal, poison attacks, +90 Max Health. +- **Moder:** Fire Skeleton model, 20% lifesteal, fire aura, enhanced regen, +125 Max Health. +- **Yagluth:** 25% lifesteal, auto-resurrect, +165 Max Health. +- **Queen:** 30% lifesteal, summon on kill (max 3 skeletons), +215 Max Health. - **Fader:** 35% lifesteal, max 5 summons, +275 Max Health.
From 20dec64fa01cabecce1446156efdfe5a1db47a6e Mon Sep 17 00:00:00 2001 From: kanym Date: Sat, 24 Oct 2026 18:28:17 +0200 Subject: [PATCH 064/163] chore(release): v1.5.15 - Skeleton health rebalance, Auto-Resurrect fix, Summon on Kill toggle Skeleton max health is lower in the early and middle game, from 75 to 50 at the start and unchanged at Fader. Auto-Resurrect triggers only on a hit that would really kill, dedicated servers included. Summon on Kill toggles with G and shows a Raise the Dead icon while on. README: New in block, Queen line, changelog entry. --- JotunnModStub/Package/manifest.json | 2 +- JotunnModStub/RacesOfValheim.cs | 2 +- README.md | 11 ++++++++--- manifest.json | 2 +- 4 files changed, 11 insertions(+), 6 deletions(-) diff --git a/JotunnModStub/Package/manifest.json b/JotunnModStub/Package/manifest.json index 6c5a7ef..7418483 100644 --- a/JotunnModStub/Package/manifest.json +++ b/JotunnModStub/Package/manifest.json @@ -1,7 +1,7 @@ { "name": "RacesOfValheim", "description": "A Valheim mod that adds ten custom playable races (Aswid, Draugh, Dvergar, Fenrir, Furling, Skadi, Skeleton, Sverm, Trenta, Trol) each with unique abilities, traits, race stations and a deep boss-driven progression system.", - "version_number": "1.5.14", + "version_number": "1.5.15", "website_url": "", "dependencies": [ "denikson-BepInExPack_Valheim-5.4.2333", diff --git a/JotunnModStub/RacesOfValheim.cs b/JotunnModStub/RacesOfValheim.cs index 4ff8ec9..122655b 100644 --- a/JotunnModStub/RacesOfValheim.cs +++ b/JotunnModStub/RacesOfValheim.cs @@ -16,7 +16,7 @@ namespace RacesOfValheim { public const string PluginGUID = "com.nandor.racesofvalheim"; public const string PluginName = "Races Of Valheim"; - public const string PluginVersion = "1.5.14"; + public const string PluginVersion = "1.5.15"; private readonly Harmony harmony = new Harmony(PluginGUID); diff --git a/README.md b/README.md index 9332cc9..cb169ae 100644 --- a/README.md +++ b/README.md @@ -15,9 +15,9 @@ Support the mod: [Patreon — NandorTheModder](https://www.patreon.com/c/NandorT --- -## New in v1.5.14 +## New in v1.5.15 -A Fenrir's eyes now glow at night, brighter when a form is ready and yellow when the Cultist is back. Fenrir forms build adrenaline on every hit, Trenta can eat seeds with a full stomach, and the stamina bar comes back after leaving Aswid or Draugh. Full details in the [changelog](#v1514). +Skeleton round: max health is lower in the early and middle game (a fresh Skeleton starts at 50, Fader is unchanged), Auto-Resurrect fires only on a hit that would really kill you, and Summon on Kill can be switched on and off with G. Full details in the [changelog](#v1515). --- @@ -241,7 +241,7 @@ Right Mouse toggles flight. Glide towards aim, W = forward/climb, Shift+W = use - **Bonemass:** 15% lifesteal, poison attacks, +90 Max Health. - **Moder:** Fire Skeleton model, 20% lifesteal, fire aura, enhanced regen, +125 Max Health. - **Yagluth:** 25% lifesteal, auto-resurrect, +165 Max Health. -- **Queen:** 30% lifesteal, summon on kill (max 3 skeletons), +215 Max Health. +- **Queen:** 30% lifesteal, summon on kill (max 3 skeletons, toggle with G), +215 Max Health. - **Fader:** 35% lifesteal, max 5 summons, +275 Max Health. @@ -451,6 +451,11 @@ Both halves have an off switch under `Factions` in Configuration Manager: **Fact ## Changelog +### v1.5.15 +- **Balance - Skeleton max health:** lower in the early and middle game. The bonus over the base 25 is now +25 / +45 / +65 / +90 / +125 / +165 / +215 / +275, from no bosses to Fader (it was +50 / +80 / +110 / +140 / +170 / +200 / +230 / +275). A fresh Skeleton starts at 50 instead of 75; from Yagluth on the gap closes, and Fader is unchanged at 300. A Skeleton never needs food and never spends stamina, so it was well ahead of a fed viking at every tier. Thanks to Jondar Korric and everyone else who asked for this. +- **Fix - Auto-Resurrect on any hit:** a Skeleton's Auto-Resurrect now triggers only on a hit that would actually kill you. It used to compare the raw hit, before armour and blocking, with its poison and fire counted all at once, so with good armour it fired on almost any hit. On dedicated servers it could also miss a real deathblow when the server or another player controlled the attacker. Thanks to akira for the report. +- **New - Summon on Kill toggle:** turn Summon on Kill on and off with G (`Skeleton - Keybinds`), or from the gamepad radial: *"Thy dead shall rise again."* / *"Raising... nevermore."* While it's on, a "Raise the Dead" icon with the Dead Raiser's picture shows in the status bar; hide it with `Raise the Dead Icon` under `Skeleton - Visuals`. Your choice is saved with your character. Thanks to akira for the idea. + ### v1.5.14 - **New - Fenrir night eyes:** at night a Fenrir's eyes glow in the Fenring's orange, the way a wolf's eyes catch the light. Faint while no form is ready, bright when one is, and yellow when the Cultist is back from its cooldown. Other players see it too. Under `Fenrir - Appearance` each player can turn off the glow or the "Ready!" message for themselves. Thanks to lexsonn for the idea. - **Fix - Fenrir forms and adrenaline:** in Wolf, Ulv, Fenring and Cultist form, hits now build adrenaline the way a weapon does. Before, only staggering an enemy did, so Lox, Tar, Brutes and Furlings gave almost none. The Cultist's fire breath builds it too, about one hit's worth per second. Thanks to lexsonn for the report. diff --git a/manifest.json b/manifest.json index 6c5a7ef..7418483 100644 --- a/manifest.json +++ b/manifest.json @@ -1,7 +1,7 @@ { "name": "RacesOfValheim", "description": "A Valheim mod that adds ten custom playable races (Aswid, Draugh, Dvergar, Fenrir, Furling, Skadi, Skeleton, Sverm, Trenta, Trol) each with unique abilities, traits, race stations and a deep boss-driven progression system.", - "version_number": "1.5.14", + "version_number": "1.5.15", "website_url": "", "dependencies": [ "denikson-BepInExPack_Valheim-5.4.2333", From 0a843bad415f99cb306a5e9e908ade29d991a5ff Mon Sep 17 00:00:00 2001 From: kanym Date: Sat, 24 Oct 2026 23:53:53 +0200 Subject: [PATCH 065/163] fix(skeleton): the Summon on Kill "on" line is "Thy shall raise again." MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit As written by the author; Italian "Tu rialzerai ancora.", Russian "Ты вновь поднимешь.". README changelog line too. --- JotunnModStub/Translations/English/messages.json | 2 +- JotunnModStub/Translations/Italian/messages.json | 2 +- JotunnModStub/Translations/Russian/messages.json | 2 +- README.md | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/JotunnModStub/Translations/English/messages.json b/JotunnModStub/Translations/English/messages.json index 1edf32c..a764b92 100644 --- a/JotunnModStub/Translations/English/messages.json +++ b/JotunnModStub/Translations/English/messages.json @@ -203,7 +203,7 @@ "rov_msg_warvulture_vulture_spirals_down": "The vulture spirals down.", "rov_msg_boneship_no_shore": "No shore in reach. They stay at the oars.", "rov_msg_boneship_sunk": "The ship goes down, and $1 go with it.", - "rov_msg_skeleton_summon_on": "Thy dead shall rise again.", + "rov_msg_skeleton_summon_on": "Thy shall raise again.", "rov_msg_skeleton_summon_off": "Raising... nevermore.", "rov_msg_skeleton_summon_locked": "Summon on Kill awakens once The Queen falls." } diff --git a/JotunnModStub/Translations/Italian/messages.json b/JotunnModStub/Translations/Italian/messages.json index 20caf0b..2c6ed4c 100644 --- a/JotunnModStub/Translations/Italian/messages.json +++ b/JotunnModStub/Translations/Italian/messages.json @@ -203,7 +203,7 @@ "rov_msg_warvulture_vulture_spirals_down": "L'avvoltoio scende a spirale.", "rov_msg_boneship_no_shore": "Nessuna riva a portata. Restano ai remi.", "rov_msg_boneship_sunk": "La nave affonda, e con lei $1.", - "rov_msg_skeleton_summon_on": "I tuoi morti risorgeranno ancora.", + "rov_msg_skeleton_summon_on": "Tu rialzerai ancora.", "rov_msg_skeleton_summon_off": "Risorgere... mai più.", "rov_msg_skeleton_summon_locked": "Evoca all'uccisione si risveglia quando cade la Regina." } diff --git a/JotunnModStub/Translations/Russian/messages.json b/JotunnModStub/Translations/Russian/messages.json index 5b0f03e..c4f2975 100644 --- a/JotunnModStub/Translations/Russian/messages.json +++ b/JotunnModStub/Translations/Russian/messages.json @@ -203,7 +203,7 @@ "rov_msg_warvulture_vulture_spirals_down": "Стервятник кружит, спускаясь по спирали.", "rov_msg_boneship_no_shore": "Берега не видно. Они остаются на веслах.", "rov_msg_boneship_sunk": "Корабль идет ко дну, и $1 вместе с ним.", - "rov_msg_skeleton_summon_on": "Твои мёртвые вновь восстанут.", + "rov_msg_skeleton_summon_on": "Ты вновь поднимешь.", "rov_msg_skeleton_summon_off": "Восстание... никогда более.", "rov_msg_skeleton_summon_locked": "Призыв при убийстве пробудится, когда падёт Королева." } diff --git a/README.md b/README.md index cb169ae..35bd680 100644 --- a/README.md +++ b/README.md @@ -454,7 +454,7 @@ Both halves have an off switch under `Factions` in Configuration Manager: **Fact ### v1.5.15 - **Balance - Skeleton max health:** lower in the early and middle game. The bonus over the base 25 is now +25 / +45 / +65 / +90 / +125 / +165 / +215 / +275, from no bosses to Fader (it was +50 / +80 / +110 / +140 / +170 / +200 / +230 / +275). A fresh Skeleton starts at 50 instead of 75; from Yagluth on the gap closes, and Fader is unchanged at 300. A Skeleton never needs food and never spends stamina, so it was well ahead of a fed viking at every tier. Thanks to Jondar Korric and everyone else who asked for this. - **Fix - Auto-Resurrect on any hit:** a Skeleton's Auto-Resurrect now triggers only on a hit that would actually kill you. It used to compare the raw hit, before armour and blocking, with its poison and fire counted all at once, so with good armour it fired on almost any hit. On dedicated servers it could also miss a real deathblow when the server or another player controlled the attacker. Thanks to akira for the report. -- **New - Summon on Kill toggle:** turn Summon on Kill on and off with G (`Skeleton - Keybinds`), or from the gamepad radial: *"Thy dead shall rise again."* / *"Raising... nevermore."* While it's on, a "Raise the Dead" icon with the Dead Raiser's picture shows in the status bar; hide it with `Raise the Dead Icon` under `Skeleton - Visuals`. Your choice is saved with your character. Thanks to akira for the idea. +- **New - Summon on Kill toggle:** turn Summon on Kill on and off with G (`Skeleton - Keybinds`), or from the gamepad radial: *"Thy shall raise again."* / *"Raising... nevermore."* While it's on, a "Raise the Dead" icon with the Dead Raiser's picture shows in the status bar; hide it with `Raise the Dead Icon` under `Skeleton - Visuals`. Your choice is saved with your character. Thanks to akira for the idea. ### v1.5.14 - **New - Fenrir night eyes:** at night a Fenrir's eyes glow in the Fenring's orange, the way a wolf's eyes catch the light. Faint while no form is ready, bright when one is, and yellow when the Cultist is back from its cooldown. Other players see it too. Under `Fenrir - Appearance` each player can turn off the glow or the "Ready!" message for themselves. Thanks to lexsonn for the idea. From 9e9790d1e99730970e2e30f3e3b632f058f48dd4 Mon Sep 17 00:00:00 2001 From: kanym Date: Sat, 24 Oct 2026 23:55:26 +0200 Subject: [PATCH 066/163] docs(readme): the v1.5.15 entry quotes the line that shipped The new line goes out in v1.5.16 and is listed for that release. --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 35bd680..cb169ae 100644 --- a/README.md +++ b/README.md @@ -454,7 +454,7 @@ Both halves have an off switch under `Factions` in Configuration Manager: **Fact ### v1.5.15 - **Balance - Skeleton max health:** lower in the early and middle game. The bonus over the base 25 is now +25 / +45 / +65 / +90 / +125 / +165 / +215 / +275, from no bosses to Fader (it was +50 / +80 / +110 / +140 / +170 / +200 / +230 / +275). A fresh Skeleton starts at 50 instead of 75; from Yagluth on the gap closes, and Fader is unchanged at 300. A Skeleton never needs food and never spends stamina, so it was well ahead of a fed viking at every tier. Thanks to Jondar Korric and everyone else who asked for this. - **Fix - Auto-Resurrect on any hit:** a Skeleton's Auto-Resurrect now triggers only on a hit that would actually kill you. It used to compare the raw hit, before armour and blocking, with its poison and fire counted all at once, so with good armour it fired on almost any hit. On dedicated servers it could also miss a real deathblow when the server or another player controlled the attacker. Thanks to akira for the report. -- **New - Summon on Kill toggle:** turn Summon on Kill on and off with G (`Skeleton - Keybinds`), or from the gamepad radial: *"Thy shall raise again."* / *"Raising... nevermore."* While it's on, a "Raise the Dead" icon with the Dead Raiser's picture shows in the status bar; hide it with `Raise the Dead Icon` under `Skeleton - Visuals`. Your choice is saved with your character. Thanks to akira for the idea. +- **New - Summon on Kill toggle:** turn Summon on Kill on and off with G (`Skeleton - Keybinds`), or from the gamepad radial: *"Thy dead shall rise again."* / *"Raising... nevermore."* While it's on, a "Raise the Dead" icon with the Dead Raiser's picture shows in the status bar; hide it with `Raise the Dead Icon` under `Skeleton - Visuals`. Your choice is saved with your character. Thanks to akira for the idea. ### v1.5.14 - **New - Fenrir night eyes:** at night a Fenrir's eyes glow in the Fenring's orange, the way a wolf's eyes catch the light. Faint while no form is ready, bright when one is, and yellow when the Cultist is back from its cooldown. Other players see it too. Under `Fenrir - Appearance` each player can turn off the glow or the "Ready!" message for themselves. Thanks to lexsonn for the idea. From 3f8cf1ee27b0ee48badd7fdd34d6ffcea0bce9e2 Mon Sep 17 00:00:00 2001 From: Ferdinando Date: Sun, 25 Oct 2026 17:38:28 +0100 Subject: [PATCH 067/163] feat(alfar): v1.6.0 - the Alfar, an eleventh race Grey, tall and thin, with black eyes. Eitr is armour and fuel (shield, diet, soft fall, levitation), Heimkall sends a lethal blow home at one health every 20 minutes. Caster powers from Skrid to the archon Sameining, with on-screen cooldowns. Automated base around the Ljoskjarne: drones, three constructs, crystals, Ljosgard, Prismavard. Compendium page in EN/IT/RU. README: New in block, race section, progression, station line, changelog. Co-Authored-By: Claude Sonnet 5.5 --- JotunnModStub/Alfar/AlfarArchon.cs | 176 ++ JotunnModStub/Alfar/AlfarChests.cs | 134 ++ JotunnModStub/Alfar/AlfarCommands.cs | 110 + JotunnModStub/Alfar/AlfarConfig.cs | 159 ++ JotunnModStub/Alfar/AlfarConstructs.cs | 397 ++++ JotunnModStub/Alfar/AlfarDroneAI.cs | 1950 +++++++++++++++++ JotunnModStub/Alfar/AlfarDrones.cs | 365 +++ JotunnModStub/Alfar/AlfarEitr.cs | 166 ++ JotunnModStub/Alfar/AlfarHeimkall.cs | 171 ++ JotunnModStub/Alfar/AlfarLevitation.cs | 120 + JotunnModStub/Alfar/AlfarLjosgard.cs | 108 + JotunnModStub/Alfar/AlfarMark.cs | 149 ++ JotunnModStub/Alfar/AlfarMiners.cs | 104 + JotunnModStub/Alfar/AlfarNexus.cs | 576 +++++ JotunnModStub/Alfar/AlfarNexusConfig.cs | 144 ++ JotunnModStub/Alfar/AlfarNexusStore.cs | 171 ++ JotunnModStub/Alfar/AlfarPatches.cs | 149 ++ JotunnModStub/Alfar/AlfarPowerConfig.cs | 170 ++ JotunnModStub/Alfar/AlfarPowers.cs | 616 ++++++ JotunnModStub/Alfar/AlfarProbe.cs | 434 ++++ JotunnModStub/Alfar/AlfarRace.cs | 40 + JotunnModStub/Alfar/AlfarStatusEffects.cs | 169 ++ JotunnModStub/Alfar/AlfarTowers.cs | 239 ++ JotunnModStub/Alfar/AlfarVisuals.cs | 495 +++++ JotunnModStub/ConfigSync.cs | 1 + JotunnModStub/Package/manifest.json | 2 +- JotunnModStub/RaceCompendium.cs | 57 +- JotunnModStub/RaceRadial.cs | 13 + JotunnModStub/RaceScale.cs | 2 + JotunnModStub/RaceStationLock.cs | 5 + JotunnModStub/RacesOfValheim.cs | 51 +- .../Translations/English/compendium.json | 24 + JotunnModStub/Translations/English/items.json | 35 + .../Translations/English/messages.json | 30 +- JotunnModStub/Translations/English/races.json | 4 +- .../Translations/English/status_effects.json | 12 +- .../Translations/Italian/compendium.json | 24 + JotunnModStub/Translations/Italian/items.json | 35 + .../Translations/Italian/messages.json | 30 +- JotunnModStub/Translations/Italian/races.json | 4 +- .../Translations/Italian/status_effects.json | 12 +- .../Translations/Russian/compendium.json | 24 + JotunnModStub/Translations/Russian/items.json | 35 + .../Translations/Russian/messages.json | 30 +- JotunnModStub/Translations/Russian/races.json | 4 +- .../Translations/Russian/status_effects.json | 12 +- README.md | 35 +- manifest.json | 2 +- 48 files changed, 7779 insertions(+), 16 deletions(-) create mode 100644 JotunnModStub/Alfar/AlfarArchon.cs create mode 100644 JotunnModStub/Alfar/AlfarChests.cs create mode 100644 JotunnModStub/Alfar/AlfarCommands.cs create mode 100644 JotunnModStub/Alfar/AlfarConfig.cs create mode 100644 JotunnModStub/Alfar/AlfarConstructs.cs create mode 100644 JotunnModStub/Alfar/AlfarDroneAI.cs create mode 100644 JotunnModStub/Alfar/AlfarDrones.cs create mode 100644 JotunnModStub/Alfar/AlfarEitr.cs create mode 100644 JotunnModStub/Alfar/AlfarHeimkall.cs create mode 100644 JotunnModStub/Alfar/AlfarLevitation.cs create mode 100644 JotunnModStub/Alfar/AlfarLjosgard.cs create mode 100644 JotunnModStub/Alfar/AlfarMark.cs create mode 100644 JotunnModStub/Alfar/AlfarMiners.cs create mode 100644 JotunnModStub/Alfar/AlfarNexus.cs create mode 100644 JotunnModStub/Alfar/AlfarNexusConfig.cs create mode 100644 JotunnModStub/Alfar/AlfarNexusStore.cs create mode 100644 JotunnModStub/Alfar/AlfarPatches.cs create mode 100644 JotunnModStub/Alfar/AlfarPowerConfig.cs create mode 100644 JotunnModStub/Alfar/AlfarPowers.cs create mode 100644 JotunnModStub/Alfar/AlfarProbe.cs create mode 100644 JotunnModStub/Alfar/AlfarRace.cs create mode 100644 JotunnModStub/Alfar/AlfarStatusEffects.cs create mode 100644 JotunnModStub/Alfar/AlfarTowers.cs create mode 100644 JotunnModStub/Alfar/AlfarVisuals.cs diff --git a/JotunnModStub/Alfar/AlfarArchon.cs b/JotunnModStub/Alfar/AlfarArchon.cs new file mode 100644 index 0000000..0be4415 --- /dev/null +++ b/JotunnModStub/Alfar/AlfarArchon.cs @@ -0,0 +1,176 @@ +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// SAMEINING, the archon (Alfar_Progettazione.txt sec. 13.8): Fader's power, an all-or-nothing form. + /// + /// - needs 75% of the maximum eitr and a READY Heimkall, and spends ALL the eitr; + /// - lasts up to three minutes: bigger (x1.5), glowing, +20% speed; + /// - instead of armour there is a POOL of points, three per eitr spent: every blow lands on it, + /// and when it is gone the form ends early; + /// - no weapons: a psionic pulse strikes everything hostile around the body, once a second; + /// - Ljosstorm and Geisli cost nothing in the form, but wait a few seconds between uses; + /// - it ENDS (time up, pool gone) with a teleport home at one hit point, eitr at zero, and the + /// Heimkall wait starting. The form IS a Heimkall spent on purpose. + /// + /// The form is published in the ZDO so other players see the size and the glow. + /// + public static class AlfarArchon + { + public const string ZdoKey = "Alfar_Archon"; + + public static bool Active { get; private set; } + public static float Pool { get; private set; } + public static float EndsAt { get; private set; } + public static float StartedAt { get; private set; } + + private static float nextPulse; + + /// True for any player in range: the form is read off the ZDO, not local state. + public static bool IsArchon(Player player) + { + if (player == null) return false; + ZNetView nview = player.GetComponent(); + return nview != null && nview.IsValid() && nview.GetZDO().GetInt(ZdoKey, 0) == 1; + } + + public static bool IsLocalActive => Active && Player.m_localPlayer != null; + + private static void Publish(Player player, bool on) + { + ZNetView nview = player.GetComponent(); + if (nview != null && nview.IsValid()) nview.GetZDO().Set(ZdoKey, on ? 1 : 0); + } + + // ─── Entering ──────────────────────────────────────────────────────── + + public static bool TryActivate(Player player) + { + if (Active || player == null) return false; + + float max = player.GetMaxEitr(); + float eitr = player.GetEitr(); + if (max <= 0f || eitr < max * AlfarPowerConfig.ArchonThreshold.Value) + { + player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_alfar_archon_not_charged")); + return false; + } + + if (!AlfarHeimkall.IsReady(player)) + { + player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_alfar_archon_not_ready")); + return false; + } + + // Everything goes in: the strength of the form is what the Alfr had eaten. + Pool = eitr * AlfarPowerConfig.ArchonPoolPerEitr.Value; + AlfarEitr.Spend(player, eitr); + + Active = true; + StartedAt = Time.time; + EndsAt = Time.time + AlfarPowerConfig.ArchonSeconds.Value; + AlfarStatusEffects.ShowTimer("archon", AlfarPowerConfig.ArchonSeconds.Value); + nextPulse = Time.time + AlfarPowerConfig.ArchonPulseInterval.Value; + Publish(player, true); + + Jotunn.Logger.LogInfo($"[Alfar] Sameining on: pool {Pool:0} for {AlfarPowerConfig.ArchonSeconds.Value:0}s."); + player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_alfar_archon_on")); + return true; + } + + // ─── In the form ───────────────────────────────────────────────────── + + /// + /// Takes a blow into the pool. Called from the shield prefix before anything else, because in + /// the form the pool IS the defence: every type of damage, drowning and the edge of the world + /// included, since nothing else can end the form but the pool and the clock. + /// + public static void Absorb(Player player, HitData hit) + { + if (!Active || hit == null) return; + + float total = hit.m_damage.GetTotalDamage(); + hit.m_damage = default(HitData.DamageTypes); + if (total <= 0f) return; + + Pool -= total; + // The exit itself is done in Tick, outside the damage call. + } + + public static void Tick(Player player) + { + if (!Active) return; + + if (player == null || player.IsDead()) + { + // The body is gone (or the world is): nothing to teleport, only the state to drop. + Active = false; + if (player != null) Publish(player, false); + return; + } + + if (Pool <= 0f || Time.time >= EndsAt) + { + Exit(player, Pool <= 0f ? "pool gone" : "time up"); + return; + } + + if (Time.time >= nextPulse) + { + nextPulse = Time.time + AlfarPowerConfig.ArchonPulseInterval.Value; + AlfarPowers.Pulse(player, AlfarPowerConfig.ArchonPulseRadius.Value, AlfarPowerConfig.ArchonPulseDamage.Value); + } + } + + // ─── Leaving ───────────────────────────────────────────────────────── + + public static void Exit(Player player, string reason) + { + if (!Active) return; + + Active = false; + Pool = 0f; + Publish(player, false); + AlfarStatusEffects.ClearTimer("archon"); + + // Eitr to zero, then the Heimkall: the form spends the one that was ready. + AlfarEitr.Spend(player, player.GetEitr()); + AlfarHeimkall.TryTrigger(player, "Sameining " + reason, force: true); + + player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_alfar_archon_off")); + Jotunn.Logger.LogInfo($"[Alfar] Sameining off ({reason})."); + } + + /// The cooldown Ljosstorm and Geisli wait in the form, instead of costing eitr. + public static float FreePowerCooldown => AlfarPowerConfig.ArchonFreePowerCooldown.Value; + + /// + /// NO WEAPONS in the form: the psionic pulse is the attack. Humanoid.StartAttack is the one + /// door every swing, shot and draw goes through (verified, doc sec. 16B); returning false + /// with a false result is "nothing started". + /// + [HarmonyLib.HarmonyPatch(typeof(Humanoid), "StartAttack")] + public static class Alfar_Archon_NoWeapons_Patch + { + public static bool Prefix(Humanoid __instance, ref bool __result) + { + if (Active && __instance == Player.m_localPlayer) + { + __result = false; + return false; + } + return true; + } + } + + /// Clears the state without teleporting (used by the reset command). + public static void ForceClear(Player player) + { + Active = false; + Pool = 0f; + if (player != null) Publish(player, false); + AlfarStatusEffects.ClearTimer("archon"); + } + } +} diff --git a/JotunnModStub/Alfar/AlfarChests.cs b/JotunnModStub/Alfar/AlfarChests.cs new file mode 100644 index 0000000..e8fc1d9 --- /dev/null +++ b/JotunnModStub/Alfar/AlfarChests.cs @@ -0,0 +1,134 @@ +using System.Collections.Generic; +using Jotunn.Configs; +using Jotunn.Entities; +using Jotunn.Managers; +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// The EIRINNSIGLI, the verdigris seal (Alfar_Progettazione.txt sec. 9.2c): a bronze nail turned at + /// the forge. Put inside a chest it tells the drones NOT to look there - the inverse of the + /// Butler's, where the seal says "this one is yours". Only the colour differs from the nail: a model + /// recolour does not touch the inventory icon (guide 5.2), so in the pack it looks like a bronze + /// nail and only the name tells it apart. + /// + public static class AlfarSigil + { + public const string PrefabName = "AlfarSigil"; + public const string DisplayName = "$rov_item_alfar_sigil_name"; + + public static void Register() + { + GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(PrefabName, "BronzeNails"); + if (prefab == null) + { + Jotunn.Logger.LogWarning("[Alfar] Could not clone BronzeNails: no verdigris seal."); + return; + } + + ItemDrop drop = prefab.GetComponent(); + if (drop == null || drop.m_itemData == null || drop.m_itemData.m_shared == null) return; + + ItemDrop.ItemData.SharedData shared = drop.m_itemData.m_shared; + shared.m_name = DisplayName; + shared.m_description = "$rov_item_alfar_sigil_desc"; + + AlfarConstructs.Tint(prefab, new Color(0.36f, 0.68f, 0.58f, 1f)); + ItemManager.Instance.AddItem(new CustomItem(prefab, fixReference: false)); + + ItemManager.Instance.AddRecipe(new CustomRecipe(new RecipeConfig + { + Item = PrefabName, + Amount = 1, + CraftingStation = CraftingStations.Forge, + MinStationLevel = 1, + Requirements = new[] { new RequirementConfig("BronzeNails", 1, 0, true) }, + })); + } + } + + /// + /// The two special chests (sec. 9.2c): built like an ordinary chest with Greydwarf eyes added to + /// the price. The ENTRY chest is where everything is thrown and where the drones sort from; the + /// WOOD chest holds the wood the drones may burn - the only wood they ever consume. + /// + public static class AlfarChests + { + public const string EntryName = "AlfarInngangskista"; + public const string WoodName = "AlfarEldividarkista"; + + public static void Register() + { + RegisterOne(EntryName, "$rov_piece_alfar_inngangskista_name", "$rov_piece_alfar_inngangskista_desc", + new Color(0.62f, 0.80f, 1f, 1f)); + RegisterOne(WoodName, "$rov_piece_alfar_eldividarkista_name", "$rov_piece_alfar_eldividarkista_desc", + new Color(0.85f, 0.62f, 0.36f, 1f)); + } + + private static void RegisterOne(string pieceName, string display, string description, Color tint) + { + GameObject source = PrefabManager.Cache.GetPrefab("piece_chest_wood"); + if (source == null) + { + Jotunn.Logger.LogWarning("[Alfar] No 'piece_chest_wood': the chest " + pieceName + " is not registered."); + return; + } + + GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(pieceName, source); + if (prefab == null) return; + + // The price of a plain chest, read from the game (guide 3.2), plus the eyes. + var requirements = new List(); + Piece vanilla = source.GetComponent(); + if (vanilla != null && vanilla.m_resources != null) + { + foreach (Piece.Requirement r in vanilla.m_resources) + { + if (r.m_resItem == null) continue; + requirements.Add(new RequirementConfig(r.m_resItem.gameObject.name, r.m_amount, 0, true)); + } + } + requirements.Add(new RequirementConfig("GreydwarfEye", AlfarNexusConfig.ChestEyes.Value, 0, true)); + + Container container = prefab.GetComponent(); + if (container != null) container.m_name = display; + + Piece piece = prefab.GetComponent(); + if (piece == null) { Jotunn.Logger.LogWarning("[Alfar] The chest has no Piece: " + pieceName); return; } + piece.m_name = display; + piece.m_description = description; + + AlfarConstructs.Tint(prefab, tint); + + PieceManager.Instance.AddPiece(new CustomPiece(prefab, fixReference: false, new PieceConfig + { + Name = display, + Description = description, + PieceTable = PieceTables.Hammer, + Category = PieceCategories.Crafting, + Icon = piece.m_icon, + Requirements = requirements.ToArray(), + })); + + // One of each inside the reach of a Ljoskjarne, and only for the Alfar, and only where a core stands. + PieceDensityLimit.Register(pieceName, AlfarNexusConfig.NexusRadius.Value, 1, "rov_msg_build_limit_alfar_chest"); + PieceDensityLimit.RegisterGate(pieceName, (player, position) => + { + if (!AlfarRace.IsLocalAlfar()) + { + if (player != null) player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_alfar_only_alfar")); + return false; + } + if (AlfarNexusBehaviour.Covering(position) == null) + { + if (player != null) player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_alfar_chest_needs_nexus")); + return false; + } + return true; + }); + + AlfarPieces.Extra.Add(pieceName); + } + } +} diff --git a/JotunnModStub/Alfar/AlfarCommands.cs b/JotunnModStub/Alfar/AlfarCommands.cs new file mode 100644 index 0000000..a0f4785 --- /dev/null +++ b/JotunnModStub/Alfar/AlfarCommands.cs @@ -0,0 +1,110 @@ +using Jotunn.Entities; +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// Test helpers for the Alfar, in the F5 console. They exist so the phases of Alfar_Test.txt can + /// be walked through without waiting twenty minutes between steps. + /// + /// alfarstatus what the race is doing right now (eitr, Heimkall timer, SE, form...) + /// alfarreset clears every Alfar timer and cooldown + /// alfareitr sets the eitr pool: a number, "full", or 0 + /// alfarhp sets the current health, to try the lethal-blow case without dying + /// + public class AlfarStatusCommand : ConsoleCommand + { + public override string Name => "alfarstatus"; + public override string Help => "[DEBUG] Prints the Alfar's eitr, health, Heimkall timer and passive."; + + public override void Run(string[] args) + { + Player player = Player.m_localPlayer; + if (player == null) { Console.instance.Print("No local player."); return; } + + string race = AlfarVisuals.GetPlayerRace(player); + Print($"race={race} progression state={BossProgressionManager.GetCurrentProgressionState()}"); + Print($"health={player.GetHealth():0}/{player.GetMaxHealth():0} eitr={player.GetEitr():0.0}/{player.GetMaxEitr():0}"); + + float left = AlfarHeimkall.Remaining(player); + Print($"Heimkall: {(left <= 0f ? "READY" : (left / 60f).ToString("0.0") + " min left")} " + + $"(cooldown now {AlfarHeimkall.CooldownSeconds() / 60f:0} min)"); + + bool se = player.GetSEMan().HaveStatusEffect(SE_AlfarStats.EffectName.GetStableHashCode()); + Print($"passive status effect: {(se ? "on" : "OFF")}"); + } + + private static void Print(string text) + { + Console.instance.Print("[Alfar] " + text); + Jotunn.Logger.LogInfo("[Alfar] " + text); + } + } + + public class AlfarResetCommand : ConsoleCommand + { + public override string Name => "alfarreset"; + public override string Help => "[DEBUG] Clears the Alfar's Heimkall timer and every power cooldown."; + + public override void Run(string[] args) + { + Player player = Player.m_localPlayer; + if (player == null) return; + + AlfarHeimkall.ResetTimer(player); + AlfarHeimkall.InvulnerableUntil = 0f; + AlfarPowers.ResetCooldowns(player); + Console.instance.Print("[Alfar] Heimkall timer and power cooldowns cleared."); + } + } + + public class AlfarEitrCommand : ConsoleCommand + { + public override string Name => "alfareitr"; + public override string Help => "[DEBUG] alfareitr - sets the Alfr's current eitr."; + + public override void Run(string[] args) + { + Player player = Player.m_localPlayer; + if (player == null || args.Length == 0) { Console.instance.Print("alfareitr "); return; } + + float target; + if (args[0].ToLower() == "full") target = player.GetMaxEitr(); + else if (!float.TryParse(args[0], System.Globalization.NumberStyles.Float, + System.Globalization.CultureInfo.InvariantCulture, out target)) + { + Console.instance.Print("alfareitr "); + return; + } + + target = Mathf.Clamp(target, 0f, player.GetMaxEitr()); + float delta = target - player.GetEitr(); + if (delta > 0f) player.AddEitr(delta); + else if (delta < 0f) AlfarEitr.Spend(player, -delta); + + Console.instance.Print($"[Alfar] eitr = {player.GetEitr():0.0}/{player.GetMaxEitr():0}"); + } + } + + public class AlfarHpCommand : ConsoleCommand + { + public override string Name => "alfarhp"; + public override string Help => "[DEBUG] alfarhp - sets the current health, to test the lethal-blow case."; + + public override void Run(string[] args) + { + Player player = Player.m_localPlayer; + if (player == null || args.Length == 0) { Console.instance.Print("alfarhp "); return; } + + if (!float.TryParse(args[0], System.Globalization.NumberStyles.Float, + System.Globalization.CultureInfo.InvariantCulture, out float hp)) + { + Console.instance.Print("alfarhp "); + return; + } + + player.SetHealth(Mathf.Clamp(hp, 1f, player.GetMaxHealth())); + Console.instance.Print($"[Alfar] health = {player.GetHealth():0}/{player.GetMaxHealth():0}"); + } + } +} diff --git a/JotunnModStub/Alfar/AlfarConfig.cs b/JotunnModStub/Alfar/AlfarConfig.cs new file mode 100644 index 0000000..1769a1a --- /dev/null +++ b/JotunnModStub/Alfar/AlfarConfig.cs @@ -0,0 +1,159 @@ +using BepInEx.Configuration; +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// Every number the Alfar use. Nothing numeric lives in the logic files (guide 3.4), and every + /// value here is a STARTING value: Alfar_Progettazione.txt sec. 19 says they will all be + /// corrected in play. + /// + /// Only the look is bound so far. The shield, the powers and the base add their own sections as + /// they are written. + /// + public static class AlfarConfig + { + /// + /// Written into m_customData["Race"] and the ZDO. Chosen once and never changed: renaming it + /// later leaves every saved Alfar character unrecognised and back to human (the Brandr + /// lesson, design doc sec. 2). + /// + public const string RaceId = "Alfar"; + + // ─── Look ──────────────────────────────────────────────────────────── + + /// The tint written into _SkinColor. Ash grey: low saturation, a hair cool. + public static ConfigEntry SkinColor; + + /// + /// Height against a normal Viking: +5%, design doc sec. 7.1. Applied to the Visual child's Y, + /// never the root (RaceEyeHeight explains why). + /// + public static ConfigEntry HeightScale; + + /// + /// Width and depth: "barely visibly thinner", about -8%. Together with HeightScale this is a + /// NON-UNIFORM scale, which is where held weapons and the first-person camera tend to look + /// squashed - doc sec. 7.2. If it does, raise this toward 1 before touching anything else. + /// + public static ConfigEntry WidthScale; + + /// + /// 1 is the Sverm's size, which is what the design asked to try first ("se non va li + /// allarghiamo"). Raise it to enlarge the eyes: 1.6 is roughly a grey from the films. + /// + public static ConfigEntry EyeSizeMultiplier; + + // The eye geometry is the Sverm's, unchanged (SvermVisuals): offsets are metres in the head + // bone's OWN frame, so they land on the same part of the face at any body scale. + public const float EyeSeparation = 0.032f; + public const float EyeForward = 0.081f; + public const float EyeHeight = 0.181f; + public const float EyeSize = 0.062f; + + // ─── Eitr: diet, shield, soft fall ─────────────────────────────────── + + /// + /// What each food adds to the maximum eitr besides its own: min(hp, stamina) times this. + /// 1 is the design (sec. 3): native eitr plus the lower of hp and stamina. + /// + public static ConfigEntry DietMultiplier; + + /// + /// Eitr spent per point of damage. 1:1, FIXED, for ever (sec. 4.1): progression comes from + /// the food raising the pool, not from a better rate. + /// + public static ConfigEntry ShieldRate; + + /// Lightning and spirit cost this many times the rate (sec. 5.1: the double cost). + public static ConfigEntry ConductiveMultiplier; + + /// + /// Falls cost nothing while there is any eitr (sec. 4.5: soft fall). Off, a fall is shielded + /// like any other blow. + /// + public static ConfigEntry SoftFall; + + /// + /// The fastest an Alfr falls while there is eitr, in metres per second. The vanilla Feather + /// Cape caps at 5; a little under that reads as floating. + /// + public static ConfigEntry FeatherFallSpeed; + + // ─── Heimkall: the death that costs a wait ─────────────────────────── + + /// Minutes before a second Heimkall is possible, before Yagluth (sec. 6). + public static ConfigEntry HeimkallMinutes; + + /// The same, once Yagluth is down. + public static ConfigEntry HeimkallMinutesAfterYagluth; + + /// The same, once Fader is down. + public static ConfigEntry HeimkallMinutesAfterFader; + + /// + /// Seconds of invulnerability on arrival, so a lethal blow does not simply repeat at the + /// bed. Without it a burning or drowning death would loop. + /// + public static ConfigEntry HeimkallInvulnerableSeconds; + + public static void Bind(ConfigFile config) + { + const string heimkall = "Alfar - Heimkall"; + + HeimkallMinutes = config.Bind(heimkall, "Cooldown Minutes", 20f, + new ConfigDescription("Minutes between two Heimkalls (the lethal-blow teleport to the bed). Inside this wait, a lethal blow kills normally.", + new AcceptableValueRange(0f, 120f))); + + HeimkallMinutesAfterYagluth = config.Bind(heimkall, "Cooldown Minutes After Yagluth", 15f, + new ConfigDescription("The cooldown once Yagluth is defeated.", + new AcceptableValueRange(0f, 120f))); + + HeimkallMinutesAfterFader = config.Bind(heimkall, "Cooldown Minutes After Fader", 10f, + new ConfigDescription("The cooldown once Fader is defeated.", + new AcceptableValueRange(0f, 120f))); + + HeimkallInvulnerableSeconds = config.Bind(heimkall, "Invulnerable Seconds", 5f, + new ConfigDescription("Seconds nothing can hurt the Alfr after arriving.", + new AcceptableValueRange(0f, 30f))); + + const string eitr = "Alfar - Eitr"; + + DietMultiplier = config.Bind(eitr, "Diet Multiplier", 1f, + new ConfigDescription("Each food adds its native eitr plus min(hp, stamina) times this to the maximum eitr.", + new AcceptableValueRange(0f, 3f))); + + ShieldRate = config.Bind(eitr, "Shield Rate", 1f, + new ConfigDescription("Eitr spent per point of damage absorbed (1 = 1:1).", + new AcceptableValueRange(0.1f, 5f))); + + ConductiveMultiplier = config.Bind(eitr, "Lightning And Spirit Multiplier", 2f, + new ConfigDescription("Lightning and spirit damage cost this many times the shield rate.", + new AcceptableValueRange(1f, 5f))); + + SoftFall = config.Bind(eitr, "Soft Fall", true, + new ConfigDescription("Falling does no damage, and is slowed, while the Alfr has any eitr.")); + + FeatherFallSpeed = config.Bind(eitr, "Feather Fall Speed", 4f, + new ConfigDescription("Maximum falling speed (m/s) while the Alfr has eitr. Lower floats more.", + new AcceptableValueRange(1f, 20f))); + + const string look = "Alfar - Look"; + + SkinColor = config.Bind(look, "Skin Color", new Color(0.86f, 0.88f, 0.88f, 1f), + new ConfigDescription("How light the ash-grey skin is. The skin texture itself is made grey; this only sets its brightness.")); + + HeightScale = config.Bind(look, "Height Scale", 1.05f, + new ConfigDescription("Body height against a normal Viking (1.05 = +5%).", + new AcceptableValueRange(0.8f, 1.3f))); + + WidthScale = config.Bind(look, "Width Scale", 0.92f, + new ConfigDescription("Body width and depth against a normal Viking (0.92 = 8% thinner).", + new AcceptableValueRange(0.7f, 1.2f))); + + EyeSizeMultiplier = config.Bind(look, "Eye Size Multiplier", 0.8f, + new ConfigDescription("1 = the Sverm's eye size; 0.8 is slightly smaller. Raise to enlarge the black eyes.", + new AcceptableValueRange(0.5f, 3f))); + } + } +} diff --git a/JotunnModStub/Alfar/AlfarConstructs.cs b/JotunnModStub/Alfar/AlfarConstructs.cs new file mode 100644 index 0000000..80fe2a5 --- /dev/null +++ b/JotunnModStub/Alfar/AlfarConstructs.cs @@ -0,0 +1,397 @@ +using System.Collections.Generic; +using Jotunn.Entities; +using Jotunn.Managers; +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// The three constructs, the Alfar's only troops (Alfar_Progettazione.txt sec. 8.5): + /// + /// Neistvordr a Surtling: hp 60 and a shield of 60 (the vanilla Surtling has 20), fire thrower + /// Steinvordr the StoneGolem: hp 800, the tank, ONE per Nexus + /// Eldingvordr a smaller Abomination at half its hp, which fires a lightning sphere every 8 s + /// + /// Everything that makes them the Alfar's is done by what is added, not by rewriting attacks: + /// AlfarMark turns whatever they deal into lightning and keeps it off friends and buildings, + /// AlfarCreatureShield gives them a shield that returns by itself, and RaisedThrall gives them + /// the follow and stay orders every other race's troops already have. + /// + /// They are NOT repaired and do not heal: the damage to the body is permanent. RaisedThrall's + /// sentinel regeneration (SkeletonSentryBehaviour) is therefore left off, and the creature's own + /// slow vanilla regeneration is switched off too. + /// + public static class AlfarConstructs + { + public const string Neistvordr = "AlfarNeistvordr"; + public const string Steinvordr = "AlfarSteinvordr"; + public const string Eldingvordr = "AlfarEldingvordr"; + + public const string SphereProjectile = "AlfarLightningSphere"; + public const string SphereWeapon = "AlfarSphereAttack"; + + public class Kind + { + public string PrefabName; + public string Display; + public string Source; + public float Health; // 0 = keep the vanilla creature's + public float HealthFactor; // applied after Health when Health is 0 + public float Scale; // 1 = the vanilla size + } + + public static readonly Kind[] Roster = + { + new Kind { PrefabName = Neistvordr, Display = "$rov_creature_alfar_neistvordr_name", Source = "Surtling", Health = 60f, Scale = 1f }, + new Kind { PrefabName = Steinvordr, Display = "$rov_creature_alfar_steinvordr_name", Source = "StoneGolem", Health = 0f, HealthFactor = 1f, Scale = 0.6f }, + new Kind { PrefabName = Eldingvordr, Display = "$rov_creature_alfar_eldingvordr_name", Source = "Abomination", Health = 0f, HealthFactor = 0.5f, Scale = 0.4f }, + }; + + public static Kind Find(string prefabName) + { + foreach (Kind kind in Roster) if (kind.PrefabName == prefabName) return kind; + return null; + } + + // ─── Registration ──────────────────────────────────────────────────── + + public static void Register() + { + // The sphere first: the Eldingvordr's weapon needs it. + bool sphere = RegisterSphere(); + + foreach (Kind kind in Roster) + { + if (kind.PrefabName == Eldingvordr && !sphere) + { + Jotunn.Logger.LogWarning("[Alfar] No lightning sphere: the Eldingvordr keeps the Abomination's melee."); + } + RegisterOne(kind, sphere); + } + } + + private static void RegisterOne(Kind kind, bool sphere) + { + GameObject source = PrefabManager.Cache.GetPrefab(kind.Source); + if (source == null) + { + Jotunn.Logger.LogWarning($"[Alfar] No '{kind.Source}' to build {kind.Display} from."); + return; + } + + GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(kind.PrefabName, source); + if (prefab == null) return; + + Character character = prefab.GetComponent(); + if (character != null) + { + character.m_name = kind.Display; + character.m_faction = Character.Faction.Players; + if (kind.Health > 0f) character.m_health = kind.Health; + else character.m_health *= kind.HealthFactor; + + // The damage to the body is permanent: no slow regeneration either. + character.m_regenAllHPTime = 0f; + } + + if (!Mathf.Approximately(kind.Scale, 1f)) + { + prefab.transform.localScale = Vector3.one * kind.Scale; + ZNetView nview = prefab.GetComponent(); + if (nview != null) nview.m_syncInitialScale = true; + } + + BaseAI ai = prefab.GetComponent(); + if (ai != null) ai.m_randomMoveRange = AlfarNexusConfig.ConstructLeash.Value; + + MonsterAI monster = prefab.GetComponent(); + if (monster != null) + { + // The vanilla creatures attack player-built objects. Ours never touch a building. + monster.m_attackPlayerObjects = false; + monster.m_alertRange = AlfarNexusConfig.ConstructAlertRange.Value; + monster.m_maxChaseDistance = AlfarNexusConfig.ConstructAlertRange.Value; + } + + // A construct that dropped Coal, a Surtling core or a trophy would be a loot farm. + foreach (CharacterDrop drops in prefab.GetComponentsInChildren(true)) + { + if (drops != null) Object.DestroyImmediate(drops); + } + + if (kind.PrefabName == Eldingvordr && sphere) GiveSphereWeapon(prefab); + if (kind.PrefabName == Neistvordr) BlueFlames(prefab); + else Tint(prefab, new Color(0.85f, 0.52f, 0.2f, 1f)); + + AlfarMark mark = prefab.AddComponent(); + mark.Role = "construct"; + + // What a destroyed construct gives back: the METAL it was built from, and nothing else - the + // crystals and the refined eitr are spent for good (design sec. 8.5). + AlfarRefund refund = prefab.AddComponent(); + refund.Item = kind.PrefabName == Neistvordr ? "Bronze" : kind.PrefabName == Eldingvordr ? "Iron" : "BlackMetal"; + refund.Amount = kind.PrefabName == Neistvordr ? AlfarNexusConfig.NeistMetal.Value + : kind.PrefabName == Eldingvordr ? AlfarNexusConfig.EldingMetal.Value + : AlfarNexusConfig.SteinMetal.Value; + + AlfarCreatureShield shield = prefab.AddComponent(); + shield.MaxShield = character != null ? character.m_health : 0f; + shield.Shield = shield.MaxShield; + + RaisedThrall thrall = prefab.AddComponent(); + thrall.m_kind = kind.PrefabName; + thrall.m_commandingRace = AlfarConfig.RaceId; + thrall.m_maxFollowers = -1; // the cap is the Nexus's, per type, counted at the Nexus + thrall.m_witherSeconds = AlfarNexusConfig.WitherSeconds.Value; + thrall.m_homeCheckRange = AlfarNexusConfig.NexusRadius.Value; + thrall.m_refusalMessage = "$rov_msg_thrall_refusal_alfar"; + + PrefabManager.Instance.AddPrefab(prefab); + Jotunn.Logger.LogInfo($"[Alfar] Registered '{kind.PrefabName}' from '{kind.Source}'."); + } + + // ─── The lightning sphere ──────────────────────────────────────────── + + /// + /// The Eldingvordr's shot: a sphere that bursts in a small area, hurts only enemies, and never + /// touches a building (doc sec. 8.5 and 16B V12). Cloned from the Dverger ice projectile, the + /// clean base the probe found: an area burst and NO lingering effect spawned on impact (the + /// fire one drops a fire field and also spawns on buildings). + /// + private static bool RegisterSphere() + { + GameObject source = PrefabManager.Cache.GetPrefab("DvergerStaffIce_projectile"); + if (source == null) + { + Jotunn.Logger.LogWarning("[Alfar] DvergerStaffIce_projectile not found: no lightning sphere."); + return false; + } + + GameObject projectile = PrefabManager.Instance.CreateClonedPrefab(SphereProjectile, source); + if (projectile == null) return false; + + Projectile settings = projectile.GetComponent(); + if (settings == null) return false; + + settings.m_gravity = 0f; + settings.m_ttl = 4f; + settings.m_aoe = 3f; + settings.m_aoeSkipWearNTear = true; + settings.m_hitFriendly = false; + settings.m_noDamageFriendly = true; + settings.m_hitOwner = false; + settings.m_statusEffect = ""; + + Tint(projectile, new Color(0.55f, 0.85f, 1f, 1f)); + PrefabManager.Instance.AddPrefab(projectile); + + // The weapon that fires it: the Surtling's own fireball weapon, because a creature that + // shoots needs an item with a projectile attack, and that is the one that exists. + GameObject surtling = PrefabManager.Cache.GetPrefab("Surtling"); + Humanoid surtlingHumanoid = surtling != null ? surtling.GetComponent() : null; + GameObject fireball = surtlingHumanoid != null && surtlingHumanoid.m_defaultItems != null && + surtlingHumanoid.m_defaultItems.Length > 0 + ? surtlingHumanoid.m_defaultItems[0] + : null; + if (fireball == null) + { + Jotunn.Logger.LogWarning("[Alfar] The Surtling's fireball weapon was not found: no sphere weapon."); + return false; + } + + GameObject weapon = PrefabManager.Instance.CreateClonedPrefab(SphereWeapon, fireball); + if (weapon == null) return false; + + ItemDrop drop = weapon.GetComponent(); + if (drop == null || drop.m_itemData == null || drop.m_itemData.m_shared == null) return false; + + ItemDrop.ItemData.SharedData shared = drop.m_itemData.m_shared; + shared.m_name = "$rov_item_alfar_sphere_name"; + + // One shot every eight seconds (design): the AI waits this long between uses. + shared.m_aiAttackInterval = AlfarNexusConfig.SphereIntervalSeconds.Value; + shared.m_aiAttackRange = AlfarNexusConfig.SphereRange.Value; + shared.m_aiAttackRangeMin = 4f; + + HitData.DamageTypes damage = default(HitData.DamageTypes); + damage.m_lightning = AlfarNexusConfig.SphereDamage.Value; + shared.m_damages = damage; + + if (shared.m_attack != null) + { + shared.m_attack.m_attackProjectile = projectile; + // The Abomination's right hand: where the sphere leaves from. + shared.m_attack.m_attackOriginJoint = "r.hand"; + } + + ItemManager.Instance.AddItem(new CustomItem(weapon, fixReference: false)); + return true; + } + + private static void GiveSphereWeapon(GameObject prefab) + { + Humanoid humanoid = prefab.GetComponent(); + GameObject weapon = PrefabManager.Instance.GetPrefab(SphereWeapon); + if (humanoid == null || weapon == null) return; + + humanoid.m_defaultItems = new[] { weapon }; + humanoid.m_randomWeapon = new GameObject[0]; + humanoid.m_randomArmor = new GameObject[0]; + humanoid.m_randomShield = new GameObject[0]; + humanoid.m_randomSets = new Humanoid.ItemSet[0]; + } + + // ─── Colour ────────────────────────────────────────────────────────── + + /// + /// A tint on every mesh, through renderer.materials (an instanced copy) and NEVER .material or + /// sharedMaterial: the vanilla creature uses the same asset and must stay as it is (guide 3.5). + /// This is a recolour and not a retexture: a true repaint of the golem and the Abomination is + /// still to do (test file, phase 6). + /// + public static void Tint(GameObject prefab, Color color) + { + foreach (Renderer renderer in prefab.GetComponentsInChildren(true)) + { + if (renderer is ParticleSystemRenderer || renderer is TrailRenderer || renderer is LineRenderer) continue; + + Material[] materials = renderer.materials; + foreach (Material material in materials) + { + if (material == null) continue; + if (material.HasProperty("_Color")) material.color = color; + if (material.HasProperty("_EmissionColor")) + { + material.SetColor("_EmissionColor", color * 0.08f); + material.EnableKeyword("_EMISSION"); + } + } + renderer.materials = materials; + } + + foreach (Light light in prefab.GetComponentsInChildren(true)) light.color = color; + } + + /// + /// The Surtling is made of particles and lights, not textures, and the vanilla prefab ALREADY + /// carries blue variants of its flames, switched off (probe, doc 16C P2): turn those on, turn + /// the red ones off, and recolour the glow of the body and the point light. + /// + private static void BlueFlames(GameObject prefab) + { + foreach (Transform child in prefab.GetComponentsInChildren(true)) + { + if (child.name == "flames_world_BLUE") child.gameObject.SetActive(true); + else if (child.name == "flames" || child.name == "flames_world" || child.name == "flames_world_Purple") + { + child.gameObject.SetActive(false); + } + } + + Color blue = new Color(0.25f, 0.55f, 1f, 1f); + foreach (Light light in prefab.GetComponentsInChildren(true)) light.color = blue; + + foreach (Renderer renderer in prefab.GetComponentsInChildren(true)) + { + Material[] materials = renderer.materials; + foreach (Material material in materials) + { + if (material != null && material.HasProperty("_EmissionColor")) + { + // The vanilla emission is white-hot (73): keep the strength, change the hue. + material.SetColor("_EmissionColor", new Color(0.25f, 0.55f, 1f, 1f) * 30f); + } + } + renderer.materials = materials; + } + } + + // ─── Counting and spawning (called by the Nexus) ───────────────────── + + /// + /// A destroyed construct drops the metal it cost, on the ground where it fell. Only a DEATH: + /// a zone unloading destroys the object too and must not pay anyone (the same rule as the + /// Butler's payload). + /// + public class AlfarRefund : MonoBehaviour + { + public string Item = ""; + public int Amount; + } + + [HarmonyLib.HarmonyPatch(typeof(Character), "OnDeath")] + public static class Alfar_Refund_Patch + { + public static void Postfix(Character __instance) + { + AlfarRefund refund = __instance != null ? __instance.GetComponent() : null; + if (refund == null || refund.Amount <= 0 || ObjectDB.instance == null) return; + + GameObject prefab = ObjectDB.instance.GetItemPrefab(refund.Item); + ItemDrop template = prefab != null ? prefab.GetComponent() : null; + if (template == null || template.m_itemData == null) return; + + int left = refund.Amount; + int max = Mathf.Max(1, template.m_itemData.m_shared.m_maxStackSize); + Vector3 at = __instance.transform.position + Vector3.up * 0.5f; + + while (left > 0) + { + int stack = Mathf.Min(left, max); + ItemDrop.ItemData clone = template.m_itemData.Clone(); + clone.m_dropPrefab = prefab; + ItemDrop.DropItem(clone, stack, at + Random.insideUnitSphere * 0.3f, Quaternion.identity); + left -= stack; + } + refund.Amount = 0; // once only + } + } + + public static int CountAlive(Vector3 anchor, string prefabName) + { + int count = 0; + foreach (RaisedThrall thrall in RaisedThrall.BoundTo(anchor)) + { + if (thrall != null && thrall.Kind == prefabName) count++; + } + return count; + } + + public static bool Spawn(Vector3 anchor, string prefabName) + { + GameObject prefab = ZNetScene.instance != null ? ZNetScene.instance.GetPrefab(prefabName) : null; + if (prefab == null) + { + Jotunn.Logger.LogWarning($"[Alfar] No '{prefabName}' in ZNetScene: it cannot be built."); + return false; + } + + Vector3 where = SpawnSpot(anchor); + GameObject spawned = Object.Instantiate(prefab, where, Quaternion.Euler(0f, Random.Range(0, 360), 0f)); + RaisedThrall thrall = spawned != null ? spawned.GetComponent() : null; + if (thrall != null) thrall.Bind(anchor); + return spawned != null; + } + + /// A free spot on a ring around the Nexus, on the ground, or due south as a last resort. + public static Vector3 SpawnSpot(Vector3 centre) + { + const float radius = 3.5f; + int obstacleMask = LayerMask.GetMask("Default", "static_solid", "Default_small", "piece", "vehicle"); + float start = Random.Range(0f, 360f); + + for (int i = 0; i < 12; i++) + { + float angle = (start + i * 30f) * Mathf.Deg2Rad; + Vector3 candidate = centre + new Vector3(Mathf.Cos(angle), 0f, Mathf.Sin(angle)) * radius; + if (ZoneSystem.instance != null) candidate.y = ZoneSystem.instance.GetGroundHeight(candidate); + if (Physics.CheckSphere(candidate + Vector3.up * 1.5f, 1f, obstacleMask)) continue; + return candidate + Vector3.up * 0.3f; + } + + Vector3 fallback = centre + new Vector3(0f, 0f, -radius); + if (ZoneSystem.instance != null) fallback.y = ZoneSystem.instance.GetGroundHeight(fallback); + return fallback + Vector3.up * 0.3f; + } + } +} diff --git a/JotunnModStub/Alfar/AlfarDroneAI.cs b/JotunnModStub/Alfar/AlfarDroneAI.cs new file mode 100644 index 0000000..59d8fea --- /dev/null +++ b/JotunnModStub/Alfar/AlfarDroneAI.cs @@ -0,0 +1,1950 @@ +using System.Collections.Generic; +using System.Text; +using HarmonyLib; +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// The Alfar drone's own head (Alfar_Progettazione.txt sec. 9): a FORK of the Butler's BoneServantAI, + /// kept as a separate class so nothing that ships with the Skeleton, Skadi or Sverm can be broken + /// from here. What it keeps: the movement, the payload in the ZDO, the three families of stations, + /// the burn protection and the one-stage rule. What it changes: ONE drone does both trades; chests + /// are read the other way round (the sigil marks the ones NOT to touch); stations are fed only from + /// the entry chest, wood only from the wood chest; the product goes back to the entry chest and is + /// SORTED from there into the chest that already holds the same thing; and three jobs are new - + /// repair, farming (with the replant rule) and sorting. + /// + /// The Bone Servant's own head, as it was written: everything it does is here; vanilla's MonsterAI + /// never runs on it. + /// + /// HOW IT MOVES, which was the one open question in the design and is answered here rather than in + /// the doc. Three candidates were on the table: a ghost follow-target, pinning m_patrolPoint the way + /// RaisedThrall does, and calling BaseAI.MoveTo directly. The IL settled it: + /// + /// - BaseAI has NO Update and NO FixedUpdate. UpdateAI(dt) is driven centrally by + /// MonoUpdaters.FixedUpdate over BaseAI.Instances, and that list is maintained by OnEnable / + /// OnDisable. So "disable the AI and drive MoveTo yourself" kills the only thing that would + /// call anything: a disabled BaseAI is not ticked at all. That candidate is dead. + /// - BaseAI.UpdateAI itself does almost nothing - IsOwner, UpdateTakeoffLanding, + /// UpdateRegeneration - so skipping it costs a flying check we do not need and a regeneration + /// we already have from SkeletonSentryBehaviour. + /// + /// So: a PREFIX on MonsterAI.UpdateAI that hands the tick to this class and returns false. The + /// servant keeps its place in the central tick, keeps vanilla pathing through BaseAI.MoveTo, and + /// vanilla's own AI - targeting, fleeing, wandering, attacking - never executes a single line. That + /// is also why the servant cannot fight: not because its weapon was taken (it was), but because the + /// code that would swing it is never reached. + /// + /// MoveTo(dt, point, dist, run) is private, hence the cached MethodInfo. It returns TRUE on arrival + /// (read in the IL: DistanceXZ under the threshold calls StopMoving and returns 1), which is the + /// whole arrival test - no distance maths of our own. + /// + /// THE PAYLOAD IS VIRTUAL. The servant has no inventory. Every station's input RPC takes a STRING, + /// so what it carries is a list of prefab names and counts in its own ZDO, which survives saving, + /// zone reload and - the case that matters - a change of owner mid-job in multiplayer. The one + /// thing this costs is that the goods do not exist as objects while in transit, so they have to be + /// put back into the world by hand if the servant dies holding them. That is , + /// and it is the reason nothing here can quietly delete a player's ore. + /// + public class AlfarDroneAI : MonoBehaviour + { + // ─── ZDO keys ──────────────────────────────────────────────────────── + public const string KeyAnchor = "RoV_alfarAnchor"; + public const string KeyOrphanAt = "RoV_alfarOrphanAt"; + public const string KeyLoad = "RoV_alfarLoad"; + public const string KeySource = "RoV_alfarSource"; + public const string KeyTarget = "RoV_alfarTarget"; + public const string KeyStatus = "RoV_alfarStatus"; + public const string KeyDest = "RoV_alfarDest"; + + /// Every drone alive in the loaded zones: the repairs look at each other through it. + public static readonly List All = new List(); + + /// Written into a STATION's ZDO: the chest whose material is in it right now, so the + /// product goes home to where the raw came from even after a reload, and even if a different + /// client collects it. + public const string KeyFedBy = "RoV_alfarFedBy"; + + // ─── numbers that are not worth a config entry ─────────────────────── + private const float PlanInterval = 1.5f; + + /// + /// How close is close enough. Measured to the piece's ORIGIN, which on a furnace or a kiln sits + /// inside a metre or so of solid collider - so anything tight enough to look like hugging the + /// thing is a distance the servant can never actually reach, and it would time out and put a + /// perfectly good station in the penalty box. Two and a half metres is roughly where a player + /// stands to use one. + /// + private const float ArriveDistance = 2.5f; + + private const float CollectRadius = 3.5f; + private const float JobTimeout = 25f; + private const float PenaltySeconds = 180f; + + /// Set aside briefly when a job was reached but achieved nothing. Without this, a job + /// that arrives and finds nothing to do is re-planned identically on the next tick and the + /// servant stands there deciding the same thing forever. + private const float ShortPenaltySeconds = 20f; + private const float FleeSeconds = 6f; + private const float WitherSeconds = 30f; + private const float HomeCheckRange = 25f; + + /// A cooking slot inside this many seconds of burning outranks everything else. Twelve + /// seconds is a walk of about twenty metres with room to spare, which is the whole radius. + private const float SpoilPanicSeconds = 12f; + + /// How long a station may sit unserved before its wait starts outweighing distance. + /// This is what stops a furnace at the edge of the circle from starving while the servant + /// shuttles between two closer ones. + private const float WaitToMetres = 0.25f; + + private const int PayloadCap = 120; + + private static readonly System.Reflection.MethodInfo MoveToMethod = + AccessTools.Method(typeof(BaseAI), "MoveTo", + new[] { typeof(float), typeof(Vector3), typeof(float), typeof(bool) }); + + private static readonly System.Reflection.FieldInfo AllPiecesField = + AccessTools.Field(typeof(Piece), "s_allPieces"); + + private static readonly System.Reflection.MethodInfo ContainerSaveMethod = + AccessTools.Method(typeof(Container), "Save"); + + private static int s_itemMask = -1; + + /// Which stations this one serves. Set on the prefab at registration, so it travels + /// with every instance the table raises. + public ButlerFamily m_family = ButlerFamily.Forge; + + /// + /// Whether this one stands and fights instead of walking home when trouble comes. Off for the + /// Bone Servants, which are pacifists by decision; on for the Sverm's Seeker Workers, which + /// keep the forge AND defend the nest. See . + /// + public bool m_fightsBack = false; + + /// + /// How close to the anchor counts as home, and how far past the configured radius it works. + /// 2.5 and 0 for a table. A Sverm nest is metres of collider that grows with its stage, so + /// SvermWorkerBehaviour sets both to the nest's measured edge - otherwise an idle worker would + /// spend its life walking into the trunk, and the work circle would be mostly nest. + /// + public float m_homeDistance = 2.5f; + public float m_radiusBonus = 0f; + + /// For a servant that fights back: how close an enemy has to be to stop the work, how + /// often that is asked, and how long the fight holds after the last sign of one. + private const float FightRange = 12f; + private const float FightScanInterval = 1f; + private const float FightLinger = 5f; + + private float m_nextFightScan; + private float m_fightUntil; + + private ZNetView m_nview; + private Character m_character; + private MonsterAI m_ai; + + private readonly object[] m_moveArgs = new object[4]; + private readonly List m_payload = new List(); + private readonly Dictionary m_penalties = new Dictionary(); + private readonly Dictionary m_idleSince = new Dictionary(); + + private readonly List m_stations = new List(); + private readonly List m_chests = new List(); // the storage chests + private Container m_entry; // the entry chest + private Container m_wood; // the wood-to-burn chest + private readonly List m_damaged = new List(); + + // Farming: where the last harvest was, and what to put back there. + private Vector3? m_farmSpot; + private Quaternion m_farmRot; + private PlantInfo m_farmInfo; + private float m_farmReadyAt; + + // Sorting: what was chosen at the entry chest and where it is going. + private string m_sortItem; + private ZDOID m_sortDest; + private float m_scannedAt = -99f; + + private Job m_job; + private float m_nextPlan; + private float m_jobDeadline; + private float m_fleeUntil; + private string m_status = ""; + + private class Load + { + public string Name; + public int Count; + } + + private class Job + { + public string Kind; // load | fuel | collect | deposit | drop + public ZDOID Target; + public Vector3 Point; + public bool Hurry; + public string Label; + public ZDOID Claim; // the one target other drones must leave alone + } + + // ================================================================ life + + private void Awake() + { + m_nview = GetComponent(); + m_character = GetComponent(); + m_ai = GetComponent(); + + All.Add(this); + ReadPayload(); + } + + private void OnDestroy() + { + All.Remove(this); + + // Only a DEATH scatters the load. A zone unloading destroys this object too, and there the + // payload must stay in the ZDO where it will be read again on the way back in - dropping it + // would mint a copy every time the player walked away. + if (m_character != null && m_character.IsDead()) DropPayload(); + } + + /// Called by the table the moment it raises one. + public void Bind(Vector3 anchor) + { + if (m_nview == null || !m_nview.IsValid()) return; + + m_nview.GetZDO().Set(KeyAnchor, anchor); + + if (m_ai != null) m_ai.MakeTame(); + if (m_character != null) m_character.SetTamed(true); + } + + public Vector3? Anchor + { + get + { + if (m_nview == null || !m_nview.IsValid()) return null; + + Vector3 anchor = m_nview.GetZDO().GetVec3(KeyAnchor, Vector3.zero); + return anchor == Vector3.zero ? (Vector3?)null : anchor; + } + } + + public bool IsBoundTo(Vector3 anchor) + { + Vector3? own = Anchor; + return own != null && Vector3.SqrMagnitude(own.Value - anchor) < 0.25f; + } + + /// The one line the table's hover shows. Read from the ZDO so a client that does not + /// own the servant still sees what it is doing. + public string Status + { + get + { + if (m_nview == null || !m_nview.IsValid()) return m_status; + return m_nview.GetZDO().GetString(KeyStatus, m_status); + } + } + + private void SetStatus(string text) + { + if (text == m_status) return; + + m_status = text; + if (m_nview != null && m_nview.IsValid() && m_nview.IsOwner()) + { + m_nview.GetZDO().Set(KeyStatus, text); + } + } + + /// Hit by something: stop working and walk home. It never fights back - there is + /// nothing in this class that could. A servant that fights back ignores this: vanilla already + /// holds the attacker as its target (MonsterAI.OnDamaged calls SetTarget, read off the IL), and + /// gives it the tick on the next frame. + public void NoteDamage() + { + if (m_fightsBack) return; + + m_fleeUntil = Time.time + FleeSeconds; + m_job = null; + } + + /// + /// True while vanilla's MonsterAI should have the tick instead of the work - only ever for a + /// servant that fights back, and only on the client that runs it. + /// + /// VANILLA DOES THE FIGHTING, this only decides when. Two things start a fight: a target the + /// MonsterAI already holds - which covers being hit, see NoteDamage - and an enemy inside + /// FightRange, found with BaseAI.FindClosestEnemy. That one is a static sweep of distance and + /// IsEnemy with no line of sight (IL), which is why the range is short. Either holds the fight + /// for FightLinger seconds, so the worker does not flicker between swinging and walking to the + /// chest on alternate ticks. + /// + /// The job is dropped, not the payload: whatever it was carrying stays in the ZDO, and the + /// first plan after the fight carries it on to where it was going. + /// + public bool HandsToVanilla() + { + if (!m_fightsBack || m_ai == null || m_character == null || m_character.IsDead()) return false; + if (m_nview == null || !m_nview.IsValid() || !m_nview.IsOwner()) return false; + + Character target = m_ai.GetTargetCreature(); + if (target != null && !target.IsDead()) + { + m_fightUntil = Time.time + FightLinger; + } + else if (Time.time >= m_nextFightScan) + { + m_nextFightScan = Time.time + FightScanInterval; + if (BaseAI.FindClosestEnemy(m_character, transform.position, FightRange) != null) + { + m_fightUntil = Time.time + FightLinger; + } + } + + if (Time.time >= m_fightUntil) return false; + + m_job = null; + m_nextPlan = 0f; // the fight moved it; plan afresh the moment it hands back + SetStatus("Fighting."); + return true; + } + + // ================================================================ the tick + + /// Everything. Returns what MonsterAI.UpdateAI would have returned. + public bool Tick(float dt) + { + if (m_nview == null || !m_nview.IsValid() || !m_nview.IsOwner()) return false; + if (m_character == null || m_character.IsDead()) return false; + + if (TickWither()) return true; + + if (Time.time < m_fleeUntil) + { + SetStatus("Driven off."); + GoHome(dt); + return true; + } + + if (Time.time >= m_nextPlan) + { + m_nextPlan = Time.time + PlanInterval; + Plan(); + } + + Execute(dt); + return true; + } + + /// + /// The table is gone: start the clock, and stop when it runs out. Same shape as RaisedThrall's, + /// and deliberately only asked near home - further out the table's zone is simply not loaded, so + /// "nothing there" would be a lie. + /// + private bool TickWither() + { + Vector3? anchor = Anchor; + if (anchor == null || ZNet.instance == null) return false; + + long stamp = m_nview.GetZDO().GetLong(KeyOrphanAt, 0L); + + if (stamp == 0L) + { + if (Vector3.SqrMagnitude(transform.position - anchor.Value) > + HomeCheckRange * HomeCheckRange) return false; + if (RaisedThrall.StationStandsAt(anchor.Value)) return false; + + m_nview.GetZDO().Set(KeyOrphanAt, ZNet.instance.GetTime().Ticks); + return false; + } + + if (RaisedThrall.StationStandsAt(anchor.Value)) + { + m_nview.GetZDO().Set(KeyOrphanAt, 0L); + return false; + } + + double elapsed = (ZNet.instance.GetTime() - new System.DateTime(stamp)).TotalSeconds; + if (elapsed < WitherSeconds) return false; + + HitData hit = new HitData(); + hit.m_damage.m_damage = 1E+10f; + hit.m_hitType = HitData.HitType.Undefined; + m_character.ApplyDamage(hit, true, false); + return true; + } + + // ================================================================ planning + + private void Plan() + { + Vector3? anchor = Anchor; + if (anchor == null) { m_job = null; return; } + + Scan(anchor.Value); + ExpirePenalties(); + + // A harvest is in progress: wait for the drops to land, then gather them and replant. + if (m_farmSpot != null) + { + m_job = Time.time < m_farmReadyAt + ? new Job { Kind = "wait", Point = transform.position, Label = "Waiting" } + : new Job { Kind = "farm_finish", Point = m_farmSpot.Value, Label = "Gathering" }; + return; + } + + if (m_payload.Count > 0) { m_job = PlanDelivery(anchor.Value); return; } + + // The forge has no clock: a smelter holds its ore indefinitely and puts its own output on + // the floor, so PlanRescue would ask a question whose answer is always no. The smith is a + // four-state machine and the cook is a five-state one, and that is the whole of the + // simplification the split bought. + // REFUEL BEFORE LOAD, and that order is the whole of the blast furnace fix. FreeSlots goes + // back above zero the instant a furnace eats one ore, so while there is scrap left in any + // chest PlanLoad always has an answer and PlanFuel, sitting behind it, never got a turn - + // the furnace was topped up forever and burned down to nothing. Fuel cannot starve loading + // in return, because FuelWanted is zero for a station with no work: an empty furnace asks + // for no coal, gets filled, and only then becomes worth stoking. + // One drone does both trades, so the burn protection is always on. Stations first, then the + // base: repairs, the fields, and last the tidying of the entry chest. + Job job = PlanRescue(); + job = job ?? PlanCollect() ?? PlanFuel() ?? PlanLoad(); + job = job ?? PlanRepair(anchor.Value) ?? PlanFarm(anchor.Value) ?? PlanSort(); + + if (job != null && (m_job == null || m_job.Kind != job.Kind || m_job.Target != job.Target)) + { + m_jobDeadline = Time.time + JobTimeout; + } + if (m_job != null && !ReferenceEquals(m_job, job)) Release(m_job.Claim); + if (job != null) Claim(job.Claim); + m_job = job; + } + + /// + /// Everything within the radius, once every planning tick. Piece.s_allPieces is the cheap way in + /// - it is the list the game already keeps of every built piece - so there is no OverlapSphere + /// and no guessing at layer masks for the part that runs constantly. + /// + private void Scan(Vector3 anchor) + { + if (Time.time - m_scannedAt < PlanInterval * 0.5f) return; + m_scannedAt = Time.time; + + m_stations.Clear(); + m_chests.Clear(); + m_damaged.Clear(); + m_entry = null; + m_wood = null; + + List pieces = AllPiecesField != null ? AllPiecesField.GetValue(null) as List : null; + if (pieces == null) return; + + float radius = AlfarNexusConfig.NexusRadius.Value + m_radiusBonus; + float radiusSq = radius * radius; + + for (int i = 0; i < pieces.Count; i++) + { + Piece piece = pieces[i]; + if (piece == null) continue; + if (Vector3.SqrMagnitude(piece.transform.position - anchor) > radiusSq) continue; + + // A station of the other trade is not this servant's business, but it is still not a + // chest - hence the continue either way. + // Both trades: the drone serves the smelters AND the kitchens. + ButlerStation station = ButlerStation.From(piece.gameObject); + if (station != null) + { + m_stations.Add(station); + continue; + } + + // Every chest in reach is the drone's, EXCEPT one holding the sigil. The two special + // chests are told apart by prefab name. + Container container = piece.GetComponent(); + if (container != null && !IsMarkedOff(container)) + { + string chestName = Utils.GetPrefabName(piece.gameObject); + if (chestName == AlfarChests.EntryName) m_entry = container; + else if (chestName == AlfarChests.WoodName) m_wood = container; + else m_chests.Add(container); + } + + // Anything damaged is for the drones to mend, towers and chests and walls alike. + WearNTear wear = piece.GetComponent(); + if (wear != null && wear.GetHealthPercentage() < 0.999f) m_damaged.Add(wear); + } + } + + /// + /// The sigil is INVERTED from the Butler's: it marks the chests the drones must NOT look at. A + /// chest in use by a player is left alone too. The sigil itself is never counted as material and + /// never carried away - see TakeFrom. + /// + private static bool IsMarkedOff(Container container) + { + if (container == null || container.IsInUse()) return true; + + Inventory inventory = container.GetInventory(); + if (inventory == null) return true; + + string sigil = SigilSharedName(); + return !string.IsNullOrEmpty(sigil) && inventory.CountItems(sigil) > 0; + } + + private static string s_sigilShared; + private static string s_sigilFor; + + /// Inventory.CountItems matches on the SHARED name ($item_...), not on the prefab name + /// the stations use, so the configured prefab is resolved once into the other kind of name. + private static string SigilSharedName() + { + string wanted = AlfarSigil.PrefabName; + if (s_sigilFor == wanted) return s_sigilShared; + + s_sigilFor = wanted; + s_sigilShared = null; + + GameObject prefab = ObjectDB.instance != null ? ObjectDB.instance.GetItemPrefab(wanted) : null; + ItemDrop drop = prefab != null ? prefab.GetComponent() : null; + if (drop != null && drop.m_itemData != null && drop.m_itemData.m_shared != null) + { + s_sigilShared = drop.m_itemData.m_shared.m_name; + } + else + { + Jotunn.Logger.LogWarning($"[AlfarDrone] No item '{wanted}' to use as the sigil; " + + "no chest can be marked until that name is right."); + } + + return s_sigilShared; + } + + // ---------------------------------------------------------------- the five states + + /// 1. SAVE. A slot about to burn beats everything, and it is the only job it runs to. + private Job PlanRescue() + { + ButlerStation best = null; + float soonest = SpoilPanicSeconds; + + foreach (ButlerStation station in m_stations) + { + if (!station.Alive || IsPenalised(station.Id) || ClaimedByOther(station.Id)) continue; + if (!station.HasOutput) continue; // nothing pullable yet, panic changes nothing + + float left = station.SecondsToSpoil; + if (left >= soonest) continue; + + soonest = left; + best = station; + } + + if (best == null) return null; + + return new Job + { + Kind = "collect", + Target = best.Id, + Claim = best.Id, + Point = best.Position, + Hurry = true, + Label = "Saving the food", + }; + } + + /// 2. COLLECT. Anything finished, and anything already lying under a station. + private Job PlanCollect() + { + ButlerStation best = null; + float bestScore = float.MaxValue; + + foreach (ButlerStation station in m_stations) + { + if (!station.Alive || IsPenalised(station.Id) || ClaimedByOther(station.Id)) continue; + if (!station.HasOutput && !HasDropsNear(station.Position)) continue; + + float score = Vector3.Distance(transform.position, station.Position); + if (score >= bestScore) continue; + + bestScore = score; + best = station; + } + + if (best == null) return null; + + return new Job + { + Kind = "collect", + Target = best.Id, + Claim = best.Id, + Point = best.Position, + Label = "Collecting", + }; + } + + /// + /// 4. LOAD. Urgency, then distance - and the urgency of a station with nothing wrong with it is + /// how long it has been waiting. A metre of walking is worth four seconds of a station standing + /// idle, so the far furnace wins eventually instead of never. + /// + private Job PlanLoad() + { + ButlerStation best = null; + string bestItem = null; + Container bestChest = null; + float bestScore = float.MaxValue; + + foreach (ButlerStation station in m_stations) + { + if (!station.Alive || IsPenalised(station.Id) || ClaimedByOther(station.Id)) continue; + if (!station.Operable || station.FreeSlots <= 0) continue; + + Container chest; + string item = FindMaterialFor(station, out chest); + if (item == null) { m_idleSince.Remove(station.Id); continue; } + + float waited = NoteIdle(station.Id); + float score = Vector3.Distance(transform.position, chest.transform.position) + + Vector3.Distance(chest.transform.position, station.Position) - + waited * WaitToMetres; + + if (score >= bestScore) continue; + + bestScore = score; + best = station; + bestItem = item; + bestChest = chest; + } + + if (best == null) return null; + + // The chest first - the station is where the payload goes afterwards, and PlanDelivery + // works that out from the target written on the load. + return new Job + { + Kind = "load", + Target = ZdoOf(bestChest), + Claim = best.Id, + Point = bestChest.transform.position, + Label = "Fetching " + bestItem, + }; + } + + /// + /// 3. REFUEL. Only stations that actually have something to work on. + /// + /// Scored by the walk, the same way PlanLoad is, and for a reason that only appeared once this + /// moved up the list: taking the first station in scan order was harmless while refuelling was + /// the job of last resort, but ahead of loading it lets one furnace at the edge of the circle + /// hold the servant while a cold one two metres away waits. + /// + private Job PlanFuel() + { + Container bestChest = null; + string bestFuel = null; + float bestScore = float.MaxValue; + + foreach (ButlerStation station in m_stations) + { + if (!station.Alive || IsPenalised(station.Id) || ClaimedByOther(station.Id)) continue; + if (!station.Operable) continue; + + int wanted = station.FuelWanted; + if (wanted <= 0) continue; + + string fuel = station.FuelPrefab; + if (string.IsNullOrEmpty(fuel)) continue; + + Container chest = FindChestWith(fuel); + if (chest == null) continue; + + float score = Vector3.Distance(transform.position, chest.transform.position) + + Vector3.Distance(chest.transform.position, station.Position); + if (score >= bestScore) continue; + + bestScore = score; + bestChest = chest; + bestFuel = fuel; + } + + if (bestChest == null) return null; + + return new Job + { + Kind = "fuel", + Target = ZdoOf(bestChest), + Point = bestChest.transform.position, + Label = "Fetching " + bestFuel, + }; + } + + /// Where the load in hand is going: on to its station, or back into a chest. + private Job PlanDelivery(Vector3 anchor) + { + // A sorting trip has a destination chosen at the entry chest: take it there. + ZDOID dest = m_nview.GetZDO().GetZDOID(KeyDest); + if (dest != ZDOID.None) + { + Container destination = ContainerById(dest); + if (destination != null && !IsMarkedOff(destination) && !IsPenalised(dest) && HasRoomFor(destination)) + { + return new Job + { + Kind = "deposit", + Target = dest, + Point = destination.transform.position, + Label = "Sorting " + Describe(), + }; + } + m_nview.GetZDO().Set(KeyDest, ZDOID.None); + } + + ZDOID target = m_nview.GetZDO().GetZDOID(KeyTarget); + if (target != ZDOID.None) + { + // NO FreeSlots CHECK HERE, and that was the first bug found in play: fuel does not go + // into a slot. A furnace filled to m_maxOre with copper has FreeSlots 0 and still wants + // coal, so gating the delivery on free slots sent the servant back to the chest with + // the coal it had just fetched - and then PlanFuel sent it out for the same coal again, + // forever. AcceptsAnything already asks the right question of both doors. + ButlerStation station = StationById(target); + if (station != null && station.Alive && station.Operable && AcceptsAnything(station)) + { + return new Job + { + Kind = "deposit_station", + Target = target, + Point = station.Position, + Label = "Loading " + Describe(), + }; + } + + // The station is gone, full or cold. The goods are ours to put back, not to hold. + m_nview.GetZDO().Set(KeyTarget, ZDOID.None); + } + + Container chest = ChestForProduct(); + if (chest != null) + { + return new Job + { + Kind = "deposit", + Target = ZdoOf(chest), + Point = chest.transform.position, + Label = "Storing " + Describe(), + }; + } + + // Every sealed chest is full - but a chest is not the only place a thing can go. A station + // that BURNS what is in hand is a destination too, and for the smith it is usually the + // right one: the charcoal kiln releases its whole batch in one go (verified in the IL - + // UpdateSmelter only calls SpawnProcessed once the ore queue empties), which is exactly the + // delivery a nearly full chest cannot absorb, and the coal it makes is what the furnace + // beside it is waiting for. Offering the load to a consumer before giving up is what turns + // "nowhere to put 20x Coal" into a full blast furnace. + // + // It comes AFTER the chest and not before, so a product still goes home to the chest that + // paid for it whenever there is room; this is the step before the floor, not instead of + // storing. + ButlerStation consumer = StationWanting(); + if (consumer != null) + { + return new Job + { + Kind = "deposit_station", + Target = consumer.Id, + Point = consumer.Position, + Label = "Loading " + Describe(), + }; + } + + // Nothing will take it. Beside the table it goes: a stalled chain is worse than a tidy + // floor, and nothing may vanish (sec. 7.3). + return new Job + { + Kind = "drop", + Target = ZDOID.None, + Point = anchor, + Label = "Nowhere to put " + Describe(), + }; + } + + /// The nearest station that will take something out of the payload, as material or as + /// fuel. No FreeSlots check, for the reason spelled out above the KeyTarget branch: fuel does + /// not go into a slot, and AcceptsAnything already asks the right question of both doors. + private ButlerStation StationWanting() + { + ButlerStation best = null; + float bestDistance = float.MaxValue; + + foreach (ButlerStation station in m_stations) + { + if (!station.Alive || IsPenalised(station.Id) || ClaimedByOther(station.Id)) continue; + if (!station.Operable || !AcceptsAnything(station)) continue; + + float distance = Vector3.Distance(transform.position, station.Position); + if (distance >= bestDistance) continue; + + bestDistance = distance; + best = station; + } + + return best; + } + + // ================================================================ execution + + private void Execute(float dt) + { + if (m_job == null) + { + SetStatus(m_stations.Count == 0 ? "Nothing to serve." : "Nothing to do."); + GoHome(dt); + return; + } + + SetStatus(m_job.Label); + + if (!MoveToPoint(dt, m_job.Point, ArriveDistance, m_job.Hurry)) + { + // Doors do not open for pathfinding. A target it cannot reach goes into the penalty box + // and the servant gets on with something it can do. + if (Time.time > m_jobDeadline) + { + Penalise(m_job.Target); + Jotunn.Logger.LogInfo($"[AlfarDrone] Could not reach {m_job.Kind} target; " + + "setting it aside for a few minutes."); + m_job = null; + m_nextPlan = 0f; + } + return; + } + + bool achieved; + switch (m_job.Kind) + { + case "load": achieved = DoLoad(); break; + case "fuel": achieved = DoFuel(); break; + case "collect": achieved = DoCollect(); break; + case "deposit_station": achieved = DoDepositStation(); break; + case "deposit": achieved = DoDeposit(); break; + case "drop": DropPayload(); achieved = true; break; + case "wait": achieved = true; break; + case "repair": achieved = DoRepair(); break; + case "farm": achieved = DoFarm(); break; + case "farm_finish": achieved = DoFarmFinish(); break; + case "sortfetch": achieved = DoSortFetch(); break; + default: achieved = true; break; + } + + // Arrived and nothing happened: the world moved while it walked. Set that target aside for + // twenty seconds so the next plan picks something else instead of re-deciding the same + // errand on every tick. + if (!achieved) PenaliseShort(m_job.Target); + + m_job = null; + m_nextPlan = 0f; // arriving changes the world; re-plan on the next tick rather than in 1.5 s + } + + /// At the chest: take what the chosen station will eat, and remember where it came from. + private bool DoLoad() + { + Container chest = ContainerById(m_job.Target); + if (chest == null) return false; + + // The station is chosen again here rather than carried on the job, because the walk took + // time and the world may have moved on. + ButlerStation station = null; + string item = null; + + foreach (ButlerStation candidate in m_stations) + { + if (!candidate.Alive || !candidate.Operable || candidate.FreeSlots <= 0) continue; + if (IsPenalised(candidate.Id)) continue; + + string found = FirstAccepted(candidate, chest); + if (found == null) continue; + + station = candidate; + item = found; + break; + } + + if (station == null || item == null) return false; + + int taken = TakeFrom(chest, item, station.FreeSlots); + if (taken <= 0) return false; + + AddToPayload(item, taken); + m_nview.GetZDO().Set(KeySource, ZdoOf(chest)); + m_nview.GetZDO().Set(KeyTarget, station.Id); + WritePayload(); + return true; + } + + /// At the chest, for fuel. Same shape as DoLoad, and kept separate because fuel goes in + /// through a different door and is never the thing being processed. + private bool DoFuel() + { + Container chest = ContainerById(m_job.Target); + if (chest == null) return false; + + foreach (ButlerStation station in m_stations) + { + if (!station.Alive || !station.Operable || IsPenalised(station.Id)) continue; + + int wanted = station.FuelWanted; + string fuel = station.FuelPrefab; + if (wanted <= 0 || string.IsNullOrEmpty(fuel)) continue; + + int taken = TakeFrom(chest, fuel, wanted); + if (taken <= 0) continue; + + AddToPayload(fuel, taken); + m_nview.GetZDO().Set(KeySource, ZdoOf(chest)); + m_nview.GetZDO().Set(KeyTarget, station.Id); + WritePayload(); + return true; + } + + return false; + } + + /// + /// At a station with something finished. Pull first, sweep second - and the sweep is the only + /// place the servant ever picks anything up off the ground, which is what keeps it from tidying + /// away things the player left lying about on purpose. + /// + /// THE ORDER IS THE POINT, and it used to be the other way round. Sweeping first meant every + /// visit collected what the LAST visit had thrown on the floor and then threw a fresh one down; + /// since Plan() hands the servant to PlanDelivery the moment it is carrying anything, it walked + /// off to the chest the instant the sweep landed and abandoned the item it had just pulled. + /// While a hearth kept working there was therefore always exactly one cooked meat lying on the + /// ground - the "loses one per batch, whether that is two or five" the testers reported. + /// + /// The loop is the other half of it. RPC_RemoveDoneItem empties ONE slot per call, so a hearth + /// with five done slots needs five calls; one per visit turned one batch into five round trips + /// to the chest. It runs against OutputPulls rather than against HasOutput alone because the + /// fermenter's Ready survives its own tap for the length of the animation. + /// + private bool DoCollect() + { + ButlerStation station = StationById(m_job.Target); + if (station == null || !station.Alive) return false; + + bool pulled = false; + for (int i = 0; i < station.OutputPulls && station.HasOutput; i++) + { + station.PullOutput(transform.position); + pulled = true; + } + + int before = PayloadCount(); + SweepDrops(station.Position); + bool swept = PayloadCount() > before; + + if (swept) + { + // The product belongs to whoever fed the station. If nothing was written there - the + // player loaded it by hand - it goes to the nearest sealed chest instead, which is the + // "yes, it collects your work too" decision paying its own way. + ZDOID fedBy = station.Nview.GetZDO().GetZDOID(KeyFedBy); + m_nview.GetZDO().Set(KeySource, fedBy); + m_nview.GetZDO().Set(KeyTarget, ZDOID.None); + WritePayload(); + } + + return swept || pulled; + } + + /// At the station, with raw material in hand. + private bool DoDepositStation() + { + ButlerStation station = StationById(m_job.Target); + if (station == null || !station.Alive || !station.Operable) return false; + + bool loadedAny = false; + + for (int i = m_payload.Count - 1; i >= 0; i--) + { + Load load = m_payload[i]; + + while (load.Count > 0 && station.FreeSlots > 0 && station.Accepts(load.Name)) + { + station.Add(load.Name); + load.Count--; + loadedAny = true; + } + + // Fuel goes in through its own door, and only for as long as it is wanted. + if (load.Count > 0 && load.Name == station.FuelPrefab) + { + int wanted = station.FuelWanted; + while (load.Count > 0 && wanted > 0) + { + station.AddFuel(); + load.Count--; + wanted--; + loadedAny = true; + } + } + + if (load.Count <= 0) m_payload.RemoveAt(i); + } + + if (loadedAny) + { + // Whoever fed it, gets it back. + ZDOID source = m_nview.GetZDO().GetZDOID(KeySource); + if (source != ZDOID.None && station.Nview.IsValid()) + { + if (!station.Nview.IsOwner()) station.Nview.ClaimOwnership(); + station.Nview.GetZDO().Set(KeyFedBy, source); + } + } + + if (m_payload.Count == 0) m_nview.GetZDO().Set(KeyTarget, ZDOID.None); + WritePayload(); + return loadedAny; + } + + /// At a chest, with the finished goods. + private bool DoDeposit() + { + Container chest = ContainerById(m_job.Target); + if (chest == null) return false; + + ZNetView nview = chest.GetComponent(); + if (nview == null || !nview.IsValid()) return false; + if (!nview.IsOwner()) nview.ClaimOwnership(); + + Inventory inventory = chest.GetInventory(); + if (inventory == null) return false; + + bool wrote = false; + + for (int i = m_payload.Count - 1; i >= 0; i--) + { + Load load = m_payload[i]; + + GameObject prefab = ObjectDB.instance != null + ? ObjectDB.instance.GetItemPrefab(load.Name) + : null; + if (prefab == null) continue; + + // One at a time: it stacks correctly, it stops exactly when the chest is full, and the + // counts are small enough that being tidy costs nothing. + while (load.Count > 0 && inventory.CanAddItem(prefab, 1) && inventory.AddItem(prefab, 1)) + { + load.Count--; + wrote = true; + } + + if (load.Count <= 0) m_payload.RemoveAt(i); + } + + if (wrote && ContainerSaveMethod != null) ContainerSaveMethod.Invoke(chest, null); + WritePayload(); + + // Still holding something: that chest is full, so do not choose it again on the next pass. + if (m_payload.Count > 0) Penalise(m_job.Target); + else m_nview.GetZDO().Set(KeyDest, ZDOID.None); + return wrote; + } + + // ================================================================ claims + + // Two drones must not take the same station or chest in the same moment. The Butler forbids a + // second table nearby; with N drones to a Nexus that is impossible, so the choice is made + // visible between them: a target is CLAIMED by the drone that picked it for a short while. This + // is the local-client form of the dispatcher the design asks for; two clients owning two + // drones still cannot see each other's claims (doc 17.14). + private static readonly Dictionary> s_claims = + new Dictionary>(); + private const float ClaimSeconds = 30f; + + private bool ClaimedByOther(ZDOID id) + { + if (id == ZDOID.None) return false; + KeyValuePair claim; + if (!s_claims.TryGetValue(id, out claim)) return false; + + if (claim.Key == null || Time.time >= claim.Value) { s_claims.Remove(id); return false; } + return claim.Key != this; + } + + private void Claim(ZDOID id) + { + if (id != ZDOID.None) s_claims[id] = new KeyValuePair(this, Time.time + ClaimSeconds); + } + + private void Release(ZDOID id) + { + KeyValuePair claim; + if (id != ZDOID.None && s_claims.TryGetValue(id, out claim) && claim.Key == this) s_claims.Remove(id); + } + + // ================================================================ repair + + /// + /// Anything damaged in the base, and any other drone that is hurt. Free, like the hammer. NOT the + /// constructs: their damage is permanent by design (they are Characters and not pieces, and + /// they are not drones, so they never come up here). + /// + private Job PlanRepair(Vector3 anchor) + { + WearNTear bestPiece = null; + AlfarDroneAI bestDrone = null; + float bestDistance = float.MaxValue; + + foreach (WearNTear wear in m_damaged) + { + if (wear == null) continue; + ZDOID id = ZdoOf(wear); + if (IsPenalised(id) || ClaimedByOther(id)) continue; + + float distance = Vector3.Distance(transform.position, wear.transform.position); + if (distance >= bestDistance) continue; + bestDistance = distance; + bestPiece = wear; + } + + foreach (AlfarDroneAI other in All) + { + if (other == null || other == this || other.m_character == null || other.m_character.IsDead()) continue; + if (other.m_character.GetHealth() >= other.m_character.GetMaxHealth() - 0.5f) continue; + if (Vector3.Distance(other.transform.position, anchor) > AlfarNexusConfig.NexusRadius.Value) continue; + + ZDOID id = ZdoOf(other); + if (IsPenalised(id) || ClaimedByOther(id)) continue; + + float distance = Vector3.Distance(transform.position, other.transform.position); + if (distance >= bestDistance) continue; + bestDistance = distance; + bestDrone = other; + bestPiece = null; + } + + if (bestPiece != null) + { + ZDOID id = ZdoOf(bestPiece); + return new Job { Kind = "repair", Target = id, Claim = id, Point = bestPiece.transform.position, Label = "Repairing" }; + } + if (bestDrone != null) + { + ZDOID id = ZdoOf(bestDrone); + return new Job { Kind = "repair", Target = id, Claim = id, Point = bestDrone.transform.position, Label = "Mending a drone" }; + } + return null; + } + + private bool DoRepair() + { + if (ZNetScene.instance == null) return false; + + GameObject go = ZNetScene.instance.FindInstance(m_job.Target); + if (go == null) return false; + + WearNTear wear = go.GetComponent(); + if (wear != null) return wear.Repair(); + + Character character = go.GetComponent(); + if (character != null && !character.IsDead() && go.GetComponent() != null) + { + character.Heal(character.GetMaxHealth(), true); + return true; + } + return false; + } + + // ================================================================ farming + + private class PlantInfo + { + public GameObject Sapling; // the piece that grows the plant + public string Item; // the item that piece costs, and so the item to put back + } + + // pickable prefab name -> the sapling that grows it and the item that sapling costs + private static readonly Dictionary s_plants = new Dictionary(); + private static bool s_plantsBuilt; + private static float s_pickScanAt = -99f; + private static readonly List s_pickables = new List(); + private static readonly System.Reflection.FieldInfo PickedField = AccessTools.Field(typeof(Pickable), "m_picked"); + + /// + /// Built from the game, not from a list: every Plant in ZNetScene names the pickable it grows + /// into and costs one of an item through its Piece. The drone ONLY works plants it can put back + /// (rule R2): it never harvests something it could not replant. + /// + private static void BuildPlants() + { + if (s_plantsBuilt || ZNetScene.instance == null) return; + s_plantsBuilt = true; + + foreach (GameObject prefab in ZNetScene.instance.m_prefabs) + { + if (prefab == null) continue; + + Plant plant = prefab.GetComponent(); + Piece piece = prefab.GetComponent(); + if (plant == null || piece == null || plant.m_grownPrefabs == null) continue; + if (piece.m_resources == null || piece.m_resources.Length == 0 || piece.m_resources[0].m_resItem == null) continue; + + string item = piece.m_resources[0].m_resItem.gameObject.name; + foreach (GameObject grown in plant.m_grownPrefabs) + { + if (grown != null && !s_plants.ContainsKey(grown.name)) + { + s_plants[grown.name] = new PlantInfo { Sapling = prefab, Item = item }; + } + } + } + Jotunn.Logger.LogInfo($"[AlfarDrone] {s_plants.Count} replantable crops known."); + } + + private static void RefreshPickables() + { + if (Time.time - s_pickScanAt < 4f) return; + s_pickScanAt = Time.time; + + s_pickables.Clear(); + s_pickables.AddRange(Object.FindObjectsByType(FindObjectsSortMode.None)); + } + + private static bool IsPicked(Pickable pickable) + { + return PickedField != null && (bool)PickedField.GetValue(pickable); + } + + /// Does picking it give back the item the sapling costs? + private static bool Yields(Pickable pickable, string item) + { + if (pickable.m_itemPrefab != null && pickable.m_itemPrefab.name == item) return true; + + if (pickable.m_extraDrops != null && pickable.m_extraDrops.m_drops != null) + { + foreach (DropTable.DropData drop in pickable.m_extraDrops.m_drops) + { + if (drop.m_item != null && drop.m_item.name == item) return true; + } + } + return false; + } + + private static string[] s_wild; + private static bool IsWildTarget(string prefabName) + { + if (s_wild == null) s_wild = AlfarNexusConfig.WildPickables.Value.Split(new[] { ',' }, System.StringSplitOptions.RemoveEmptyEntries); + foreach (string part in s_wild) + { + if (prefabName.IndexOf(part.Trim(), System.StringComparison.OrdinalIgnoreCase) >= 0) return true; + } + return false; + } + + /// + /// FARMING, with the iron rule (doc 9.4): a cultivated plant is harvested only if the drone can + /// replant one of what it gives; the replant is made RIGHT AWAY, in the SAME place, out of what + /// was just picked, and the rest is stored. Wild mushrooms, berry bushes and flowers on the list + /// are picked and NOT replanted (they grow back by themselves, and trees are never touched). + /// + private Job PlanFarm(Vector3 anchor) + { + BuildPlants(); + RefreshPickables(); + + float radius = AlfarNexusConfig.NexusRadius.Value; + Pickable best = null; + PlantInfo bestInfo = null; + float bestDistance = float.MaxValue; + + foreach (Pickable pickable in s_pickables) + { + if (pickable == null || !pickable.gameObject.activeInHierarchy) continue; + if (Vector3.Distance(pickable.transform.position, anchor) > radius) continue; + if (IsPicked(pickable)) continue; + + ZDOID id = ZdoOf(pickable); + if (id == ZDOID.None || IsPenalised(id) || ClaimedByOther(id)) continue; + + string name = Utils.GetPrefabName(pickable.gameObject); + PlantInfo info = null; + + if (pickable.m_respawnTimeMinutes > 0f) + { + if (!IsWildTarget(name)) continue; // wild and regrowing: only the listed ones + } + else + { + if (!s_plants.TryGetValue(name, out info) || !Yields(pickable, info.Item)) continue; + } + + float distance = Vector3.Distance(transform.position, pickable.transform.position); + if (distance >= bestDistance) continue; + + bestDistance = distance; + best = pickable; + bestInfo = info; + } + + if (best == null) return null; + + m_farmInfo = bestInfo; + ZDOID target = ZdoOf(best); + return new Job { Kind = "farm", Target = target, Claim = target, Point = best.transform.position, Label = "Harvesting" }; + } + + private bool DoFarm() + { + if (ZNetScene.instance == null) return false; + + GameObject go = ZNetScene.instance.FindInstance(m_job.Target); + Pickable pickable = go != null ? go.GetComponent() : null; + if (pickable == null || IsPicked(pickable)) return false; + + Humanoid hands = m_character as Humanoid; + if (hands == null) return false; + + Vector3 spot = pickable.transform.position; + Quaternion rot = pickable.transform.rotation; + + if (!pickable.Interact(hands, false, false)) return false; + + m_farmSpot = spot; + m_farmRot = rot; + m_farmReadyAt = Time.time + 0.8f; // the drops need a moment to land + return true; + } + + private bool DoFarmFinish() + { + Vector3? spot = m_farmSpot; + PlantInfo info = m_farmInfo; + m_farmSpot = null; + m_farmInfo = null; + if (spot == null) return false; + + SweepDrops(spot.Value); + + if (info != null) + { + // R6: the replant comes OUT OF what was just picked, never out of anyone's stock. + bool have = false; + foreach (Load load in m_payload) + { + if (load.Name == info.Item && load.Count > 0) { load.Count--; have = true; break; } + } + m_payload.RemoveAll(l => l.Count <= 0); + WritePayload(); + + if (have && info.Sapling != null) + { + Object.Instantiate(info.Sapling, spot.Value, m_farmRot); + } + else + { + Jotunn.Logger.LogWarning($"[AlfarDrone] Harvested a crop but found no '{info.Item}' to put back."); + } + } + + m_nview.GetZDO().Set(KeySource, ZDOID.None); + m_nview.GetZDO().Set(KeyTarget, ZDOID.None); + return true; + } + + // ================================================================ sorting + + private bool AnyStationAccepts(string prefabName) + { + foreach (ButlerStation station in m_stations) + { + if (!station.Alive || !station.Operable) continue; + if (station.Accepts(prefabName) || prefabName == station.FuelPrefab) return true; + } + return false; + } + + /// The storage chest that already holds this item and has room; else the first EMPTY one. + private Container DestinationFor(string prefabName) + { + GameObject prefab = ObjectDB.instance != null ? ObjectDB.instance.GetItemPrefab(prefabName) : null; + if (prefab == null) return null; + + Container firstEmpty = null; + foreach (Container chest in m_chests) + { + if (chest == null || chest.IsInUse()) continue; + + ZDOID id = ZdoOf(chest); + if (IsPenalised(id) || ClaimedByOther(id)) continue; + + Inventory inventory = chest.GetInventory(); + if (inventory == null || !inventory.CanAddItem(prefab, 1)) continue; + + if (inventory.GetAllItems().Count == 0) + { + if (firstEmpty == null) firstEmpty = chest; + continue; + } + + foreach (ItemDrop.ItemData item in inventory.GetAllItems()) + { + if (item != null && item.m_dropPrefab != null && item.m_dropPrefab.name == prefabName) return chest; + } + } + return firstEmpty; + } + + /// + /// Tidying the entry chest, last of all. What a station will take is the WORK QUEUE and stays; the + /// rest (and any wood, which is stock unless it is in the wood chest) goes to the chest that + /// already holds the same thing, or to an empty one. With nowhere to go it stays where it is. + /// + private Job PlanSort() + { + if (m_entry == null || m_entry.IsInUse()) return null; + + ZDOID entryId = ZdoOf(m_entry); + if (IsPenalised(entryId)) return null; + + Inventory inventory = m_entry.GetInventory(); + if (inventory == null) return null; + + string sigil = AlfarSigil.PrefabName; + foreach (ItemDrop.ItemData item in inventory.GetAllItems()) + { + if (item == null || item.m_dropPrefab == null) continue; + + string name = item.m_dropPrefab.name; + if (name == sigil) continue; + if (!IsWood(name) && AnyStationAccepts(name)) continue; + + Container destination = DestinationFor(name); + if (destination == null) continue; + + m_sortItem = name; + m_sortDest = ZdoOf(destination); + return new Job + { + Kind = "sortfetch", + Target = entryId, + Claim = m_sortDest, + Point = m_entry.transform.position, + Label = "Sorting " + name, + }; + } + return null; + } + + private bool DoSortFetch() + { + if (m_sortItem == null || m_sortDest == ZDOID.None) return false; + + Container entry = ContainerById(m_job.Target); + if (entry == null) return false; + + int taken = TakeFrom(entry, m_sortItem, 40); + if (taken <= 0) return false; + + AddToPayload(m_sortItem, taken); + m_nview.GetZDO().Set(KeyDest, m_sortDest); + m_nview.GetZDO().Set(KeyTarget, ZDOID.None); + WritePayload(); + return true; + } + + // ================================================================ moving + + /// Vanilla pathing, through the private MoveTo. True the moment it has arrived. + private bool MoveToPoint(float dt, Vector3 point, float distance, bool run) + { + if (m_ai == null || MoveToMethod == null) return true; // cannot walk: act in place + + m_moveArgs[0] = dt; + m_moveArgs[1] = point; + m_moveArgs[2] = distance; + m_moveArgs[3] = run; + + return (bool)MoveToMethod.Invoke(m_ai, m_moveArgs); + } + + private void GoHome(float dt) + { + Vector3? anchor = Anchor; + if (anchor == null) + { + if (m_ai != null) m_ai.StopMoving(); + return; + } + + MoveToPoint(dt, anchor.Value, m_homeDistance, false); + } + + // ================================================================ the ground + + private static int ItemMask() + { + if (s_itemMask >= 0) return s_itemMask; + + int mask = LayerMask.GetMask("item"); + s_itemMask = mask != 0 ? mask : ~0; + return s_itemMask; + } + + private bool HasDropsNear(Vector3 point) + { + Collider[] hits = Physics.OverlapSphere(point, CollectRadius, ItemMask()); + foreach (Collider hit in hits) + { + if (hit == null) continue; + ItemDrop drop = hit.GetComponentInParent(); + if (drop != null && drop.m_itemData != null) return true; + } + return false; + } + + /// + /// Picks up everything lying around a station. The drop is destroyed and its contents become + /// entries in the virtual payload, which is the same road the smelter's bars, the oven's bread + /// and the fermenter's bottles all arrive by - one pickup routine for three families. + /// + private void SweepDrops(Vector3 point) + { + Collider[] hits = Physics.OverlapSphere(point, CollectRadius, ItemMask()); + + foreach (Collider hit in hits) + { + if (hit == null) continue; + if (PayloadCount() >= PayloadCap) return; + + ItemDrop drop = hit.GetComponentInParent(); + if (drop == null || drop.m_itemData == null) continue; + + ZNetView nview = drop.GetComponent(); + if (nview == null || !nview.IsValid()) continue; + if (!nview.IsOwner()) nview.ClaimOwnership(); + + string name = drop.m_itemData.m_dropPrefab != null + ? drop.m_itemData.m_dropPrefab.name + : Utils.GetPrefabName(drop.gameObject); + if (string.IsNullOrEmpty(name)) continue; + + AddToPayload(name, Mathf.Max(1, drop.m_itemData.m_stack)); + if (ZNetScene.instance != null) ZNetScene.instance.Destroy(drop.gameObject); + } + } + + /// + /// Puts the virtual load back into the world as real objects. Called when the servant dies and + /// when there is nowhere left to put anything - the two ends of the same promise, which is that + /// nothing the player owns is ever deleted by this feature. + /// + public void DropPayload() + { + if (m_payload.Count == 0) return; + if (ObjectDB.instance == null) { m_payload.Clear(); return; } + + Vector3 at = transform.position + Vector3.up * 0.4f; + + foreach (Load load in m_payload) + { + GameObject prefab = ObjectDB.instance.GetItemPrefab(load.Name); + ItemDrop template = prefab != null ? prefab.GetComponent() : null; + if (template == null || template.m_itemData == null) continue; + + int left = load.Count; + int max = Mathf.Max(1, template.m_itemData.m_shared.m_maxStackSize); + + while (left > 0) + { + int stack = Mathf.Min(left, max); + + // ItemDrop.DropItem instantiates item.m_dropPrefab - a clone off a raw ObjectDB + // prefab does not carry that (see AswidBloodPotions.MakeFood for the same fix). + // Without this, dropping a payload throws instantiating null and never clears + // it, so the same broken load is retried - and crashes - on every AI tick after. + ItemDrop.ItemData clone = template.m_itemData.Clone(); + clone.m_dropPrefab = prefab; + + ItemDrop.DropItem(clone, stack, + at + Random.insideUnitSphere * 0.3f, Quaternion.identity); + left -= stack; + } + } + + m_payload.Clear(); + WritePayload(); + } + + // ================================================================ chests + + /// + /// Takes up to of a prefab out of a chest. The sigil is skipped by name, + /// which is the one thing in here that must never be got wrong: carrying it off would unmark the + /// chest halfway through a job. + /// + private int TakeFrom(Container chest, string prefabName, int want) + { + if (chest == null || want <= 0) return 0; + if (prefabName == AlfarSigil.PrefabName) return 0; + + ZNetView nview = chest.GetComponent(); + if (nview == null || !nview.IsValid()) return 0; + if (!nview.IsOwner()) nview.ClaimOwnership(); + + Inventory inventory = chest.GetInventory(); + if (inventory == null) return 0; + + List matches = new List(); + foreach (ItemDrop.ItemData item in inventory.GetAllItems()) + { + if (item == null || item.m_dropPrefab == null) continue; + if (item.m_dropPrefab.name != prefabName) continue; + matches.Add(item); + } + + int taken = 0; + foreach (ItemDrop.ItemData item in matches) + { + if (taken >= want) break; + + int amount = Mathf.Min(item.m_stack, want - taken); + if (amount <= 0) continue; + + inventory.RemoveItem(item, amount); + taken += amount; + } + + if (taken > 0 && ContainerSaveMethod != null) ContainerSaveMethod.Invoke(chest, null); + return taken; + } + + // The wood that may be burnt. Only the wood chest's wood is ever consumed: the same wood in the + // entry chest is stock to be sorted, never fuel or charcoal. + private static readonly HashSet s_woodFamily = new HashSet + { + "Wood", "FineWood", "RoundLog", "ElderBark", "YggdrasilWood", "Blackwood", + }; + + private static bool IsWood(string prefabName) => s_woodFamily.Contains(prefabName); + + /// + /// The first thing a station will take, and the chest it is in: raw material from the ENTRY chest + /// (never its wood), and wood only from the WOOD chest. + /// + private string FindMaterialFor(ButlerStation station, out Container chest) + { + foreach (Container candidate in new[] { m_entry, m_wood }) + { + if (candidate == null || candidate.IsInUse()) continue; + + string item = FirstAccepted(station, candidate); + if (item == null) continue; + + chest = candidate; + return item; + } + + chest = null; + return null; + } + + private string FirstAccepted(ButlerStation station, Container chest) + { + Inventory inventory = chest != null ? chest.GetInventory() : null; + if (inventory == null) return null; + + bool woodChest = chest == m_wood; + string sigil = AlfarSigil.PrefabName; + string fuel = station.FuelPrefab; + + foreach (ItemDrop.ItemData item in inventory.GetAllItems()) + { + if (item == null || item.m_dropPrefab == null) continue; + + string name = item.m_dropPrefab.name; + if (name == sigil) continue; + if (name == fuel) continue; // fuel has its own errand + if (IsWood(name) != woodChest) continue; // wood from the wood chest, the rest from the entry + if (!station.Accepts(name)) continue; + + return name; + } + + return null; + } + + /// Fuel: wood-type fuel from the wood chest, anything else (coal) from the entry chest. + private Container FindChestWith(string prefabName) + { + Container chest = IsWood(prefabName) ? m_wood : m_entry; + if (chest == null || chest.IsInUse()) return null; + + Inventory inventory = chest.GetInventory(); + if (inventory == null) return null; + + foreach (ItemDrop.ItemData item in inventory.GetAllItems()) + { + if (item != null && item.m_dropPrefab != null && item.m_dropPrefab.name == prefabName) return chest; + } + return null; + } + + /// + /// Where the finished goods go: back to the ENTRY chest, which is both the inbox and the outbox; + /// they are sorted from there. If it is full, the nearest storage chest with room. + /// + private Container ChestForProduct() + { + if (m_entry != null && !m_entry.IsInUse() && !IsPenalised(ZdoOf(m_entry)) && HasRoomFor(m_entry)) return m_entry; + + Container best = null; + float bestDistance = float.MaxValue; + + foreach (Container chest in m_chests) + { + if (chest == null || chest.IsInUse()) continue; + if (IsPenalised(ZdoOf(chest))) continue; + if (!HasRoomFor(chest)) continue; + + float distance = Vector3.Distance(transform.position, chest.transform.position); + if (distance >= bestDistance) continue; + + bestDistance = distance; + best = chest; + } + + return best; + } + + private bool HasRoomFor(Container chest) + { + Inventory inventory = chest != null ? chest.GetInventory() : null; + if (inventory == null || ObjectDB.instance == null) return false; + + foreach (Load load in m_payload) + { + GameObject prefab = ObjectDB.instance.GetItemPrefab(load.Name); + if (prefab != null && inventory.CanAddItem(prefab, 1)) return true; + } + + return false; + } + + // ================================================================ payload + + private bool AcceptsAnything(ButlerStation station) + { + foreach (Load load in m_payload) + { + if (station.Accepts(load.Name)) return true; + if (load.Name == station.FuelPrefab && station.FuelWanted > 0) return true; + } + return false; + } + + private void AddToPayload(string name, int count) + { + if (string.IsNullOrEmpty(name) || count <= 0) return; + + foreach (Load load in m_payload) + { + if (load.Name != name) continue; + load.Count += count; + WritePayload(); + return; + } + + m_payload.Add(new Load { Name = name, Count = count }); + WritePayload(); + } + + private int PayloadCount() + { + int total = 0; + foreach (Load load in m_payload) total += load.Count; + return total; + } + + private string Describe() + { + if (m_payload.Count == 0) return "nothing"; + if (m_payload.Count == 1) return m_payload[0].Count + "x " + m_payload[0].Name; + + return PayloadCount() + " items"; + } + + /// "Copper:8;Coal:12". Small, readable in a ZDO dump, and enough to survive a handover + /// mid-job - which is the whole reason the payload lives in the ZDO instead of in this class. + private void WritePayload() + { + if (m_nview == null || !m_nview.IsValid()) return; + + StringBuilder builder = new StringBuilder(); + foreach (Load load in m_payload) + { + if (load.Count <= 0) continue; + if (builder.Length > 0) builder.Append(';'); + builder.Append(load.Name).Append(':').Append(load.Count); + } + + m_nview.GetZDO().Set(KeyLoad, builder.ToString()); + } + + private void ReadPayload() + { + m_payload.Clear(); + if (m_nview == null || !m_nview.IsValid()) return; + + string raw = m_nview.GetZDO().GetString(KeyLoad, ""); + if (string.IsNullOrEmpty(raw)) return; + + foreach (string entry in raw.Split(';')) + { + if (string.IsNullOrEmpty(entry)) continue; + + int split = entry.LastIndexOf(':'); + if (split <= 0) continue; + + int count; + if (!int.TryParse(entry.Substring(split + 1), out count) || count <= 0) continue; + + m_payload.Add(new Load { Name = entry.Substring(0, split), Count = count }); + } + } + + // ================================================================ small change + + private static ZDOID ZdoOf(Component component) + { + ZNetView nview = component != null ? component.GetComponent() : null; + return nview != null && nview.IsValid() ? nview.GetZDO().m_uid : ZDOID.None; + } + + private Container ContainerById(ZDOID id) + { + if (id == ZDOID.None || ZNetScene.instance == null) return null; + + GameObject go = ZNetScene.instance.FindInstance(id); + return go != null ? go.GetComponent() : null; + } + + private ButlerStation StationById(ZDOID id) + { + foreach (ButlerStation station in m_stations) + { + if (station.Id == id) return station; + } + + if (id == ZDOID.None || ZNetScene.instance == null) return null; + + GameObject go = ZNetScene.instance.FindInstance(id); + return go != null ? ButlerStation.From(go) : null; + } + + private void Penalise(ZDOID id) + { + if (id == ZDOID.None) return; + m_penalties[id] = Time.time + PenaltySeconds; + } + + /// Never shortens a penalty already running: a target set aside for three minutes + /// because it could not be reached must not be let back in after twenty seconds. + private void PenaliseShort(ZDOID id) + { + if (id == ZDOID.None) return; + + float until; + float wanted = Time.time + ShortPenaltySeconds; + if (m_penalties.TryGetValue(id, out until) && until > wanted) return; + + m_penalties[id] = wanted; + } + + private bool IsPenalised(ZDOID id) + { + float until; + return m_penalties.TryGetValue(id, out until) && Time.time < until; + } + + private void ExpirePenalties() + { + if (m_penalties.Count == 0) return; + + List done = null; + foreach (KeyValuePair entry in m_penalties) + { + if (Time.time < entry.Value) continue; + if (done == null) done = new List(); + done.Add(entry.Key); + } + + if (done == null) return; + foreach (ZDOID id in done) m_penalties.Remove(id); + } + + /// Seconds this station has been waiting with work available. + private float NoteIdle(ZDOID id) + { + float since; + if (!m_idleSince.TryGetValue(id, out since)) + { + m_idleSince[id] = Time.time; + return 0f; + } + + return Time.time - since; + } + } + + /// + /// The whole of the servant's mind, in one prefix. + /// + /// Returning false skips MonsterAI.UpdateAI entirely - targeting, alerting, fleeing, wandering and + /// attacking with it - so the servant is peaceful by construction rather than by having its weapon + /// confiscated. __result is legitimate here and not the old PlacePiece trap: that one threw because + /// the patched method was VOID. This one returns bool, which is exactly what a prefix may write. + /// + /// Bound positionally (__0) so a parameter rename in a future patch cannot stop the mod from + /// applying its patches at startup. + /// + [HarmonyPatch(typeof(MonsterAI), "UpdateAI")] + public static class AlfarDroneUpdateAIPatch + { + public static bool Prefix(MonsterAI __instance, float __0, ref bool __result) + { + if (__instance == null) return true; + + AlfarDroneAI servant = __instance.GetComponent(); + if (servant == null) return true; + + // The one way back into vanilla: a servant that fights back hands over the whole tick for + // as long as there is a fight. Always false for the Bone Servants themselves. + if (servant.HandsToVanilla()) return true; + + __result = servant.Tick(__0); + return false; + } + } + + /// Hit and it walks home. The same postfix shape the sentry's regeneration uses, on the + /// same method, which is a shape known to work in this project. + [HarmonyPatch(typeof(Character), "Damage")] + public static class AlfarDroneDamagePatch + { + public static void Postfix(Character __instance) + { + if (__instance == null) return; + + AlfarDroneAI servant = __instance.GetComponent(); + if (servant != null) servant.NoteDamage(); + } + } +} diff --git a/JotunnModStub/Alfar/AlfarDrones.cs b/JotunnModStub/Alfar/AlfarDrones.cs new file mode 100644 index 0000000..7cef524 --- /dev/null +++ b/JotunnModStub/Alfar/AlfarDrones.cs @@ -0,0 +1,365 @@ +using System.Collections.Generic; +using HarmonyLib; +using Jotunn.Entities; +using Jotunn.Managers; +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// The LJOSVAETTIR, the Alfar's drones (Alfar_Progettazione.txt sec. 9): a Deathsquito without legs, + /// stinger or buzz, bronze, with blue light. One kind of drone does every job (the work itself is + /// AlfarDroneWork); the only thing apart is the GRAFVAETTIR, the same creature thrown like a + /// grenade to dig the precious ores around a point for two minutes and then vanish. + /// + /// What a drone is by itself: 25 hp and a shield of 25, tamed, tied to its Ljoskjarne, and able to + /// defend itself with a lightning zap of 1 damage every two seconds. It never attacks anything + /// outside the Nexus's radius and never goes after anything: it is a worker, not a soldier. + /// + /// The Deathsquito is ONE skinned mesh with one material (probe, doc 16C P1): the legs are bones, so + /// they are hidden by scaling the bones to zero, and the blue is an emission on a bronze body, not + /// separate eyes and wings - a true repaint is still to do. + /// + public static class AlfarDrones + { + public const string DroneName = "AlfarDrone"; + public const string MinerName = "AlfarGrafvaettir"; + public const string ZapWeapon = "AlfarDroneZap"; + + private static readonly Color Bronze = new Color(1f, 0.62f, 0.25f, 1f); + private static readonly Color ElectricBlue = new Color(0.25f, 0.65f, 1f, 1f); + + public static void Register() + { + GameObject source = PrefabManager.Cache.GetPrefab("Deathsquito"); + if (source == null) + { + Jotunn.Logger.LogWarning("[Alfar] No 'Deathsquito' to build the drones from."); + return; + } + + bool zap = RegisterZap(source); + RegisterOne(source, DroneName, "$rov_creature_alfar_drone_name", zap, miner: false); + RegisterOne(source, MinerName, "$rov_creature_alfar_grafvaettir_name", zap, miner: true); + } + + /// The Deathsquito's sting turned into a zap: 1 lightning, every two seconds. + private static bool RegisterZap(GameObject deathsquito) + { + Humanoid humanoid = deathsquito.GetComponent(); + GameObject sting = humanoid != null && humanoid.m_defaultItems != null && humanoid.m_defaultItems.Length > 0 + ? humanoid.m_defaultItems[0] + : null; + if (sting == null) return false; + + GameObject weapon = PrefabManager.Instance.CreateClonedPrefab(ZapWeapon, sting); + if (weapon == null) return false; + + ItemDrop drop = weapon.GetComponent(); + if (drop == null || drop.m_itemData == null || drop.m_itemData.m_shared == null) return false; + + ItemDrop.ItemData.SharedData shared = drop.m_itemData.m_shared; + shared.m_name = "$rov_item_alfar_zap_name"; + + HitData.DamageTypes damage = default(HitData.DamageTypes); + damage.m_lightning = AlfarNexusConfig.DroneZapDamage.Value; + shared.m_damages = damage; + shared.m_aiAttackInterval = AlfarNexusConfig.DroneZapInterval.Value; + + ItemManager.Instance.AddItem(new CustomItem(weapon, fixReference: false)); + return true; + } + + private static void RegisterOne(GameObject source, string prefabName, string display, bool zap, bool miner) + { + GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(prefabName, source); + if (prefab == null) return; + + Character character = prefab.GetComponent(); + if (character != null) + { + character.m_name = display; + character.m_faction = Character.Faction.Players; + character.m_health = AlfarNexusConfig.DroneHealth.Value; + } + + Humanoid humanoid = prefab.GetComponent(); + if (humanoid != null) + { + GameObject weapon = zap ? PrefabManager.Instance.GetPrefab(ZapWeapon) : null; + // A miner does not fight at all; the worker only defends itself. + humanoid.m_defaultItems = !miner && weapon != null ? new[] { weapon } : new GameObject[0]; + humanoid.m_randomWeapon = new GameObject[0]; + humanoid.m_randomArmor = new GameObject[0]; + humanoid.m_randomShield = new GameObject[0]; + humanoid.m_randomSets = new Humanoid.ItemSet[0]; + } + + MonsterAI monster = prefab.GetComponent(); + if (monster != null) + { + monster.m_attackPlayerObjects = false; + monster.m_alertRange = AlfarNexusConfig.NexusRadius.Value; + monster.m_maxChaseDistance = AlfarNexusConfig.NexusRadius.Value; + } + + BaseAI ai = prefab.GetComponent(); + if (ai != null) ai.m_randomMoveRange = 5f; + + foreach (CharacterDrop drops in prefab.GetComponentsInChildren(true)) + { + if (drops != null) Object.DestroyImmediate(drops); + } + + // The buzz: the continuous sound child, and the flying loop effect. + foreach (Transform child in prefab.GetComponentsInChildren(true)) + { + if (child != null && child.name == "SFX") Object.DestroyImmediate(child.gameObject); + } + if (character != null) character.m_flyingContinuousEffect = new EffectList { m_effectPrefabs = new EffectList.EffectData[0] }; + + HideLegs(prefab); + Look(prefab); + prefab.AddComponent(); + + AlfarMark mark = prefab.AddComponent(); + mark.Role = miner ? "miner" : "drone"; + + AlfarCreatureShield shield = prefab.AddComponent(); + shield.MaxShield = AlfarNexusConfig.DroneHealth.Value; + shield.Shield = shield.MaxShield; + + if (miner) + { + // The mining drone has no anchor and no leash: it lives two minutes and vanishes. + prefab.AddComponent(); + } + else + { + // The worker is NOT a RaisedThrall: that brings the follow command on E, and a drone + // that can be walked out of the base stops working (the Butler's reasoning, Butler 9). + // AlfarDroneAI keeps its own anchor to the Nexus and its own wither. + AlfarDroneAI work = prefab.AddComponent(); + work.m_fightsBack = true; // it defends itself with the zap + work.m_homeDistance = 4f; + } + + PrefabManager.Instance.AddPrefab(prefab); + Jotunn.Logger.LogInfo($"[Alfar] Registered '{prefabName}'."); + } + + /// + /// No legs: the mesh is one skinned body, so the leg bones are scaled to zero and take their + /// part of the mesh with them. The stinger has no bone of its own and is left (doc 16C P1). + /// + private static void HideLegs(GameObject prefab) + { + foreach (Transform bone in prefab.GetComponentsInChildren(true)) + { + string n = bone.name; + if (n == "L.leg1" || n == "R.leg1") bone.localScale = Vector3.zero; + } + } + + private static void Look(GameObject prefab) + { + foreach (Renderer renderer in prefab.GetComponentsInChildren(true)) + { + Material[] materials = renderer.materials; + foreach (Material material in materials) + { + if (material == null) continue; + if (material.HasProperty("_Color")) material.color = Bronze; + if (material.HasProperty("_EmissionColor")) + { + material.SetColor("_EmissionColor", ElectricBlue * 0.15f); + material.EnableKeyword("_EMISSION"); + } + } + renderer.materials = materials; + } + foreach (Light light in prefab.GetComponentsInChildren(true)) light.color = ElectricBlue; + } + + /// + /// The same look, applied to the LIVE body at spawn and re-applied after the animator every + /// frame for the bones: edits made on the registered clone may not reach the instance, and the + /// animator can write the leg scale back. + /// + public class AlfarDroneLook : MonoBehaviour + { + private Transform[] legs; + + private void Awake() + { + var list = new System.Collections.Generic.List(); + foreach (Transform bone in GetComponentsInChildren(true)) + { + if (bone.name == "L.leg1" || bone.name == "R.leg1") list.Add(bone); + } + legs = list.ToArray(); + Look(gameObject); + } + + private void LateUpdate() + { + foreach (Transform leg in legs) if (leg != null) leg.localScale = Vector3.zero; + } + } + + // ─── Counting and spawning ─────────────────────────────────────────── + + public static int CountAlive(Vector3 anchor) + { + int count = 0; + foreach (AlfarDroneAI drone in AlfarDroneAI.All) + { + if (drone != null && drone.IsBoundTo(anchor)) count++; + } + return count; + } + + public static bool Spawn(Vector3 anchor) + { + GameObject prefab = ZNetScene.instance != null ? ZNetScene.instance.GetPrefab(DroneName) : null; + if (prefab == null) + { + Jotunn.Logger.LogWarning($"[Alfar] No '{DroneName}' in ZNetScene: no drone can be made."); + return false; + } + + Vector3 where = AlfarConstructs.SpawnSpot(anchor) + Vector3.up * 1.5f; + GameObject spawned = Object.Instantiate(prefab, where, Quaternion.identity); + AlfarDroneAI work = spawned != null ? spawned.GetComponent() : null; + if (work != null) work.Bind(anchor); + return spawned != null; + } + } + + /// + /// A MINING DRONE: thrown to a point, it digs the precious ores around that point for a fixed time + /// and then vanishes (design sec. 9.3). It takes over its own AI tick like the Butler's servants do + /// (a prefix on MonsterAI.UpdateAI), flies to the nearest deposit on the list and strikes it with + /// pickaxe damage at a tool tier high enough for any of them. The ore falls where it stands. + /// + /// Whatever it breaks is on the list in AlfarMiner.Deposits; a name list in the config so a + /// wrong or missing name is a config edit, not a rebuild. + /// + public class AlfarMiner : MonoBehaviour + { + public Vector3 Centre; + public float Radius = 12f; + public float LiveSeconds = 120f; + + private float born; + private float nextStrike; + private Component target; + + private static readonly System.Reflection.MethodInfo MoveToMethod = + AccessTools.Method(typeof(BaseAI), "MoveTo", new[] { typeof(float), typeof(Vector3), typeof(float), typeof(bool) }); + + private void Start() + { + born = Time.time; + } + + public bool Tick(MonsterAI ai, float dt) + { + if (Time.time - born >= LiveSeconds) + { + ZNetView nview = GetComponent(); + if (nview != null && nview.IsValid() && nview.IsOwner()) ZNetScene.instance.Destroy(gameObject); + return true; + } + + if (target == null || !target.gameObject.activeInHierarchy) target = FindDeposit(); + if (target == null) { ai.StopMoving(); return true; } + + Vector3 point = target.transform.position; + float distance = Vector3.Distance(transform.position, point); + + if (distance > 3.5f) + { + if (MoveToMethod != null) MoveToMethod.Invoke(ai, new object[] { dt, point + Vector3.up * 1.5f, 2f, true }); + return true; + } + + ai.StopMoving(); + if (Time.time < nextStrike) return true; + nextStrike = Time.time + 1f; + Strike(target); + return true; + } + + private static string[] names; + private static string[] Deposits => names ?? (names = AlfarNexusConfig.MinerDeposits.Value.Split( + new[] { ',' }, System.StringSplitOptions.RemoveEmptyEntries)); + + private bool IsPrecious(string prefabName) + { + foreach (string wanted in Deposits) + { + if (prefabName.IndexOf(wanted.Trim(), System.StringComparison.OrdinalIgnoreCase) >= 0) return true; + } + return false; + } + + private Component FindDeposit() + { + Component best = null; + float bestDistance = float.MaxValue; + foreach (Collider collider in Physics.OverlapSphere(Centre, Radius, ~0, QueryTriggerInteraction.Ignore)) + { + Component deposit = collider.GetComponentInParent(); + if (deposit == null) deposit = collider.GetComponentInParent(); + if (deposit == null) deposit = collider.GetComponentInParent(); + if (deposit == null) continue; + + string prefabName = Utils.GetPrefabName(deposit.gameObject); + if (!IsPrecious(prefabName)) continue; + + float distance = Vector3.Distance(transform.position, deposit.transform.position); + if (distance < bestDistance) { best = deposit; bestDistance = distance; } + } + return best; + } + + private void Strike(Component deposit) + { + IDestructible destructible = deposit as IDestructible; + if (destructible == null) return; + + HitData hit = new HitData(); + hit.m_damage.m_pickaxe = AlfarNexusConfig.MinerDamage.Value; + hit.m_toolTier = 100; + hit.m_dodgeable = false; + hit.m_blockable = false; + hit.m_point = deposit.transform.position; + hit.m_dir = (deposit.transform.position - transform.position).normalized; + + // MineRock5 picks the piece of the rock to hurt from the collider that was hit. + Collider collider = deposit.GetComponentInChildren(); + if (collider != null) + { + hit.m_hitCollider = collider; + hit.m_point = collider.bounds.center; + } + + destructible.Damage(hit); + } + + [HarmonyPatch(typeof(MonsterAI), "UpdateAI")] + public static class Alfar_Miner_UpdateAI_Patch + { + public static bool Prefix(MonsterAI __instance, float __0, ref bool __result) + { + if (__instance == null) return true; + AlfarMiner miner = __instance.GetComponent(); + if (miner == null) return true; + + __result = miner.Tick(__instance, __0); + return false; + } + } + } +} diff --git a/JotunnModStub/Alfar/AlfarEitr.cs b/JotunnModStub/Alfar/AlfarEitr.cs new file mode 100644 index 0000000..5d79655 --- /dev/null +++ b/JotunnModStub/Alfar/AlfarEitr.cs @@ -0,0 +1,166 @@ +using System.Reflection; +using HarmonyLib; +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// The Alfar's one resource (Alfar_Progettazione.txt sec. 3, 4 and 5.1): food becomes eitr, and + /// eitr is the shield. + /// + /// Every signature and call order here was read from assembly_valheim.dll (doc sec. 16B V1-V4), + /// not remembered: + /// - Character.ApplyDamage is the single final stage for direct hits, burning and poison + /// ticks AND falls, so one prefix on it covers all three; + /// - Player.RPC_UseEitr spends eitr and arms the vanilla regeneration delay, which is the + /// only brake the shield has - writing m_eitr by hand would skip the delay; + /// - Player.GetTotalFoodValue is what UpdateFood hands to SetMaxEitr. + /// + public static class AlfarEitr + { + private static readonly MethodInfo UseEitrRpc = + AccessTools.Method(typeof(Player), "RPC_UseEitr", new[] { typeof(long), typeof(float) }); + + /// + /// Spends eitr WITHOUT Game.m_eitrRate scaling, so the rate is exactly the configured one. + /// UseEitr would multiply by the world modifier first; the RPC does not, and it is what + /// arms the regeneration delay (V3). + /// + public static void Spend(Player player, float amount) + { + if (player == null || amount <= 0f) return; + + if (UseEitrRpc == null) + { + Jotunn.Logger.LogWarning("[Alfar] Player.RPC_UseEitr not found: the shield cannot spend eitr."); + return; + } + UseEitrRpc.Invoke(player, new object[] { 0L, amount }); + } + + // ─── Diet ──────────────────────────────────────────────────────────── + + /// + /// Each food adds min(hp, stamina) to the maximum eitr, on top of the eitr it already has. + /// Clarified by the user: the minimum is between hp and stamina ONLY, so a plain cooked + /// meat (40 / 30 / 0) is worth +30 eitr and a balanced food is better than a lopsided one. + /// + /// Locally only: GetTotalFoodValue is the owner's own bookkeeping. Positional parameters + /// (guide 5.16): __0 hp, __1 stamina, __2 eitr. + /// + [HarmonyPatch(typeof(Player), "GetTotalFoodValue")] + public static class Alfar_FoodValue_Patch + { + public static void Postfix(Player __instance, ref float __2) + { + if (__instance == null || !AlfarVisuals.IsAlfarPlayer(__instance)) return; + + float bonus = 0f; + foreach (Player.Food food in __instance.GetFoods()) + { + bonus += Mathf.Min(food.m_health, food.m_stamina); + } + + __2 += bonus * AlfarConfig.DietMultiplier.Value; + } + } + + // ─── Shield and soft fall ──────────────────────────────────────────── + + /// + /// Blows land on the eitr first, 1 for 1. + /// + /// - No cooldown: the shield absorbs for as long as one point of eitr remains. + /// - Lightning and spirit cost double (the cost, not the damage: DamageModifier.Weak is a + /// flat +50% and cannot be made to double anything). + /// - A blow bigger than the pool is shared out: the eitr takes the share it can, the body + /// takes the rest. + /// - Drowning and the edge of the world skip the shield altogether; falls are free while + /// there is eitr and shielded like anything else once there is none left. + /// + /// The prefix edits the HitData and lets ApplyDamage run: with nothing left in it, + /// ApplyDamage returns at once ("took no damage"). Positional parameters, and the argument + /// types are in the attribute so the patch binds to the real overload (guide 5.16). + /// + [HarmonyPatch(typeof(Character), "ApplyDamage", + new[] { typeof(HitData), typeof(bool), typeof(bool), typeof(HitData.DamageModifier) })] + public static class Alfar_ApplyDamage_Patch + { + public static void Prefix(Character __instance, HitData __0) + { + Player player = __instance as Player; + if (player == null || __0 == null) return; + if (!AlfarVisuals.IsAlfarPlayer(player)) return; + + // The shield belongs to whoever owns the body: ApplyDamage runs on the owner, and a + // remote copy must not spend eitr it does not hold. + ZNetView nview = player.GetComponent(); + if (nview == null || !nview.IsValid() || !nview.IsOwner()) return; + + // The same early exits ApplyDamage has: nothing to absorb, nothing to spend. + if (player.IsDead() || player.IsTeleporting() || player.InCutscene() || player.InGodMode()) return; + + // Just arrived by Heimkall: nothing hurts for a few seconds, or a burning death would + // simply repeat at the bed. + if (Time.time < AlfarHeimkall.InvulnerableUntil) + { + __0.m_damage = default(HitData.DamageTypes); + return; + } + + // In the archon form the pool IS the defence: it takes every blow, drowning and the + // edge of the world included, and the eitr is already spent (AlfarArchon). + if (AlfarArchon.Active) + { + AlfarArchon.Absorb(player, __0); + return; + } + + HitData.HitType type = __0.m_hitType; + if (type == HitData.HitType.Drowning || type == HitData.HitType.EdgeOfWorld) return; + + float available = player.GetEitr(); + + if (type == HitData.HitType.Fall && AlfarConfig.SoftFall.Value) + { + // Soft fall: free while there is eitr, a normal fall once there is none. + if (available > 0f) __0.m_damage = default(HitData.DamageTypes); + return; + } + + float cost = Cost(__0.m_damage); + if (cost <= 0f || available <= 0f) return; + + if (available >= cost) + { + Spend(player, cost); + __0.m_damage = default(HitData.DamageTypes); + return; + } + + // Shared out: the eitr absorbs the fraction it can pay for, the body takes the rest. + float covered = available / cost; + HitData.DamageTypes remaining = __0.m_damage; + remaining.Modify(1f - covered); + __0.m_damage = remaining; + Spend(player, available); + } + + /// + /// The eitr a blow costs. Every damage type that wounds a person counts; chop and + /// pickaxe are tool damage (trees, rocks) and do not. Lightning and spirit are doubled. + /// + private static float Cost(HitData.DamageTypes damage) + { + float rate = AlfarConfig.ShieldRate.Value; + float conductive = AlfarConfig.ConductiveMultiplier.Value; + + float ordinary = damage.m_damage + damage.m_blunt + damage.m_slash + damage.m_pierce + + damage.m_fire + damage.m_frost + damage.m_poison; + float double_ = damage.m_lightning + damage.m_spirit; + + return (ordinary + double_ * conductive) * rate; + } + } + } +} diff --git a/JotunnModStub/Alfar/AlfarHeimkall.cs b/JotunnModStub/Alfar/AlfarHeimkall.cs new file mode 100644 index 0000000..49a7dc4 --- /dev/null +++ b/JotunnModStub/Alfar/AlfarHeimkall.cs @@ -0,0 +1,171 @@ +using System.Globalization; +using HarmonyLib; +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// HEIMKALL: a lethal blow does not kill an Alfr, it sends them to their bed with one hit point + /// (Alfar_Progettazione.txt sec. 6). Then a wait: 20 minutes, 15 after Yagluth, 10 after Fader. + /// Inside the wait a lethal blow kills like it does anyone. + /// + /// HOW IT AVOIDS DEATH (read from the IL, doc sec. 16B V5): + /// Character.ApplyDamage ends with the health at zero, and the death itself is not decided + /// there but in Character.CheckDeath, which Character.CustomFixedUpdate calls on its next step. + /// So a POSTFIX on ApplyDamage that puts one hit point back, the same frame, means the check + /// finds a living body and there is no death routine, no tomb, no skill loss, no message. + /// + /// The timer lives in m_customData as a world-time stamp, so it survives a logout. + /// + public static class AlfarHeimkall + { + private const string TimerKey = "Alfar_HeimkallAt"; + + /// Time.time until which nothing may hurt the local Alfr (the arrival grace). + public static float InvulnerableUntil; + + // ─── The timer ─────────────────────────────────────────────────────── + + /// The cooldown for the current boss progress, in seconds. + public static float CooldownSeconds() + { + int state = BossProgressionManager.GetCurrentProgressionState(); + float minutes = state >= 8 ? AlfarConfig.HeimkallMinutesAfterFader.Value + : state >= 6 ? AlfarConfig.HeimkallMinutesAfterYagluth.Value + : AlfarConfig.HeimkallMinutes.Value; + return minutes * 60f; + } + + /// Seconds left before the next Heimkall; 0 when it is ready. + public static float Remaining(Player player) + { + if (player == null || player.m_customData == null || ZNet.instance == null) return 0f; + if (!player.m_customData.TryGetValue(TimerKey, out string stamp)) return 0f; + if (!double.TryParse(stamp, NumberStyles.Float, CultureInfo.InvariantCulture, out double at)) return 0f; + + double elapsed = ZNet.instance.GetTimeSeconds() - at; + + // A stamp from a different world (its clock is another clock) reads as the future, or as + // a wait longer than any cooldown. Either way the timer is not this world's: ready. + float cooldown = CooldownSeconds(); + if (elapsed < 0d || elapsed > 1e9) return 0f; + + return Mathf.Max(0f, cooldown - (float)elapsed); + } + + public static bool IsReady(Player player) => Remaining(player) <= 0f; + + public static void StartTimer(Player player) + { + if (player == null || ZNet.instance == null) return; + player.m_customData[TimerKey] = + ZNet.instance.GetTimeSeconds().ToString("R", CultureInfo.InvariantCulture); + } + + public static void ResetTimer(Player player) + { + if (player != null && player.m_customData != null) player.m_customData.Remove(TimerKey); + AlfarStatusEffects.ClearTimer("heimkall"); + } + + private static float nextIconSync; + + /// + /// Keeps the on-screen Heimkall countdown honest: status effects are not saved, so after a + /// reload the wait is put back on screen with what is really left of it, and removed when over. + /// + public static void SyncIcon(Player player) + { + if (Time.time < nextIconSync) return; + nextIconSync = Time.time + 2f; + + float left = Remaining(player); + bool shown = AlfarStatusEffects.HasTimer("heimkall"); + if (left > 0f && !shown) AlfarStatusEffects.ShowTimer("heimkall", left); + else if (left <= 0f && shown) AlfarStatusEffects.ClearTimer("heimkall"); + } + + // ─── The call home ─────────────────────────────────────────────────── + + /// + /// Teleports to the bed (or the world spawn when there is none) at one hit point, clears what + /// was killing the body, and starts the wait. Returns false when it is not ready. + /// + public static bool TryTrigger(Player player, string reason, bool force = false) + { + // force: the archon form ends with a Heimkall that it already paid for at the start. + if (player == null || (!force && !IsReady(player))) return false; + + bool bed; + Vector3 destination = FindDestination(out bed); + + // distantTeleport tells Valheim to stream the destination zone in first. Anything past a + // couple of zone-widths needs it. + bool distant = Vector3.Distance(player.transform.position, destination) > 100f; + bool teleported = player.TeleportTo(destination, player.transform.rotation, distant); + + // Whether or not the teleport was accepted (it refuses for two seconds after another + // one), the body must not die this frame. + player.SetHealth(1f); + + // What was killing the body goes with it: burning, poison, the cold, being wet. Cleared + // before the passive is put back, since RemoveAll takes that too. + player.GetSEMan().RemoveAllStatusEffects(true); + AlfarStatusEffects.Ensure(player); + + InvulnerableUntil = Time.time + AlfarConfig.HeimkallInvulnerableSeconds.Value; + StartTimer(player); + AlfarStatusEffects.ShowTimer("heimkall", CooldownSeconds()); + + Jotunn.Logger.LogInfo($"[Alfar] Heimkall ({reason}): teleported={teleported} to {destination}; " + + $"next in {CooldownSeconds() / 60f:0} min."); + player.Message(MessageHud.MessageType.Center, ModText.Get(bed ? "rov_msg_alfar_heimkall" : "rov_msg_alfar_heimkall_nobed")); + return true; + } + + /// + /// The bed the player set, else the world's original spawn. A bed point already has its height; + /// the world spawn is stored with a placeholder height (50), so its ground is worked out from the + /// world generator, which answers even when the zone there is not loaded yet - the first version + /// stood the Alfr at 50.5 m in the air or inside a hill. A bed counts only after the player has + /// SET it (sleeping in it, or interacting with it); an unused bed is not a spawn point. + /// + private static Vector3 FindDestination(out bool bed) + { + PlayerProfile profile = Game.instance != null ? Game.instance.GetPlayerProfile() : null; + + bed = profile != null && profile.HaveCustomSpawnPoint(); + if (bed) return profile.GetCustomSpawnPoint() + Vector3.up * 0.5f; + + Vector3 point = PlayerProfile.m_originalSpawnPoint; + if (WorldGenerator.instance != null) + { + float ground = WorldGenerator.instance.GetHeight(point.x, point.z); + point.y = Mathf.Max(ground, 30f) + 1f; // 30 is the sea level: never under the water + } + return point; + } + + // ─── The patch ─────────────────────────────────────────────────────── + + /// + /// After the blow has landed: if it left the body at zero, call it home instead. The shield + /// prefix has already taken what it could, so this only fires for the blow the eitr could + /// not cover (or a fall at eitr zero, a drowning, the edge of the world). + /// + [HarmonyPatch(typeof(Character), "ApplyDamage", + new[] { typeof(HitData), typeof(bool), typeof(bool), typeof(HitData.DamageModifier) })] + public static class Alfar_Heimkall_Patch + { + public static void Postfix(Character __instance) + { + Player player = __instance as Player; + if (player == null || player != Player.m_localPlayer) return; + if (!AlfarVisuals.IsAlfarPlayer(player)) return; + if (player.IsDead() || player.GetHealth() > 0f) return; + + TryTrigger(player, "lethal blow"); + } + } + } +} diff --git a/JotunnModStub/Alfar/AlfarLevitation.cs b/JotunnModStub/Alfar/AlfarLevitation.cs new file mode 100644 index 0000000..77f6b9d --- /dev/null +++ b/JotunnModStub/Alfar/AlfarLevitation.cs @@ -0,0 +1,120 @@ +using HarmonyLib; +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// LEVITATION (Alfar_Progettazione.txt sec. 4.6): in the air, hold the jump key and the Alfr rises + /// slowly, burning eitr slowly. Let go and the soft fall takes over. + /// + /// There is no hover in vanilla. This pushes the rigidbody's vertical speed up toward a small + /// target while the key is held, and nothing else: no horizontal speed is added, so it is a way + /// over a ledge or out of a pit and not flight (the pool of an early Alfr lasts about half a + /// minute of it). + /// + /// It runs on the owner's FixedUpdate, where the rigidbody is read, and the position syncs like + /// any other movement. The eitr is spent in small batches, not every physics step: each spend arms + /// the regeneration delay and goes through an RPC call. + /// + public static class AlfarLevitation + { + // A short moment in the air before it starts, so a normal jump (a tap) is just a jump. + private const float AirDelay = 0.2f; + private const float SpendInterval = 0.25f; + + private static float airTime; + private static float owed; + private static float nextSpend; + + public static bool Rising { get; private set; } + + [HarmonyPatch(typeof(Player), "FixedUpdate")] + public static class Alfar_Levitation_Patch + { + public static void Postfix(Player __instance) + { + if (__instance == null || __instance != Player.m_localPlayer) return; + if (!AlfarVisuals.IsAlfarPlayer(__instance) || __instance.IsDead()) { Reset(); return; } + + // THE ARCHON FLIES for as long as the form lasts: it hovers where it is, climbs while + // jump is held and sinks while crouch is held. The eitr is already gone, so nothing is + // spent. Horizontal movement stays the normal controls. + if (AlfarArchon.Active) + { + Rigidbody flyer = Traverse.Create(__instance).Field("m_body").GetValue(); + if (flyer != null) + { + float speed = AlfarPowerConfig.LevitationRise.Value * 2f; + float target = 0f; + if (Time.time - AlfarArchon.StartedAt < 0.6f) target = 4f; // lift off + else if (RaceInput.Allowed && JumpHeld()) target = speed; + else if (RaceInput.Allowed && ZInput.GetButton("Crouch")) target = -speed; + + Vector3 velocity = flyer.linearVelocity; + velocity.y = Mathf.Lerp(velocity.y, target, 0.25f); + flyer.linearVelocity = velocity; + } + Traverse.Create(__instance).Field("m_maxAirAltitude").SetValue(__instance.transform.position.y); + Rising = true; + return; + } + + bool wants = RaceInput.Allowed && JumpHeld(); + bool airborne = !__instance.IsOnGround() && !__instance.IsSwimming() && !__instance.IsAttached() && + !__instance.IsFlying(); + + airTime = airborne ? airTime + Time.fixedDeltaTime : 0f; + + float cost = AlfarPowerConfig.LevitationCostPerSecond.Value; + bool canPay = AlfarArchon.Active || __instance.GetEitr() > 0f; + + if (!wants || !airborne || airTime < AirDelay || !canPay) + { + Rising = false; + FlushSpend(__instance); + return; + } + + Rising = true; + + Rigidbody body = Traverse.Create(__instance).Field("m_body").GetValue(); + if (body != null) + { + Vector3 velocity = body.linearVelocity; + velocity.y = Mathf.Lerp(velocity.y, AlfarPowerConfig.LevitationRise.Value, 0.25f); + body.linearVelocity = velocity; + } + + // Rising resets the fall: the point of the soft fall is that the way down starts at + // the top, and a long climb must not count as a long drop at eitr zero. + Traverse.Create(__instance).Field("m_maxAirAltitude").SetValue(__instance.transform.position.y); + + // In the archon form the eitr is already gone and the pool pays for nothing here. + if (!AlfarArchon.Active) owed += cost * Time.fixedDeltaTime; + if (Time.time >= nextSpend) FlushSpend(__instance); + } + } + + private static bool JumpHeld() + { + // ZInput's "Jump" covers the space bar and the pad's jump button alike, and respects the + // controls the player picked in the settings. + return ZInput.GetButton("Jump"); + } + + private static void FlushSpend(Player player) + { + nextSpend = Time.time + SpendInterval; + if (owed <= 0f) return; + AlfarEitr.Spend(player, owed); + owed = 0f; + } + + private static void Reset() + { + airTime = 0f; + owed = 0f; + Rising = false; + } + } +} diff --git a/JotunnModStub/Alfar/AlfarLjosgard.cs b/JotunnModStub/Alfar/AlfarLjosgard.cs new file mode 100644 index 0000000..e70c5cb --- /dev/null +++ b/JotunnModStub/Alfar/AlfarLjosgard.cs @@ -0,0 +1,108 @@ +using System.Collections.Generic; +using Jotunn.Configs; +using Jotunn.Entities; +using Jotunn.Managers; +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// The LJOSGARD, the garden of light (Alfar_Progettazione.txt sec. 8.6 and 12): the module of the + /// Nexus that mixes the two mushrooms of the Mistlands into SAP, very slowly. + /// + /// It is a clone of the stone furnace with its recipe turned: MAGECAP is the "ore" and JOTUN PUFFS + /// the "fuel", one of each per sap, so mixing the two is exactly what a smelter already does with + /// its two inputs. Being a Smelter it needs no new code to be served: the drones feed it (a + /// Smelter-family station) and carry the sap away, and the refinery (vanilla, sap as fuel and soft + /// tissue as ore) is served by them too. Output falls where a furnace's does. + /// + public static class AlfarLjosgard + { + public const string PieceName = "AlfarLjosgard"; + public const string PieceDisplay = "$rov_piece_alfar_ljosgard_name"; + + public static void Register() + { + GameObject source = PrefabManager.Cache.GetPrefab("smelter"); + ItemDrop magecap = PrefabManager.Cache.GetPrefab("MushroomMagecap"); + ItemDrop puffs = PrefabManager.Cache.GetPrefab("MushroomJotunPuffs"); + ItemDrop sap = PrefabManager.Cache.GetPrefab("Sap"); + + if (source == null || magecap == null || puffs == null || sap == null) + { + Jotunn.Logger.LogWarning("[Alfar] The Ljosgard needs the 'smelter' piece and the Magecap, Jotun Puffs and Sap items: not registered."); + return; + } + + GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(PieceName, source); + if (prefab == null) return; + + // The furnace's heat and its fire: the Ljosgard is cool to the touch (guide 5.1). + AswidBloodRefinery.StripOffensive(prefab, "Ljosgard"); + + Smelter smelter = prefab.GetComponent(); + if (smelter == null) + { + Jotunn.Logger.LogWarning("[Alfar] The cloned smelter has no Smelter component: no Ljosgard."); + return; + } + + smelter.m_name = PieceDisplay; + smelter.m_conversion = new List + { + new Smelter.ItemConversion { m_from = magecap, m_to = sap }, + }; + smelter.m_fuelItem = puffs; + smelter.m_fuelPerProduct = 1; + smelter.m_maxOre = AlfarNexusConfig.GardCapacity.Value; + smelter.m_maxFuel = AlfarNexusConfig.GardCapacity.Value; + smelter.m_secPerProduct = AlfarNexusConfig.GardSecondsPerSap.Value; + smelter.m_requiresRoof = false; + smelter.m_spawnStack = false; + smelter.m_windmill = null; + + AlfarConstructs.Tint(prefab, new Color(0.55f, 0.85f, 0.7f, 1f)); + + Piece piece = prefab.GetComponent(); + if (piece == null) { Jotunn.Logger.LogWarning("[Alfar] The cloned smelter has no Piece."); return; } + + piece.m_craftingStation = null; + piece.m_name = PieceDisplay; + piece.m_description = "$rov_piece_alfar_ljosgard_desc"; + + PieceManager.Instance.AddPiece(new CustomPiece(prefab, fixReference: false, new PieceConfig + { + Name = PieceDisplay, + Description = "$rov_piece_alfar_ljosgard_desc", + PieceTable = PieceTables.Hammer, + Category = PieceCategories.Crafting, + Icon = piece.m_icon, + Requirements = new[] + { + new RequirementConfig("Bronze", AlfarNexusConfig.GardBronze.Value, 0, true), + new RequirementConfig("MushroomJotunPuffs", AlfarNexusConfig.GardMushrooms.Value, 0, true), + new RequirementConfig("MushroomMagecap", AlfarNexusConfig.GardMushrooms.Value, 0, true), + }, + })); + + // One per Ljoskjarne, inside its reach, and only for the Alfar. + PieceDensityLimit.Register(PieceName, AlfarNexusConfig.NexusRadius.Value, 1, "rov_msg_build_limit_alfar_ljosgard"); + PieceDensityLimit.RegisterGate(PieceName, (player, position) => + { + if (!AlfarRace.IsLocalAlfar()) + { + if (player != null) player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_alfar_only_alfar")); + return false; + } + if (AlfarNexusBehaviour.Covering(position) == null) + { + if (player != null) player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_alfar_gard_needs_nexus")); + return false; + } + return true; + }); + + AlfarPieces.Extra.Add(PieceName); + } + } +} diff --git a/JotunnModStub/Alfar/AlfarMark.cs b/JotunnModStub/Alfar/AlfarMark.cs new file mode 100644 index 0000000..2bfc3ae --- /dev/null +++ b/JotunnModStub/Alfar/AlfarMark.cs @@ -0,0 +1,149 @@ +using System.Collections.Generic; +using System.Reflection; +using HarmonyLib; +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// Marks a creature or a piece as one of the Alfar's own: a construct, a drone or a tower. + /// + /// What the mark does is decided in ONE place, the patches below, instead of editing every attack + /// of every cloned creature (Alfar_Progettazione.txt sec. 8.5 and 16C P4): + /// - everything the marked thing deals becomes LIGHTNING, with the same total; chop and pickaxe + /// are tool damage and are dropped; + /// - it never hurts an ally; + /// - it never hurts a building, a tree or a rock. + /// Intercepting the hit covers melee, projectiles and area attacks alike, whatever the vanilla + /// creature does with its weapons. + /// + public class AlfarMark : MonoBehaviour + { + /// "drone", "construct" or "tower": only for logs and the status command. + public string Role = ""; + + /// The attacker's mark, or null when the hit is not from one of ours. + public static AlfarMark Of(HitData hit) + { + if (hit == null) return null; + Character attacker = hit.GetAttacker(); + return attacker != null ? attacker.GetComponent() : null; + } + + /// All the damage that can wound a person, moved into lightning. Chop and pickaxe go. + public static void ConvertToLightning(HitData hit) + { + HitData.DamageTypes d = hit.m_damage; + float total = d.m_damage + d.m_blunt + d.m_slash + d.m_pierce + d.m_fire + d.m_frost + + d.m_poison + d.m_spirit + d.m_lightning; + + HitData.DamageTypes converted = default(HitData.DamageTypes); + converted.m_lightning = total; + hit.m_damage = converted; + } + } + + /// The blows of an Alfar creature: lightning only, and never on a friend. + [HarmonyPatch(typeof(Character), "Damage")] + public static class AlfarMark_CharacterDamage_Patch + { + public static bool Prefix(Character __instance, HitData __0) + { + AlfarMark mark = AlfarMark.Of(__0); + if (mark == null) return true; + + Character attacker = __0.GetAttacker(); + if (__instance == attacker) return false; + + // Nobody on our side is ever hurt by us: players, their tames, the other constructs. + if (!BaseAI.IsEnemy(attacker, __instance)) return false; + + AlfarMark.ConvertToLightning(__0); + return true; + } + } + + /// + /// Buildings, trees and rocks take nothing from the Alfar's creatures: the golem that razed its + /// owner's base would be a bug. One prefix on every kind of thing that can be struck. + /// + [HarmonyPatch] + public static class AlfarMark_StructureDamage_Patch + { + public static IEnumerable TargetMethods() + { + System.Type[] types = + { + typeof(WearNTear), typeof(Destructible), typeof(MineRock5), typeof(MineRock), + typeof(TreeBase), typeof(TreeLog), + }; + + foreach (System.Type type in types) + { + MethodBase method = AccessTools.Method(type, "Damage", new[] { typeof(HitData) }); + if (method != null) yield return method; + else Jotunn.Logger.LogWarning($"[Alfar] {type.Name}.Damage(HitData) not found: that structure is not protected from the Alfar's creatures."); + } + } + + public static bool Prefix(HitData __0) + { + return AlfarMark.Of(__0) == null; + } + } + + /// + /// A shield equal to the creature's health that comes back by itself: 1% of it per second once it + /// has gone five seconds without being hit (design sec. 8.5 and 9.6). Health does NOT come back: + /// the damage to the body is permanent, which is why a construct is rebuilt and not repaired. + /// + /// Its own absorption and not SE_Shield: the blow arrives at ApplyDamage, and what is left after + /// the shield is what reaches the health (the same stage the Alfr's own eitr shield uses). + /// + public class AlfarCreatureShield : MonoBehaviour + { + public float MaxShield; + public float Shield; + public float RegenPerSecondFraction = 0.01f; + public float QuietSeconds = 5f; + + private float lastHit = -999f; + + private void Awake() + { + if (Shield <= 0f) Shield = MaxShield; + } + + private void Update() + { + if (Shield >= MaxShield || Time.time - lastHit < QuietSeconds) return; + Shield = Mathf.Min(MaxShield, Shield + MaxShield * RegenPerSecondFraction * Time.deltaTime); + } + + public void Absorb(HitData hit) + { + float total = hit.m_damage.GetTotalDamage(); + if (total <= 0f) return; + + lastHit = Time.time; + float absorbed = Mathf.Min(Shield, total); + Shield -= absorbed; + + HitData.DamageTypes rest = hit.m_damage; + rest.Modify((total - absorbed) / total); + hit.m_damage = rest; + } + + [HarmonyPatch(typeof(Character), "ApplyDamage", + new[] { typeof(HitData), typeof(bool), typeof(bool), typeof(HitData.DamageModifier) })] + public static class Alfar_CreatureShield_Patch + { + public static void Prefix(Character __instance, HitData __0) + { + if (__0 == null || __instance is Player) return; + AlfarCreatureShield shield = __instance.GetComponent(); + if (shield != null) shield.Absorb(__0); + } + } + } +} diff --git a/JotunnModStub/Alfar/AlfarMiners.cs b/JotunnModStub/Alfar/AlfarMiners.cs new file mode 100644 index 0000000..59b3b22 --- /dev/null +++ b/JotunnModStub/Alfar/AlfarMiners.cs @@ -0,0 +1,104 @@ +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// GRAFVAETTIR, the mining grenade (Alfar_Progettazione.txt sec. 9.3): unlocked at Eikthyr, thrown + /// like a grenade at a point; five drones dig the precious ores around it for two minutes and + /// vanish. The ore falls where it stands, and nothing else limits it but its cost (eitr, a little + /// stone and flint) and a five minute wait. + /// + /// The thrown part is only the spawn; the digging is AlfarMiner on the drones themselves. + /// + public static class AlfarMiners + { + private static float readyAt; + + public static void Tick(Player player) + { + // Nothing to tick per frame: the miners run themselves. Kept so the power loop treats + // every power the same way. + } + + public static void Throw(Player player) + { + if (Time.time < readyAt) return; + + Transform aim = GameCamera.instance != null ? GameCamera.instance.transform : player.transform; + Vector3 origin = aim.position; + Vector3 direction = aim.forward; + float range = AlfarPowerConfig.GrafRange.Value; + + Vector3 point = origin + direction * range; + foreach (RaycastHit hit in Physics.RaycastAll(origin, direction, range, ~0, QueryTriggerInteraction.Ignore)) + { + if (hit.collider.GetComponentInParent() == player) continue; + if (Vector3.Distance(origin, hit.point) < Vector3.Distance(origin, point)) point = hit.point; + } + + // The price: a little eitr, a little stone, a little flint. + string stone = SharedName("Stone"); + string flint = SharedName("Flint"); + int needStone = AlfarPowerConfig.GrafStone.Value; + int needFlint = AlfarPowerConfig.GrafFlint.Value; + float eitr = AlfarPowerConfig.GrafEitr.Value; + + Inventory inventory = player.GetInventory(); + if (inventory.CountItems(stone, -1, false) < needStone || inventory.CountItems(flint, -1, false) < needFlint) + { + player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_alfar_graf_materials", needStone, needFlint)); + return; + } + if (player.GetEitr() < eitr) + { + player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_alfar_no_eitr")); + return; + } + + GameObject prefab = ZNetScene.instance != null ? ZNetScene.instance.GetPrefab(AlfarDrones.MinerName) : null; + if (prefab == null) + { + Jotunn.Logger.LogWarning($"[Alfar] No '{AlfarDrones.MinerName}' in ZNetScene: the mining drones cannot be thrown."); + return; + } + + inventory.RemoveItem(stone, needStone, -1, false); + inventory.RemoveItem(flint, needFlint, -1, false); + AlfarEitr.Spend(player, eitr); + readyAt = Time.time + AlfarPowerConfig.GrafCooldown.Value; + AlfarStatusEffects.ShowTimer("graf", AlfarPowerConfig.GrafCooldown.Value); + + int count = AlfarPowerConfig.GrafCount.Value; + for (int i = 0; i < count; i++) + { + Vector2 offset = Random.insideUnitCircle * 1.5f; + Vector3 where = point + new Vector3(offset.x, 1.5f + i * 0.2f, offset.y); + GameObject spawned = Object.Instantiate(prefab, where, Quaternion.identity); + + AlfarMiner miner = spawned.GetComponent(); + if (miner != null) + { + miner.Centre = point; + miner.Radius = AlfarPowerConfig.GrafRadius.Value; + miner.LiveSeconds = AlfarPowerConfig.GrafSeconds.Value; + } + + // Tame at once so nothing flees them and they flee nothing; no anchor, no leash. + MonsterAI ai = spawned.GetComponent(); + Character character = spawned.GetComponent(); + if (ai != null) ai.MakeTame(); + if (character != null) character.SetTamed(true); + } + + AlfarFx.Spawn("fx_JotunWitch_LightningBolt_Explosion", point); + Jotunn.Logger.LogInfo($"[Alfar] Grafvaettir thrown: {count} at {point}."); + } + + private static string SharedName(string prefabName) + { + GameObject prefab = ObjectDB.instance != null ? ObjectDB.instance.GetItemPrefab(prefabName) : null; + ItemDrop drop = prefab != null ? prefab.GetComponent() : null; + return drop != null ? drop.m_itemData.m_shared.m_name : prefabName; + } + } +} diff --git a/JotunnModStub/Alfar/AlfarNexus.cs b/JotunnModStub/Alfar/AlfarNexus.cs new file mode 100644 index 0000000..8ba5ac9 --- /dev/null +++ b/JotunnModStub/Alfar/AlfarNexus.cs @@ -0,0 +1,576 @@ +using System.Collections.Generic; +using System.Text; +using HarmonyLib; +using Jotunn.Configs; +using Jotunn.Entities; +using Jotunn.Managers; +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// The LJOSKJARNE, the Alfar's Nexus (Alfar_Progettazione.txt sec. 8): the one piece the whole + /// base hangs from. It makes the drones and the constructs, it keeps the crystals, and the towers + /// and the drones only work inside its radius. One per 1.6 km2 like the other races' stations. + /// + /// ONE INTERACTION POINT (guide 4.7): E opens the vanilla merchant window with a row per product + /// (AlfarNexusStore), the way the Trol's war totem and the Dvergar's contract bank do. The first + /// version stepped through the products with Shift+E, which gave trouble in other races' tests, and + /// the player asked for the store. The prices are not coins: they come out of the pack, and the + /// row's tooltip lists them with how many exist and how many are allowed. + /// + /// Everything is paid from the player's inventory. The crystals the Nexus makes (after the + /// Kristallvigsla) pile up inside it, a beehive's way - slowly, to a cap, and it stops when full + /// until somebody collects - and "collect" moves them to the pack. + /// + public static class AlfarNexus + { + public const string PieceName = "AlfarNexus"; + public const string PieceDisplay = "$rov_piece_alfar_nexus_name"; + + public static void Register() + { + GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(PieceName, "piece_cartographytable"); + if (prefab == null) + { + Jotunn.Logger.LogWarning("[Alfar] Could not clone piece_cartographytable; the Ljoskjarne is not registered."); + return; + } + + // The MapTable trap (Butler 4.1): MapTable is Interactable AND Hoverable and takes the E + // key before our Switch sees it. Everything goes except what makes it a building. + foreach (MonoBehaviour behaviour in prefab.GetComponentsInChildren(true)) + { + if (behaviour == null) continue; + if (behaviour is Piece || behaviour is ZNetView || behaviour is WearNTear) continue; + Object.DestroyImmediate(behaviour); + } + + AlfarConstructs.Tint(prefab, new Color(0.62f, 0.8f, 1f, 1f)); + + AlfarNexusBehaviour nexus = prefab.AddComponent(); + nexus.m_switch = prefab.AddComponent(); + nexus.m_switch.m_name = PieceDisplay; + + // A Trader with an empty catalogue: StoreGui needs one to open at all, and the rows are drawn + // by AlfarNexusStore. Disabled and with every list filled, for the reasons the Trol's totem + // spells out (Trader.Update and Start assume an animator and a look-at rig that a nucleus + // does not have, and an unfilled list sends Trader.Interact into a null Say). + Trader trader = prefab.GetComponent() ?? prefab.AddComponent(); + trader.m_name = PieceDisplay; + trader.enabled = false; + trader.m_items = new List(); + trader.m_useItems = new List(); + trader.m_randomTalk = new List(); + trader.m_randomGreets = new List(); + trader.m_randomGoodbye = new List(); + trader.m_randomStartTrade = new List(); + trader.m_randomBuy = new List(); + trader.m_randomSell = new List(); + trader.m_randomGiveItemNo = new List(); + trader.m_randomUseItemAlreadyRecieved = new List(); + trader.m_randomTalkConditionals = new List(); + + Sprite icon = BorrowIcon("Eitr") ?? BorrowIcon("SurtlingCore"); + + Piece piece = prefab.GetComponent() ?? prefab.AddComponent(); + piece.m_craftingStation = null; + piece.m_resources = new Piece.Requirement[0]; + piece.m_name = PieceDisplay; + piece.m_canBeRemoved = true; + piece.m_groundPiece = false; + piece.m_groundOnly = false; + piece.m_icon = icon; + + Piece template = PrefabManager.Cache.GetPrefab("piece_workbench"); + if (template != null && template.m_placeEffect != null) piece.m_placeEffect = template.m_placeEffect; + + PieceManager.Instance.AddPiece(new CustomPiece(prefab, fixReference: false, new PieceConfig + { + Name = PieceDisplay, + Description = "$rov_piece_alfar_nexus_desc", + PieceTable = PieceTables.Hammer, + Category = PieceCategories.Crafting, + Icon = icon, + Requirements = new[] + { + new RequirementConfig("Bronze", AlfarNexusConfig.NexusBronze.Value, 0, true), + new RequirementConfig("Stone", AlfarNexusConfig.NexusStone.Value, 0, true), + }, + })); + + PieceDensityLimit.Register(PieceName, PieceDensityLimit.RadiusForArea(AlfarNexusConfig.NexusDensityKm2.Value), + 1, "rov_msg_build_limit_alfar_nexus"); + PieceDensityLimit.RegisterGate(PieceName, (player, position) => + { + if (AlfarRace.IsLocalAlfar()) return true; + if (player != null) player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_alfar_only_alfar")); + return false; + }); + } + + public static Sprite BorrowIcon(string prefabName) + { + ItemDrop drop = PrefabManager.Cache.GetPrefab(prefabName); + Sprite[] icons = drop != null && drop.m_itemData != null && drop.m_itemData.m_shared != null + ? drop.m_itemData.m_shared.m_icons + : null; + return icons != null && icons.Length > 0 ? icons[0] : null; + } + + /// Teaches the player the Alfar's pieces: a piece registered after the learning pass does not reach its table alone (guide 4.4). + public static void EnsureKnown(Player player) + { + if (player == null || !AlfarVisuals.IsAlfarPlayer(player)) return; + + Traverse traverse = Traverse.Create(player); + foreach (string name in AlfarPieces.AllNames()) + { + GameObject prefab = PrefabManager.Instance.GetPrefab(name); + Piece piece = prefab != null ? prefab.GetComponent() : null; + if (piece != null) traverse.Method("AddKnownPiece", piece).GetValue(); + } + traverse.Method("UpdateAvailablePiecesList").GetValue(); + } + } + + /// The names of every piece the Alfar can build, in one place for the lock and for learning. + public static class AlfarPieces + { + public static readonly List Extra = new List(); + + public static IEnumerable AllNames() + { + yield return AlfarNexus.PieceName; + foreach (string name in Extra) yield return name; + } + } + + [HarmonyPatch(typeof(Player), "OnSpawned")] + public static class AlfarKnownPatch + { + public static void Postfix(Player __instance) + { + if (__instance != Player.m_localPlayer) return; + AlfarNexus.EnsureKnown(__instance); + } + } + + public class AlfarNexusBehaviour : MonoBehaviour + { + public Switch m_switch; + + public static readonly List All = new List(); + + private const string KeySelected = "RoV_alfarSel"; + private const string KeyUpgrade = "RoV_alfarUp"; + private const string KeyCrystals = "RoV_alfarCr"; + private const string KeyCrystalAt = "RoV_alfarCrAt"; + + public enum Product { Drone = 0, Neistvordr = 1, Eldingvordr = 2, Steinvordr = 3, Upgrade = 4, Collect = 5 } + private static readonly int ProductCount = System.Enum.GetValues(typeof(Product)).Length; + + private ZNetView m_nview; + + private void Awake() + { + m_nview = GetComponent(); + All.Add(this); + RaisedThrall.RegisterStation(transform); + + if (m_switch != null) + { + m_switch.m_onUse = OnUse; + m_switch.m_onHover = Hover; + } + } + + private void OnDestroy() + { + All.Remove(this); + RaisedThrall.UnregisterStation(transform); + } + + /// The nearest Ljoskjarne whose radius covers the point, or null. + public static AlfarNexusBehaviour Covering(Vector3 point) + { + AlfarNexusBehaviour best = null; + float bestDistance = float.MaxValue; + foreach (AlfarNexusBehaviour nexus in All) + { + if (nexus == null) continue; + float distance = Vector3.Distance(nexus.transform.position, point); + if (distance <= AlfarNexusConfig.NexusRadius.Value && distance < bestDistance) + { + best = nexus; + bestDistance = distance; + } + } + return best; + } + + // ─── State ─────────────────────────────────────────────────────────── + + private bool Upgraded => m_nview != null && m_nview.IsValid() && m_nview.GetZDO().GetInt(KeyUpgrade, 0) == 1; + public int Crystals => m_nview != null && m_nview.IsValid() ? m_nview.GetZDO().GetInt(KeyCrystals, 0) : 0; + + private Product Selected + { + get + { + int value = m_nview != null && m_nview.IsValid() ? m_nview.GetZDO().GetInt(KeySelected, 0) : 0; + return (Product)Mathf.Clamp(value, 0, ProductCount - 1); + } + } + + private bool Available(Product product) + { + bool constructsOpen = Upgraded && BossProgressionManager.GetCurrentProgressionState() >= AlfarNexusConfig.ConstructState; + switch (product) + { + case Product.Drone: return true; + case Product.Neistvordr: + case Product.Eldingvordr: + case Product.Steinvordr: return constructsOpen; + case Product.Upgrade: return !Upgraded; + case Product.Collect: return Upgraded; + } + return false; + } + + // ─── Crystals: a beehive's way ─────────────────────────────────────── + + /// + /// One crystal per Time Factor beehive-intervals of WORLD time, up to the cap, and nothing while + /// full: the clock restarts when somebody collects, like the honey. Only the owner counts. + /// The beehive's own interval is read, not copied (guide 3.2) - and only the INTERVAL, not its + /// daylight rule: the Alfar have no light mechanic (doc sec. 8.6). + /// + private void Update() + { + if (m_nview == null || !m_nview.IsValid() || !m_nview.IsOwner() || !Upgraded || ZNet.instance == null) return; + + ZDO zdo = m_nview.GetZDO(); + int cap = AlfarNexusConfig.CrystalCap.Value; + int stored = zdo.GetInt(KeyCrystals, 0); + double now = ZNet.instance.GetTimeSeconds(); + + if (stored >= cap) { zdo.Set(KeyCrystalAt, now.ToString("R", System.Globalization.CultureInfo.InvariantCulture)); return; } + + string stamp = zdo.GetString(KeyCrystalAt, ""); + if (!double.TryParse(stamp, System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out double at)) + { + zdo.Set(KeyCrystalAt, now.ToString("R", System.Globalization.CultureInfo.InvariantCulture)); + return; + } + + float interval = CrystalInterval(); + int made = Mathf.FloorToInt((float)((now - at) / interval)); + if (made <= 0) return; + + stored = Mathf.Min(cap, stored + made); + zdo.Set(KeyCrystals, stored); + zdo.Set(KeyCrystalAt, (at + made * interval).ToString("R", System.Globalization.CultureInfo.InvariantCulture)); + } + + /// Seconds per crystal: Time Factor times a vanilla beehive's seconds per honey. + public static float CrystalInterval() + { + Beehive hive = TrentaConfig.FindVanillaBeehive(); + float honey = hive != null && hive.m_secPerUnit > 0f ? hive.m_secPerUnit : 1200f; + return honey * AlfarNexusConfig.CrystalTimeFactor.Value; + } + + // ─── Costs ─────────────────────────────────────────────────────────── + + private struct Cost + { + public string Item; + public int Amount; + public Cost(string item, int amount) { Item = item; Amount = amount; } + } + + private static List CostOf(Product product) + { + switch (product) + { + case Product.Drone: + return new List { new Cost("Bronze", AlfarNexusConfig.DroneBronze.Value) }; + case Product.Neistvordr: + return new List + { + new Cost("Bronze", AlfarNexusConfig.NeistMetal.Value), + new Cost("Crystal", AlfarNexusConfig.NeistCrystal.Value), + new Cost("Eitr", AlfarNexusConfig.NeistEitr.Value), + }; + case Product.Eldingvordr: + return new List + { + new Cost("Iron", AlfarNexusConfig.EldingMetal.Value), + new Cost("Crystal", AlfarNexusConfig.EldingCrystal.Value), + new Cost("Eitr", AlfarNexusConfig.EldingEitr.Value), + }; + case Product.Steinvordr: + return new List + { + new Cost("BlackMetal", AlfarNexusConfig.SteinMetal.Value), + new Cost("Crystal", AlfarNexusConfig.SteinCrystal.Value), + new Cost("Eitr", AlfarNexusConfig.SteinEitr.Value), + }; + case Product.Upgrade: + return new List { new Cost("Crystal", AlfarNexusConfig.UpgradeCrystals.Value) }; + } + return new List(); + } + + private static string SharedName(string prefabName) + { + GameObject prefab = ObjectDB.instance != null ? ObjectDB.instance.GetItemPrefab(prefabName) : null; + ItemDrop drop = prefab != null ? prefab.GetComponent() : null; + return drop != null ? drop.m_itemData.m_shared.m_name : prefabName; + } + + private static bool CanPay(Player player, List costs) + { + foreach (Cost cost in costs) + { + if (cost.Amount <= 0) continue; + if (player.GetInventory().CountItems(SharedName(cost.Item), -1, false) < cost.Amount) return false; + } + return true; + } + + private static void Pay(Player player, List costs) + { + foreach (Cost cost in costs) + { + if (cost.Amount > 0) player.GetInventory().RemoveItem(SharedName(cost.Item), cost.Amount, -1, false); + } + } + + private static string CostText(List costs) + { + var parts = new List(); + foreach (Cost cost in costs) + { + if (cost.Amount > 0) parts.Add($"{cost.Amount} {Localization.instance.Localize(SharedName(cost.Item))}"); + } + return parts.Count == 0 ? "-" : string.Join(", ", parts); + } + + // ─── Counts and caps ───────────────────────────────────────────────── + + private int AliveOf(Product product) + { + Vector3 anchor = transform.position; + switch (product) + { + case Product.Drone: return AlfarDrones.CountAlive(anchor); + case Product.Neistvordr: return AlfarConstructs.CountAlive(anchor, AlfarConstructs.Neistvordr); + case Product.Eldingvordr: return AlfarConstructs.CountAlive(anchor, AlfarConstructs.Eldingvordr); + case Product.Steinvordr: return AlfarConstructs.CountAlive(anchor, AlfarConstructs.Steinvordr); + } + return 0; + } + + private static int CapOf(Product product) + { + switch (product) + { + case Product.Drone: return AlfarNexusConfig.DroneCap.Value; + case Product.Neistvordr: return AlfarNexusConfig.NeistCap.Value; + case Product.Eldingvordr: return AlfarNexusConfig.EldingCap.Value; + case Product.Steinvordr: return AlfarNexusConfig.SteinCap.Value; + } + return int.MaxValue; + } + + private static string NameOf(Product product) => ModText.Get("rov_alfar_product_" + product.ToString().ToLowerInvariant()); + + // ─── Interaction ───────────────────────────────────────────────────── + + private string Hover() + { + var sb = new StringBuilder(); + sb.AppendLine(Localization.instance.Localize(AlfarNexus.PieceDisplay)); + sb.AppendLine($"[$KEY_Use] {ModText.Get("rov_alfar_nexus_open")}"); + + if (Upgraded) sb.AppendLine(ModText.Get("rov_alfar_nexus_crystals", Crystals, AlfarNexusConfig.CrystalCap.Value)); + else sb.AppendLine(ModText.Get("rov_alfar_nexus_no_upgrade")); + + return Localization.instance.Localize(sb.ToString()); + } + + private bool OnUse(Switch sw, Humanoid user, ItemDrop.ItemData item) + { + Player player = user as Player; + if (player == null || m_nview == null || !m_nview.IsValid()) return false; + + if (!AlfarVisuals.IsAlfarPlayer(player)) + { + player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_alfar_only_alfar")); + return item != null; + } + + // Holding something is not a way to use the nucleus: it only opens the store. + if (item != null) + { + player.Message(MessageHud.MessageType.Center, "$msg_wontwork"); + return true; + } + + Trader trader = GetComponent(); + if (trader == null || StoreGui.instance == null) + { + player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_alfar_nexus_no_store")); + return false; + } + + // The store reads the nucleus back out of StoreGui's own m_trader when it repaints. + StoreGui.instance.Show(trader); + return true; + } + + // ─── What the store window uses ────────────────────────────────────── + + /// The products on offer right now, in the order the rows are drawn. + public List OnOffer() + { + var list = new List(); + foreach (Product product in System.Enum.GetValues(typeof(Product))) + { + if (Available(product)) list.Add(product); + } + return list; + } + + /// Builds a product from the row the player clicked. Every check Build makes still applies. + public void BuildFromStore(Product product) + { + Player player = Player.m_localPlayer; + if (player == null || m_nview == null || !m_nview.IsValid() || !Available(product)) return; + + m_nview.ClaimOwnership(); + Build(player, product); + } + + /// The short number on a row: the metal (or the crystals of the upgrade) it costs. + public static string PriceShort(Product product) + { + foreach (Cost cost in CostOf(product)) + { + if (cost.Amount > 0) return cost.Amount.ToString(); + } + return "-"; + } + + /// The full terms for the row's tooltip: the price, how many exist, how many are allowed. + public string Terms(Product product) + { + var sb = new StringBuilder(); + sb.AppendLine(CostText(CostOf(product))); + + int cap = CapOf(product); + if (cap != int.MaxValue) sb.AppendLine(ModText.Get("rov_alfar_store_count", AliveOf(product), cap)); + if (product == Product.Collect) sb.AppendLine(ModText.Get("rov_alfar_nexus_crystals", Crystals, AlfarNexusConfig.CrystalCap.Value)); + + sb.Append(ModText.Get("rov_alfar_store_terms")); + return sb.ToString(); + } + + public static string ProductName(Product product) => NameOf(product); + + private void Build(Player player, Product product) + { + List costs = CostOf(product); + + if (product == Product.Collect) + { + Collect(player); + return; + } + + if (AliveOf(product) >= CapOf(product)) + { + player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_alfar_nexus_cap")); + return; + } + + if (!CanPay(player, costs)) + { + player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_alfar_nexus_cannot_pay", CostText(costs))); + return; + } + + bool done; + switch (product) + { + case Product.Drone: done = AlfarDrones.Spawn(transform.position); break; + case Product.Neistvordr: done = AlfarConstructs.Spawn(transform.position, AlfarConstructs.Neistvordr); break; + case Product.Eldingvordr: done = AlfarConstructs.Spawn(transform.position, AlfarConstructs.Eldingvordr); break; + case Product.Steinvordr: done = AlfarConstructs.Spawn(transform.position, AlfarConstructs.Steinvordr); break; + case Product.Upgrade: done = true; break; + default: done = false; break; + } + if (!done) return; + + Pay(player, costs); + + if (product == Product.Upgrade) + { + ZDO zdo = m_nview.GetZDO(); + zdo.Set(KeyUpgrade, 1); + zdo.Set(KeyCrystalAt, ZNet.instance.GetTimeSeconds().ToString("R", System.Globalization.CultureInfo.InvariantCulture)); + player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_alfar_nexus_upgraded")); + } + else + { + player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_alfar_nexus_built", NameOf(product))); + } + } + + private void Collect(Player player) + { + int stored = Crystals; + if (stored <= 0) + { + player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_alfar_nexus_no_crystals")); + return; + } + + GameObject prefab = ObjectDB.instance != null ? ObjectDB.instance.GetItemPrefab("Crystal") : null; + if (prefab == null) return; + + // Whatever fits goes in the pack; the rest stays in the Nexus. + int taken = 0; + for (int i = 0; i < stored; i++) + { + if (!player.GetInventory().CanAddItem(prefab, 1)) break; + if (!player.GetInventory().AddItem(prefab, 1)) break; + taken++; + } + + if (taken > 0) + { + ZDO zdo = m_nview.GetZDO(); + zdo.Set(KeyCrystals, stored - taken); + // Collecting restarts the clock, like emptying a hive. + zdo.Set(KeyCrystalAt, ZNet.instance.GetTimeSeconds().ToString("R", System.Globalization.CultureInfo.InvariantCulture)); + } + player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_alfar_nexus_collected", taken)); + } + + /// Crystals a drone may carry away from the Nexus, and the call that does it (used by the drone's work). + public int TakeCrystals(int wanted) + { + if (m_nview == null || !m_nview.IsValid() || !m_nview.IsOwner()) return 0; + int stored = Crystals; + int taken = Mathf.Min(stored, wanted); + if (taken <= 0) return 0; + ZDO zdo = m_nview.GetZDO(); + zdo.Set(KeyCrystals, stored - taken); + zdo.Set(KeyCrystalAt, ZNet.instance.GetTimeSeconds().ToString("R", System.Globalization.CultureInfo.InvariantCulture)); + return taken; + } + } +} diff --git a/JotunnModStub/Alfar/AlfarNexusConfig.cs b/JotunnModStub/Alfar/AlfarNexusConfig.cs new file mode 100644 index 0000000..59c4020 --- /dev/null +++ b/JotunnModStub/Alfar/AlfarNexusConfig.cs @@ -0,0 +1,144 @@ +using BepInEx.Configuration; +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// The numbers of the Alfar's base: the Nexus, its drones, the constructs, the towers and the + /// crystals (Alfar_Progettazione.txt sec. 8, 9 and 19). All starting values, all to be corrected + /// in play, none in the logic files. + /// + public static class AlfarNexusConfig + { + // The progression state the constructs open at (BossProgressionManager: 6 = Yagluth down). + public const int ConstructState = 6; + + // ─── The Nexus ─────────────────────────────────────────────────────── + public static ConfigEntry NexusRadius; + public static ConfigEntry NexusDensityKm2; + public static ConfigEntry NexusBronze; + public static ConfigEntry NexusStone; + + // ─── Drones ────────────────────────────────────────────────────────── + public static ConfigEntry DroneBronze; + public static ConfigEntry DroneCap; + public static ConfigEntry DroneHealth; + public static ConfigEntry DroneZapDamage; + public static ConfigEntry DroneZapInterval; + + // ─── Mining drones ─────────────────────────────────────────────────── + public static ConfigEntry MinerDeposits; + public static ConfigEntry MinerDamage; + public static ConfigEntry WildPickables; + + // ─── Constructs ────────────────────────────────────────────────────── + public static ConfigEntry NeistMetal; + public static ConfigEntry NeistCrystal; + public static ConfigEntry NeistEitr; + public static ConfigEntry NeistCap; + + public static ConfigEntry EldingMetal; + public static ConfigEntry EldingCrystal; + public static ConfigEntry EldingEitr; + public static ConfigEntry EldingCap; + + public static ConfigEntry SteinMetal; + public static ConfigEntry SteinCrystal; + public static ConfigEntry SteinEitr; + public static ConfigEntry SteinCap; + + public static ConfigEntry ConstructLeash; + public static ConfigEntry ConstructAlertRange; + public static ConfigEntry WitherSeconds; + + public static ConfigEntry SphereDamage; + public static ConfigEntry SphereIntervalSeconds; + public static ConfigEntry SphereRange; + + // ─── Crystals ──────────────────────────────────────────────────────── + public static ConfigEntry UpgradeCrystals; + public static ConfigEntry CrystalCap; + public static ConfigEntry CrystalTimeFactor; + + // ─── Towers ────────────────────────────────────────────────────────── + public static ConfigEntry TowerBronze; + public static ConfigEntry TowerCrystal; + public static ConfigEntry TowerHealthFactor; + public static ConfigEntry TowerDamage; + public static ConfigEntry TowerScale; + + // ─── Ljosgard (sap) and chests ─────────────────────────────────────── + public static ConfigEntry GardBronze; + public static ConfigEntry GardMushrooms; + public static ConfigEntry GardSecondsPerSap; + public static ConfigEntry GardCapacity; + public static ConfigEntry ChestEyes; + + public static void Bind(ConfigFile config) + { + const string nexus = "Alfar - Nexus"; + NexusRadius = config.Bind(nexus, "Radius", 40f, new ConfigDescription("Metres around a Ljoskjarne where its drones work and its towers run.", new AcceptableValueRange(10f, 150f))); + NexusDensityKm2 = config.Bind(nexus, "Density Km2", 1.6f, new ConfigDescription("At most one Ljoskjarne per this many square kilometres.", new AcceptableValueRange(0.1f, 20f))); + NexusBronze = config.Bind(nexus, "Bronze Cost", 40, new ConfigDescription("Bronze to build a Ljoskjarne.", new AcceptableValueRange(0, 500))); + NexusStone = config.Bind(nexus, "Stone Cost", 30, new ConfigDescription("Stone to build a Ljoskjarne.", new AcceptableValueRange(0, 500))); + + const string drone = "Alfar - Drones"; + DroneBronze = config.Bind(drone, "Bronze Cost", 8, new ConfigDescription("Bronze for each Ljosvaettir.", new AcceptableValueRange(0, 200))); + DroneCap = config.Bind(drone, "Cap Per Nexus", 6, new ConfigDescription("Most drones one Ljoskjarne keeps.", new AcceptableValueRange(0, 50))); + DroneHealth = config.Bind(drone, "Health", 25f, new ConfigDescription("A drone's health and shield (a Deathsquito has 10).", new AcceptableValueRange(1f, 1000f))); + DroneZapDamage = config.Bind(drone, "Zap Damage", 1f, new ConfigDescription("Lightning damage of a drone's defensive zap.", new AcceptableValueRange(0f, 100f))); + DroneZapInterval = config.Bind(drone, "Zap Interval", 2f, new ConfigDescription("Seconds between a drone's zaps.", new AcceptableValueRange(0.2f, 30f))); + + MinerDeposits = config.Bind(drone, "Mining Targets", "MineRock_Copper,MineRock_Tin,MineRock_Iron,silvervein,rock3_silver,giant_brain", + new ConfigDescription("Comma separated parts of prefab names the mining drones dig (case does not matter). Soft tissue comes from giant_brain.")); + MinerDamage = config.Bind(drone, "Mining Damage", 40f, new ConfigDescription("Pickaxe damage each mining drone does per second to a deposit.", new AcceptableValueRange(1f, 1000f))); + + WildPickables = config.Bind(drone, "Wild Plants Harvested", "Pickable_Mushroom,Pickable_Dandelion,Pickable_Thistle,RaspberryBush,BlueberryBush,CloudberryBush", + new ConfigDescription("Comma separated parts of prefab names of WILD plants the drones pick without replanting (mushrooms, berry bushes, flowers). Trees are never touched. Cultivated crops are always replanted.")); + + const string construct = "Alfar - Constructs"; + NeistMetal = config.Bind(construct, "Neistvordr Bronze", 20, new ConfigDescription("Bronze for a Neistvordr.", new AcceptableValueRange(0, 500))); + NeistCrystal = config.Bind(construct, "Neistvordr Crystal", 3, new ConfigDescription("Crystals for a Neistvordr.", new AcceptableValueRange(0, 50))); + NeistEitr = config.Bind(construct, "Neistvordr Refined Eitr", 3, new ConfigDescription("Refined eitr for a Neistvordr.", new AcceptableValueRange(0, 50))); + NeistCap = config.Bind(construct, "Neistvordr Cap", 4, new ConfigDescription("Most Neistvordr one Ljoskjarne keeps.", new AcceptableValueRange(0, 50))); + + EldingMetal = config.Bind(construct, "Eldingvordr Iron", 20, new ConfigDescription("Iron for an Eldingvordr.", new AcceptableValueRange(0, 500))); + EldingCrystal = config.Bind(construct, "Eldingvordr Crystal", 5, new ConfigDescription("Crystals for an Eldingvordr.", new AcceptableValueRange(0, 50))); + EldingEitr = config.Bind(construct, "Eldingvordr Refined Eitr", 4, new ConfigDescription("Refined eitr for an Eldingvordr.", new AcceptableValueRange(0, 50))); + EldingCap = config.Bind(construct, "Eldingvordr Cap", 4, new ConfigDescription("Most Eldingvordr one Ljoskjarne keeps.", new AcceptableValueRange(0, 50))); + + SteinMetal = config.Bind(construct, "Steinvordr Black Metal", 20, new ConfigDescription("Black metal for a Steinvordr.", new AcceptableValueRange(0, 500))); + SteinCrystal = config.Bind(construct, "Steinvordr Crystal", 8, new ConfigDescription("Crystals for a Steinvordr.", new AcceptableValueRange(0, 50))); + SteinEitr = config.Bind(construct, "Steinvordr Refined Eitr", 6, new ConfigDescription("Refined eitr for a Steinvordr.", new AcceptableValueRange(0, 50))); + SteinCap = config.Bind(construct, "Steinvordr Cap", 1, new ConfigDescription("Most Steinvordr one Ljoskjarne keeps.", new AcceptableValueRange(0, 50))); + + ConstructLeash = config.Bind(construct, "Leash Range", 12f, new ConfigDescription("How far a construct wanders from its Ljoskjarne when not following.", new AcceptableValueRange(2f, 80f))); + ConstructAlertRange = config.Bind(construct, "Alert Range", 25f, new ConfigDescription("How far a construct notices and chases enemies.", new AcceptableValueRange(5f, 100f))); + WitherSeconds = config.Bind(construct, "Wither Seconds", 60f, new ConfigDescription("How long creatures last after their Ljoskjarne falls.", new AcceptableValueRange(0f, 600f))); + + SphereDamage = config.Bind(construct, "Sphere Damage", 80f, new ConfigDescription("Lightning damage of the Eldingvordr's sphere.", new AcceptableValueRange(1f, 1000f))); + SphereIntervalSeconds = config.Bind(construct, "Sphere Interval", 8f, new ConfigDescription("Seconds between the Eldingvordr's shots.", new AcceptableValueRange(0.5f, 60f))); + SphereRange = config.Bind(construct, "Sphere Range", 30f, new ConfigDescription("How far the Eldingvordr shoots.", new AcceptableValueRange(5f, 80f))); + + const string crystal = "Alfar - Crystals"; + UpgradeCrystals = config.Bind(crystal, "Upgrade Cost", 20, new ConfigDescription("Crystals the player must find for the Kristallvigsla.", new AcceptableValueRange(0, 200))); + CrystalCap = config.Bind(crystal, "Stored Cap", 20, new ConfigDescription("Most crystals the Ljoskjarne holds before it stops making them.", new AcceptableValueRange(1, 200))); + CrystalTimeFactor = config.Bind(crystal, "Time Factor", 2f, new ConfigDescription("A crystal takes this many times a vanilla beehive's time for one honey.", new AcceptableValueRange(0.1f, 20f))); + + const string tower = "Alfar - Towers"; + TowerBronze = config.Bind(tower, "Bronze Cost", 25, new ConfigDescription("Bronze for a Prismavard.", new AcceptableValueRange(0, 500))); + TowerCrystal = config.Bind(tower, "Crystal Cost", 2, new ConfigDescription("Crystals for a Prismavard.", new AcceptableValueRange(0, 50))); + TowerHealthFactor = config.Bind(tower, "Health Factor", 0.5f, new ConfigDescription("A Prismavard's health against the charred ballista's 400.", new AcceptableValueRange(0.05f, 3f))); + TowerDamage = config.Bind(tower, "Bolt Damage", 40f, new ConfigDescription("Lightning damage of a Prismavard's bolt.", new AcceptableValueRange(1f, 1000f))); + TowerScale = config.Bind(tower, "Scale", 0.6f, new ConfigDescription("Size of a Prismavard against the charred ballista.", new AcceptableValueRange(0.2f, 2f))); + + const string gard = "Alfar - Ljosgard"; + GardBronze = config.Bind(gard, "Bronze Cost", 40, new ConfigDescription("Bronze for a Ljosgard.", new AcceptableValueRange(0, 500))); + GardMushrooms = config.Bind(gard, "Mushrooms Cost", 10, new ConfigDescription("Jotun Puffs AND Magecap, this many of each, to build a Ljosgard.", new AcceptableValueRange(0, 100))); + GardSecondsPerSap = config.Bind(gard, "Seconds Per Sap", 600f, new ConfigDescription("Seconds to turn one Jotun Puffs and one Magecap into a Sap.", new AcceptableValueRange(10f, 7200f))); + GardCapacity = config.Bind(gard, "Sap Capacity", 10, new ConfigDescription("Sap the Ljosgard holds before it stops.", new AcceptableValueRange(1, 200))); + + ChestEyes = config.Bind(gard, "Chest Greydwarf Eyes", 3, new ConfigDescription("Greydwarf eyes in the price of the entry chest and the wood chest.", new AcceptableValueRange(0, 50))); + } + } +} diff --git a/JotunnModStub/Alfar/AlfarNexusStore.cs b/JotunnModStub/Alfar/AlfarNexusStore.cs new file mode 100644 index 0000000..4b17cc1 --- /dev/null +++ b/JotunnModStub/Alfar/AlfarNexusStore.cs @@ -0,0 +1,171 @@ +using System.Collections.Generic; +using HarmonyLib; +using TMPro; +using UnityEngine; +using UnityEngine.UI; + +namespace RacesOfValheim +{ + /// + /// The Ljoskjarne's window: the merchant's own store with a column of products in it - the drone, + /// the three constructs, the crystal upgrade, and the crystals to collect. + /// + /// It is the Trol war totem's window (TrolTotemStore) cloned for another trader, and for the same + /// reasons: same three patch points (Awake to build, FillList to repaint, Hide to clear), same trick + /// of instantiating StoreGui.m_listElement for the rows. The empty-catalogue guard that keeps vanilla + /// FillList from throwing is already on every trader with no wares (StoreGuiEmptyCatalogueGuardPatch), + /// so this one needs none of its own. + /// + /// What is different from the totem: a row's price is a number out of the pack and not coins, so the + /// short figure on the row is the metal or the crystals, and the tooltip carries the whole price. + /// + public static class AlfarNexusStore + { + private static RectTransform _list; + private static readonly List _rows = new List(); + + public static AlfarNexusBehaviour ActiveNexus(StoreGui gui) + { + Trader trader = FactionMerchantRuntime.GetActiveTrader(gui); + return trader != null ? trader.GetComponent() : null; + } + + // ─── build ─────────────────────────────────────────────────────────── + + public static void Create(StoreGui gui) + { + if (gui == null || gui.m_listRoot == null || _list != null) return; + + GameObject clone = Object.Instantiate(gui.m_listRoot.gameObject, gui.m_listRoot.parent); + clone.name = "AlfarProductList"; + _list = clone.GetComponent(); + _list.anchoredPosition = gui.m_listRoot.anchoredPosition; + + // The clone carries whatever rows the vanilla list held at Awake: it starts empty. + foreach (Transform child in _list) Object.Destroy(child.gameObject); + _list.gameObject.SetActive(false); + } + + public static void Clear() + { + foreach (GameObject row in _rows) if (row != null) Object.Destroy(row); + _rows.Clear(); + if (_list != null) _list.gameObject.SetActive(false); + } + + // ─── fill ──────────────────────────────────────────────────────────── + + public static void Refresh(StoreGui gui) + { + Clear(); + + AlfarNexusBehaviour nexus = ActiveNexus(gui); + if (nexus == null) return; // an ordinary merchant: not ours + + if (_list == null) + { + Jotunn.Logger.LogWarning("[Alfar] The Ljoskjarne's column was never built (did the patch on StoreGui.Awake fail?)."); + return; + } + + _list.gameObject.SetActive(true); + + int row = 0; + foreach (AlfarNexusBehaviour.Product product in nexus.OnOffer()) + { + BuildRow(gui, nexus, product, row++); + } + + float baseSize = Traverse.Create(gui).Field("m_itemlistBaseSize").GetValue(); + _list.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, Mathf.Max(baseSize, row * gui.m_itemSpacing)); + } + + private static string IconOf(AlfarNexusBehaviour.Product product) + { + switch (product) + { + case AlfarNexusBehaviour.Product.Drone: return "TrophyDeathsquito"; + case AlfarNexusBehaviour.Product.Neistvordr: return "TrophySurtling"; + case AlfarNexusBehaviour.Product.Eldingvordr: return "TrophyAbomination"; + case AlfarNexusBehaviour.Product.Steinvordr: return "TrophySGolem"; + default: return "Crystal"; + } + } + + private static void BuildRow(StoreGui gui, AlfarNexusBehaviour nexus, AlfarNexusBehaviour.Product product, int rowIndex) + { + GameObject element = Object.Instantiate(gui.m_listElement, _list); + element.SetActive(true); + + RectTransform rt = (RectTransform)element.transform; + float offset = (_list.rect.width - rt.rect.width) / 2f; + rt.anchoredPosition = new Vector2(offset, rowIndex * -gui.m_itemSpacing - offset); + + Sprite icon = Icon(IconOf(product)); + Image iconImage = element.transform.Find("icon").GetComponent(); + if (icon != null) iconImage.sprite = icon; + + string name = AlfarNexusBehaviour.ProductName(product); + element.transform.Find("name").GetComponent().text = Localization.instance.Localize(name); + + TMP_Text price = FindDescendant(element.transform, "price"); + if (price != null) price.text = AlfarNexusBehaviour.PriceShort(product); + + // The coin that sits beside the number on a vanilla row is the wrong picture here. + foreach (Image image in element.GetComponentsInChildren(true)) + { + if (image != null && image.gameObject.name.ToLowerInvariant().Contains("coin")) image.gameObject.SetActive(false); + } + + UITooltip tooltip = element.GetComponent(); + if (tooltip != null) tooltip.Set(Localization.instance.Localize(name), nexus.Terms(product), gui.m_tooltipAnchor, default(Vector2)); + + AlfarNexusBehaviour.Product chosen = product; + element.GetComponent