Compare commits

..

150 commits

Author SHA1 Message Date
b1f3a6d666 Merge remote-tracking branch 'origin/main' into localisation 2026-11-13 17:08:48 +01:00
2f8f399b43 docs: v1.6.11 changelog and version bump, debug key in its own config section; Dagaz credit 2026-11-13 17:08:33 +01:00
eb793cfb57 Merge branch 'debug-config-section' 2026-11-13 17:07:45 +01:00
0668d59a9b feat(debug): Debug config section; debug key rebindable and off by default; Log Form Hits moved from Fenrir; dead Skeleton F8 helpers removed
Requested by Dagaz.
2026-11-13 17:07:45 +01:00
555830351d Merge remote-tracking branch 'origin/main' into localisation 2026-11-11 18:43:56 +01:00
b431bb9d1f docs: v1.6.10 adds the Skrid roof fix; Joacwoo credit 2026-11-11 18:43:43 +01:00
a5d3b54dd6 Merge branch 'fix-alfar-blink-floor' 2026-11-11 18:43:42 +01:00
ffed6fd33e fix(alfar): Skrid lands on the floor under its end, never on a roof; cancelled in a dungeon with no floor 2026-11-11 18:43:42 +01:00
1954867385 Merge remote-tracking branch 'origin/main' into localisation 2026-11-11 15:57:25 +01:00
088d969323 docs: v1.6.10 changelog and version bump, Skadi drake forms hit the dummy, Ravager damage on Unarmed, Alfar hair flash 2026-11-11 15:57:02 +01:00
91f2a8bc0a Merge branch 'fix-alfar-hair-flicker' 2026-11-11 15:56:01 +01:00
0b90201368 Merge branch 'fix-form-attacks' 2026-11-11 15:56:01 +01:00
caaa233392 fix(forms): Skadi melee hits the training dummy on the clip's hit frame, Ravager attacks get Brute sounds and scale with Unarmed 2026-11-11 15:56:01 +01:00
842af2fd4f fix(alfar): hair and beard never attach, no flash on equipment change 2026-11-11 14:57:38 +01:00
b4a6432617 Merge remote-tracking branch 'origin/main' into localisation 2026-11-06 21:45:31 +01:00
2d865f5bb0 docs: v1.6.9 changelog and version bump, hitting your own faction, grudges in multiplayer, race attacks train their skills 2026-11-06 21:45:11 +01:00
6ddca72144 Merge branch 'fix-grudge-multiplayer' 2026-11-06 21:28:13 +01:00
7a618936f2 fix(factions): grudges survive an owner change and reach kin owned elsewhere
The grudge was a dictionary in the owner's memory: when another client
took over the creature mid-fight, its copy made peace on the next
UpdateTarget. Grudge spreads to kin also skipped kin owned by another
client. The grudge now lives on the creature's ZDO (attacker ZDOID and
an end time in network time), written only by the owner; kin owned
elsewhere get an RPC that their owner handles.
2026-11-06 21:28:13 +01:00
811e4cac34 Merge branch 'fix-aswid-puke-stomach' 2026-11-06 21:21:20 +01:00
cae18b440d Merge branch 'fix-faction-grudge' 2026-11-06 21:21:20 +01:00
c1c1c76360 fix(aswid): pukeberries empty the fourth stomach too
SE_Puke calls RemoveOneFood, which only picks from vanilla's three
slots, so the Aswid's fourth meal survived the berries. It now joins
the same random draw, the way the Trol's extra slots do.
2026-11-06 21:21:20 +01:00
4ee98d90cb fix(factions): the player can strike allied creatures again
Valheim 1.0's hit filters (Attack melee/area, Projectile OnHit/DoAOE/
IsValidTarget, Aoe.ShouldHit) skip a target when BaseAI.IsEnemy says
false and the attacker is a player without PvP. The truce said false
for every allied creature, so the blow passed through: no damage, no
grudge, nothing for kin to join. RaceGrudge.StrikeScope opens a scope
around those six methods in which both truce patches stand down for
the player's own hit; everything else keeps the truce.
2026-11-06 21:21:20 +01:00
fdc5d9fab7 Merge branch 'fix-form-skill-xp' 2026-11-06 21:21:11 +01:00
d9bca1934f fix(skills): hand-built attacks level the skill they scale with
Form attacks and powers called Damage directly, and vanilla only raises
a skill inside Attack and Projectile.OnHit, so the skill never moved.
FormMelee.RaiseSkill pays once per swing or tick that hit a creature.

- Fenrir forms' claws and bites: Unarmed; Cultist fire: Elemental Magic
- Skadi drake melee and Trenta stomp: Unarmed
- Aswid aura: Blood Magic, 0.1 per second like the Frost Aura
- Alfar Geisli and Ljosstorm: Elemental Magic; Sameining pulse 0.1/s
- Trenta Purple Rain scales with Blood Magic (two new bonus keys) and
  levels it once per cast that reaches someone besides the caster
2026-11-06 21:21:11 +01:00
b8ddcfd1d5 Merge remote-tracking branch 'origin/main' into localisation 2026-11-05 13:21:49 +01:00
eeebfd4d06 docs: v1.6.8 New-in block mentions the faction changes 2026-11-05 13:21:41 +01:00
064708d844 Merge branch 'feat-faction-group-grudge'
# Conflicts:
#	README.md
2026-11-05 13:05:45 +01:00
0008e0b34e Merge branch 'fix-faction-new-skeletons' 2026-11-05 13:05:34 +01:00
5530f7dc3d feat(factions): optional group grudge, kin within 20 m join the fight
Joacwoo's request. With "Grudge spreads to kin" on (off by default),
hitting a creature at peace with you gives the same grudge to every
creature of that faction within "Grudge spread radius" (20 m) and
alerts them, like vanilla's Dvergr with a human. Only creatures whose
AI runs on this machine are told, since that is where a grudge is
read.
2026-11-05 13:05:03 +01:00
bb1769b876 fix(factions): Valheim 1.0's regional skeletons join the swamp faction
Valheim 1.0 places Skeleton_Meadows, _Swamps, _Mountains and
_DeepNorth (and the _noarcher twins) instead of the plain Skeleton,
and none of them were in the faction lists, so they attacked the
races the old skeletons left alone. Added to the swamp faction set,
the Skeleton's own enemy check and the faction shop map, with
Skeleton_NoArcher in the shop map too. Reported by Joacwoo.
2026-11-05 12:59:57 +01:00
2b1064025a Merge remote-tracking branch 'origin/main' into localisation 2026-11-05 12:44:24 +01:00
ceb0d0e35a docs: v1.6.8 changelog and version bump, Skeleton Mortal Habits, bat combat lock and cheap Dvergar marble 2026-11-05 12:44:03 +01:00
446fcc7327 Merge branch 'feat-dvergar-cheap-pieces' 2026-11-05 12:42:22 +01:00
a538e3d5e4 Merge branch 'main' into feat-dvergar-cheap-pieces 2026-11-05 12:15:13 +01:00
19281e31ce Merge branch 'feat-skeleton-mortal-options' 2026-11-05 11:07:18 +01:00
2ac22d7d86 Merge branch 'feat-aswid-bat-combat-lock' 2026-11-05 11:07:17 +01:00
71721caa8d feat(aswid): bat form waits until 2.5 s after the last hit
An Aswid could take wing in the middle of a fight. Taking bat form is
now refused until Combat Lock seconds (default 2.5, 0 turns it off)
after the local player last lost health. Health is compared around
Character.ApplyDamage, so direct hits and fire, poison and bleeding
ticks all count, and a fully blocked or absorbed hit does not.
Turning back from bat form is never blocked.
2026-11-05 11:06:33 +01:00
9204dc96a2 feat(dvergar): build black marble and Yggdrasil pieces with stone and fine wood
Wargles' suggestion. A Dvergar pays 3 stone per black marble and 2 fine
wood per Yggdrasil wood on structural hammer pieces; stations,
furniture, containers and fires keep their cost. The swap is made on
the piece prefabs of the Dvergar's own client, so the menu, the known
piece check and the cost paid all follow it, and the pieces show once
stone or fine wood is known.

Vanilla refunds whatever m_resources says on the machine that destroys
a piece, so a cheap piece is tagged on its ZDO with the ratios paid,
and DropResources gets the matching cost on every client: a cheap wall
never refunds black marble, and a vanilla wall still does.

Swapped pieces carry the Dvergar race icon on their button in the 1.0
build menu (BuildUiPieceButton). The startup log lists every swapped
piece with its station and both costs.

Config: "Dvergar - Cheap Building" (Enabled, Stone per Black Marble,
Fine Wood per Yggdrasil Wood).
2026-11-05 10:34:04 +01:00
9ed606a9aa feat(skeleton): per-player options to eat real food and spend stamina
Two options in "Skeleton - Mortal Habits", both off and not synced by
the server, since each only gives up an advantage.

Eats Mortal Food: the Skeleton eats like the living. The max health
override and the fake foods step aside, so meals decide health and
stamina and the tier's health bonus, which stood in for food, no longer
applies. The food HUD shows again.

Feels Fatigue: the Skeleton spends stamina. Without eating, its max
stamina is base plus the stamina of the tier's stand-in meals, because
the fake foods sit at m_time 0 and give none.

The compendium builds its diet line from four new keys (English,
Italian, Russian) when either option is on.
2026-11-02 23:31:58 +01:00
4c7e0ec16d docs: the README changelog starts at v1.5.0, and packaging stops on a README Thunderstore would refuse 2026-11-02 17:47:38 +01:00
42c1e7ddd3 Merge remote-tracking branch 'origin/main' into localisation 2026-11-02 17:33:22 +01:00
aa252c86ca docs: v1.6.7 changelog and version bump, a job for every Skadi and Fenrir form 2026-11-02 17:32:06 +01:00
93d5b5424e Merge branch 'fenrir-form-roles' 2026-11-02 17:31:18 +01:00
94b66f29ee Merge branch 'skadi-form-flight' 2026-11-02 17:31:18 +01:00
ec3775a304 Merge branch 'fix-drone-kiln-alert' 2026-11-02 17:31:18 +01:00
af58fcec0d feat(fenrir): each form has a job once all three are unlocked
The Fenring and the Cultist ran at +100% while the Ulv, the form that
looks made for travel, ran at +50%. Now the Ulv is the travel form at
+100%, and the Fenring and the Cultist drop to +50%.

The Fenring holds the line: every hit on it lands 30% lighter. The
Cultist keeps its damage and pays for it: every hit lands 25% harder.
The scale sits in a new SE_FenrirFormBuff.OnDamaged, which runs on the
player's own machine before armor, so it covers hits from any client.

Speed and the damage factor are set on the live effect each time a form
is taken, so the Wolf and the Ulv can share SE_WolfForm with different
speeds, and a changed value applies without a relog. The speed keys
were renamed (Ulv Speed Bonus, Wolf Speed Bonus, Fenring And Cultist
Speed Bonus) so a saved .cfg cannot keep the old order. Suggested by
Lexsonn.
2026-11-02 16:23:35 +01:00
0f5b5e4868 feat(skadi): each dragon form flies and cools down on its own terms
The Drake and the Moder shared one set of flight numbers, so once the
Moder lost its time limit at the Queen the Drake had no reason left.
Now the Drake is the scout: quick to turn, fast, free to fly, but it
will not take off while encumbered. The Moder is the freighter: slow to
turn, 3 stamina a second to beat its wings, and it lifts a heavy pack at
25% extra cost.

"Skadi - Directed Flight" becomes "Skadi - Dragon Forms", with every
flight number per form plus the bat's Flight Stamina, While Encumbered,
Encumbered Extra Stamina Cost, Max Duration, Duration Per State and
Cooldown. Duration and cooldown default to -1, which keeps the
boss-tier table.

Each form also gets its own cooldown effect and icon, so a cooldown on
one form no longer blocks another. Suggested by Dissolution.
2026-11-02 15:58:17 +01:00
038d827991 fix: drones fly beside a station instead of into it
A flyer's goal is lifted to m_flyAltitudeMin over the ground under the
point, and under a charcoal kiln's origin that is inside the dome. The
drone never came within reach, timed out on the collect job and put the
kiln in the penalty box, so no wood was loaded for three minutes at a
time (snakey's second log: penalty True, 'Could not reach collect').

Station jobs now aim a metre past the station's colliders on the side
the drone comes from. Loading and the drop sweep still use the
station's own position.
2026-10-31 02:37:00 +01:00
85c7af6d05 fix: drones no longer freeze with a load after a slow trip or a fight
Plan() returned early for a delivery and kept the deadline of the job
before it, so a delivery that started late timed out on its first tick,
was planned again with the same stale deadline, and looped every frame.
snakey's log shows 10790 deposit_station timeouts in a row: the drone
hung by the kiln with the wood, and a fight mid-trip did the same.

Every job now gets a fresh clock. A station that is in the penalty box
is not asked again for a delivery; the Alfar drone takes the load back
to the chest it came from, so fuel stays in the Eldividarkista. The
Butler's servant had the same early return and gets the same fix.
2026-10-31 02:10:32 +01:00
9bd98c68c3 debug: F8 shows why a drone feeds a station or not, and what holds its fight
For the nearest worker drone F8 now lists the Eldividarkista and its
wood, every station in the radius (operable, free slots, takes wood,
penalty, claim, fuel, what a load would bring), and stations just past
the edge with the distance. Each drone also reports the 12 m enemy
sweep and how long the fight linger has left.
2026-10-31 01:58:40 +01:00
78d75a4a84 Merge remote-tracking branch 'origin/main' into localisation 2026-10-30 23:46:51 +01:00
b16d1775d8 docs: v1.6.6 changelog and version bump, Shrink Hammer and the Alfar base's new look 2026-10-30 23:43:56 +01:00
b25548280c Merge branch 'feat-trol-sounds' 2026-10-30 23:42:58 +01:00
106dc22bc1 Merge branch 'feat-scale-hammer'
# Conflicts:
#	JotunnModStub/Translations/English/messages.json
#	JotunnModStub/Translations/Italian/messages.json
#	JotunnModStub/Translations/Russian/messages.json
2026-10-30 23:42:58 +01:00
4cf95fa8c7 Merge branch 'feat-alfar-nexus' 2026-10-30 23:42:50 +01:00
56edb02eab Merge branch 'fix-grafvaettir-centre' 2026-10-30 23:42:49 +01:00
ec533fdbd9 fix: the Shrink Hammer's badge points in, at a small square
The resize badge's arrow ran from the small square to the big one and read as
growing. Four arrows closing in on a small square read as shrinking.
2026-10-30 23:41:57 +01:00
2125e71682 feat: a rare Trol surprise 2026-10-30 23:37:19 +01:00
0d1f655598 feat: Shrink Hammer, and Alt + scroll to size pieces with both hammers
A player asked to build below vanilla size for small details. The new
Shrink Hammer, craftable by any race, builds from 0.25 to 1; Trol's Hammer
keeps 1 to 3. With either hammer, Alt + scroll in build mode changes the
size in steps of 0.05, an Alt: Size row joins the build hints, and the size
floats over the ghost when it is not the default. With the repair tool, the
aimed piece shows the size it was built at. Both hammers get icons of their
own.
2026-10-30 22:49:27 +01:00
38bb8f1813 feat: the Ljoskjarne floats 0.8 m above the ground 2026-10-30 21:56:36 +01:00
036596b80d feat: the Ljoskjarne's faces become riveted steel panels
Each face is three brushed panels split by straight seams, framed by a
seam along the sloping edges and riveted along them. Straight lines and
streaks replace the grain that read as rock.
2026-10-30 20:10:31 +01:00
778451bed8 fix: the Ljoskjarne's seam is painted into a glow map, the plates look forged
The cyan bars stood on the faces and lost part of their length to the face
on one side of the world, lit or unlit. The seam is now a line in the faces'
own glow map, with a shallow channel in a new normal map. The plates take
grain and blotches from the black metal and iron beam textures, and shine
less.
2026-10-30 19:46:55 +01:00
06cc1d8c88 feat: the Ljoskjarne becomes a floating steel pyramid
A 2 m pyramid of dark steel, carved with Valheim's runes, hovers 0.5 m
above the ground, bobs and turns slowly. A cyan rib runs down each face;
it breathes and burns brighter while crystals wait. One still collider
keeps building, support and the E key as before. New hammer icon.
2026-10-30 18:48:32 +01:00
b661fa6516 feat: Alfar chests get bodies of their own
Players mistook a plain Wood chest for the Eldividarkista, so neither
Alfar chest looks like a buildable vanilla chest any more.

Eldividarkista: the Mistlands dvergr crate stretched to 1.6 x 0.8 m,
blackened iron with a bronze frame and an iron grate on the front. The
grate glows and throws sparks only while the chest holds wood the drones
may burn.

Inngangskista: the dvergr town loot chest, navy steel with silver trim. A
cyan line in the lid shines while it holds anything but the sigil.

Both have new hammer icons, and their hover names say their role (input,
fuel) in English, Italian and Russian. If a borrowed vanilla model is
missing, the chest falls back to the old tinted wood chest.

scripts/paint_*_chest.py repaint the textures and render previews and
icons offline with scripts/render_obj.py.
2026-10-30 18:20:13 +01:00
97e25dabe9 fix: Alfar drones go back to work after a fight, and say what they skip
A tamed MonsterAI never drops a target for distance, so an enemy that ran
off but stayed loaded kept the drone fighting forever. The drone now drops
a target past its leash and clears vanilla's target and alert when the
fight ends.

Drones now talk over their heads and in chat (40 m): an item in the
Inngangskista with nowhere to go, an item kept there for a station, and an
idle kiln whose wood is in a plain chest instead of the Eldividarkista.
Texts in English, Italian and Russian.

F8 lists each worker drone's state and why each entry-chest item stays or
moves.
2026-10-30 17:41:37 +01:00
46805836f3 Merge remote-tracking branch 'origin/main' into localisation 2026-10-29 21:10:19 +01:00
16cacde532 docs: v1.6.5 changelog, the Grafvaettir drones dig copper and tin 2026-10-29 21:09:46 +01:00
e87b85597d Merge branch 'fix-grafvaettir-centre': drones break copper and tin 2026-10-29 21:09:35 +01:00
b870dc65b0 fix: Grafvaettir drones break copper and tin
The F8 readout showed each hit entering Destructible.Damage with every gate open, this machine owning the deposit and ZRoutedRpc's id equal to the owner, and the RPC handler never running, with nothing in the log. When the drone's machine owns the deposit and the routed hit did not arrive, the drone now calls the deposit's own handler (Destructible.RPC_Damage, MineRock.RPC_Hit, MineRock5.RPC_Damage) directly: the same resistance, tier and break logic, without the routing. Why the local routing drops it is still open; a remote owner still gets the routed hit, untested.

A broken copper vein (rock4_copper_frac) never matched Mining Targets: MineRock5 renames its own object to "___MineRock5 m_meshFilter" in Awake. Deposit names now come from the ZDO's prefab. Drones also drop a target another drone just broke instead of striking a dead view.

F8 prints how far each drone's last hit got: Damage entered (and its gates), the RPC with health before and after, or the direct call.
2026-10-29 21:09:34 +01:00
dc24cbbacd docs: v1.6.5 changelog carries the Grafvaettir job and cooldown fixes 2026-10-29 20:37:44 +01:00
1420db796b chore: F8 shows what each Grafvaettir hit did on arrival
Patches on Destructible.RPC_Damage, MineRock.RPC_Hit and MineRock5.DamageArea record, for hits from a miner, the health before and after, the damage left after resistances, the pickaxe damage and the tool tier against the rock's minimum. 'sent, no RPC' means the hit never reached the deposit's owner.
2026-10-29 20:37:31 +01:00
9da27b64d3 Merge branch 'fix-grafvaettir-centre': F8 hit readout for the drones 2026-10-29 20:37:31 +01:00
a7cb4b45a7 Merge branch 'fix-grafvaettir-centre': Grafvaettir drones keep their job 2026-10-29 20:04:29 +01:00
ecf6e1bedb fix: Grafvaettir drones keep their job when their zone reloads
The F8 readout showed every miner with centre (0,0,0) and no target: Valheim destroys a creature when its zone unloads and builds a fresh one from the ZDO when it comes back, and the miner's centre, radius and lifetime were plain fields, so the rebuilt drone searched for ore around the world origin and stood still. They now live in the ZDO, the birth time in network time so a rebuilt drone does not get a fresh two minutes. A drone with no job in its ZDO digs around where it stands.

The throw on cooldown returned without a word, which looked like copper refusing the cast. It now says how many seconds are left (English, Italian, Russian).
2026-10-29 20:04:28 +01:00
2147c892b0 Merge remote-tracking branch 'origin/main' into localisation 2026-10-29 19:35:45 +01:00
172ed331e5 chore(release): v1.6.5 - Free Bat Flight and Fenrir senses
Version 1.6.5 in the manifests and PluginVersion. README: the New in v1.6.5 block and the changelog, Free Bat Flight in the Aswid section and progression, Hunter's Senses in the Fenrir section and progression, crediting MrBiffty, his friend and snakey.
2026-10-29 19:34:50 +01:00
0fe91dd52f Merge branch 'feat-free-bat-flight': Free Bat Flight as a choice 2026-10-29 19:34:07 +01:00
578ecbb591 Merge branch 'feat-fenrir-senses': Fenrir forms sense nearby creatures 2026-10-29 19:34:07 +01:00
00a30d9b34 Merge branch 'fix-grafvaettir-mining': Grafvaettir miners reach the deposit 2026-10-29 19:34:07 +01:00
7ec4a14ed4 fix: Free Flight texts name Left Ctrl, the key vanilla hard-wires for sinking 2026-10-29 19:33:38 +01:00
6f439f37c3 feat: Free Bat Flight, the old bat flight as a choice
The old bat flight is back as Free Flight: vanilla debug fly, up to 50 m/s, no stamina and no weight limit, Jump rises and Left Ctrl sinks. Each player picks it with Aswid - Bat Form / Free Bat Flight (local, never synced). The synced Bat Flight Rule (PlayerChoice, AlwaysStaminaFlight, AlwaysFreeFlight) lets the host or server decide for everyone. The mode is read when the form goes up, so a change counts from the next transform.

Debug fly makes vanilla treat the player as absent: no monster sees, hears or wakes for them, and hits are dropped. The six patches removed in v1.6.1 are back in AswidBatForm, for bats only and with no switch, so a free bat is fast but not invisible or immortal. Turning flight off now clears both flags, so death and reset end either flight. The compendium shows the Free Flight line when it is the active mode.

Asked for by MrBiffty, who builds tall with the bat.
2026-10-29 19:33:30 +01:00
fc5d6b8abc feat: Fenrir forms sense nearby creatures like the Aswid
Every Fenrir form (Wolf, Ulv, Fenring, Cultist) now lights each untamed creature within 100 m with the Aswid's green glow; the human does not. The glow moved out of AswidRace into a shared HunterSenses, which the Aswid now calls too, unchanged. New setting Fenrir - Superhuman Senses / Detection Radius; the light follows the Aswid's Marker Light settings. Compendium line in English, Italian and Russian.

Asked for by a friend of MrBiffty.
2026-10-29 19:33:21 +01:00
be8c7c59d3 fix: Grafvaettir miners fly low enough to strike deposits
Vanilla's flying MoveTo lifts the goal to m_flyAltitudeMin above whatever solid lies under it, the rock top included, so the miners hovered over a deposit just out of the 3.5 m reach and never struck. The Grafvaettir now flies 0.5-2 m up and strikes within 4 m.

Mining Targets is read again when the config line changes, so an edit in game counts without a restart. F8 also prints what the camera looks at (deposit kind, on the list or not) and each live miner's target, distance and strikes.
2026-10-29 19:33:08 +01:00
9117c0b251 Merge remote-tracking branch 'origin/main' into localisation 2026-10-29 16:22:58 +01:00
1c4d1c7b6a chore(release): v1.6.4 - staggering forms and Skeleton helmets
Version 1.6.4 in the manifests and PluginVersion. README: the New in
v1.6.4 block and the changelog, the Skeleton Show Helmet switch, Purple
Rain healing the caster and the Trenta's swim stamina, crediting lexsonn,
snakey and Jondar Korric.
2026-10-29 16:21:30 +01:00
a2737dc245 Merge branch 'fix-cultist-fire': Cultist fire from the hands, forms stagger 2026-10-29 15:46:33 +01:00
c5387421d4 fix: Cultist breath pose holds, roar loops, Cultist stands still
The creature's CharacterAnimEvent resets Animator.speed to 1 every physics step
outside a vanilla attack, so the speed-0 pin never held: the pose is now replayed
at the pin each frame. The flame ZSFX loops without its fade-out. While breathing
the player is held still through FenrirForms.LocalAttacking (no walking cast clip
exists); the howl waits for the breath to end.
2026-10-29 14:24:04 +01:00
a6df7a47f8 fix: Cultist breath holds the throw pose and keeps its flames
Pin at 1.3 s, the throw, instead of 2.6 s, where the vanilla Cultist has already
lowered its arms. fx_fenring_flames is a one-throw effect (2 s non-looping
emitters, 5 s TimedDestruction): loop the emitters and drop the timer so the
flames last the whole hold.
2026-10-29 14:14:24 +01:00
d142fad330 fix: Cultist fire from the hands, tied to its clip, facing the camera
The breath waits for the flame clip's Hit point (1.245 s), holds the casting pose
while the button is held and blends back to Movement on release, so a short click
no longer leaves the arms raised for the clip's 3.5 s. Eitr drains from the
flames on. Each fx_fenring_flames emitter follows its hand bone. While breathing,
Player.AlwaysRotateCamera answers true, so the body turns to the camera as when
blocking. Onlookers' copies follow the same clip.
2026-10-29 14:00:26 +01:00
beffd0bee6 fix: a stagger cancels the form's attack
A form swing waits for its clip's hit event and lands on a timeout if none comes,
so a stagger that cut the clip short still dealt the blow. Attacks are marked as
they start (TrySpendStamina, Ravager AttackRoutine) and their hits are dropped if
a stagger began since. No attack or Cultist breath starts while staggered.
2026-10-29 13:53:04 +01:00
dd92bdf345 fix: forms play their own stagger animation
The player's stagger trigger only reached the hidden human's Animator. FormStagger
fires the form's own vanilla stagger as it starts, for every form whose controller
has one (Trol True Form, the Fenrir forms, Ravager, Aswid bat), on every client.
2026-10-29 13:28:01 +01:00
a3d4f4ca02 Merge branch 'fix-grafvaettir-drone': drones mine and work instead of wandering 2026-10-29 13:23:43 +01:00
62ebc13116 Merge branch 'feat-form-attack-stamina': Form attacks cost stamina 2026-10-29 13:22:45 +01:00
162f71c39d Merge branch 'fix-cultist-attacks': Cultist claws on the hit events, flames from the jaw 2026-10-29 13:22:45 +01:00
788e226372 Merge branch 'fix-purple-rain-caster': Purple Rain heals the caster 2026-10-29 13:22:45 +01:00
84aba227eb Merge branch 'fix-trenta-swim-regen': Bonemass Trenta regains stamina while swimming 2026-10-29 13:22:45 +01:00
ed7483568c Merge branch 'fix-form-headlamp': Lights follow the form's head 2026-10-29 13:22:45 +01:00
3b194eaec9 Merge branch 'fix-trol-log-grab-gamepad': Trol Grab Log on the Use key 2026-10-29 13:22:44 +01:00
4cb9b7788d Merge branch 'fix-form-adrenaline': Form hits build adrenaline 2026-10-29 13:22:44 +01:00
7a43ced3fb Merge branch 'fix-muspell-weapon': Muspell blocks the hidden human's attack 2026-10-29 13:22:44 +01:00
3dae107b85 fix(fenrir): the Cultist's flames leave its mouth
The breath effect was placed 1.5 m above the player's feet and 1 m
ahead, chest height on a Cultist and the same whatever the form's size.

It now sits on the form's Jaw bone (fenring_cultist rig: Neck/Head/Jaw,
read from the game files), 0.3 m ahead, Head as the second choice and
the old fixed point if neither exists. A small follower places it every
LateUpdate, facing where the player faces, on the owner's copy and on
every onlooker's. The burn area is unchanged.
2026-10-29 02:30:05 +01:00
ac4ce4c636 feat(forms): Trol True Form and Fenrir form attacks cost stamina
Every form swing was free. FormMelee.TrySpendStamina charges a form
attack the way Attack.GetAttackStamina charges a weapon: equipment
modifier, status effects, up to a third off with the skill. Short of
stamina, the attack does not start and the bar flashes.

Trol True Form (Clubs skill), priced by the troll's damage, the slam
dearer for hitting all around: punch 10, side log swing 10, overhead
log 12, ground slam 18.

Fenrir forms (Unarmed), cheaper than weapons: Fenring 6/10/16, Wolf
4/6/10, Ulv 5/8/14, Cultist claw 6 and double claw 12. In exchange each
form hit gives 1.5x adrenaline (Fenrir - Form Buffs / Form Adrenaline
Multiplier), in Fenrir forms only.

Every cost is its own config entry beside the attack's damage.
2026-10-29 02:28:23 +01:00
ffb45d1c1c fix(fenrir): Cultist claws land on the clip's own hits
The single claw dealt its damage at a fixed 0.4 s, before the swing in
ClawAttackCultist (Hit event at 0.64 s of 1.33 s), and released the lock
at 0.5 s, so clicking again started a new claw mid-swing. The double
claw dealt one hit at 0.6 s although DoubleClawAttackCultist swipes
twice (Hit events at 0.64 s and 1.21 s).

BlockPlayerAttackTriggerPatch now counts the form's Hit events
(FenrirForms.AttackEvents) instead of only swallowing them. Both claws
wait for their events, with a timeout, and hold the lock until the clip
ends. Each double-claw swipe deals 60% of Double Claw Damage, 120% in
all for a slower swing that can be cut short.
2026-10-29 02:23:27 +01:00
87db3e03a6 fix(trenta): Purple Rain heals the Trenta who casts it
The heal skipped the caster, so a lone Trenta cast a heal that touched
no one. The caster now gets the same flat heal as its allies; the
compendium line and the config description say so.
2026-10-29 02:21:49 +01:00
fdc0fdcedc fix(trenta): stamina trickles back while a Bonemass Trenta swims
Vanilla Player.UpdateStats stops stamina regen while swimming off the
ground, and drowning starts at 0 stamina. The Bonemass unlock only
waived the stroke cost, so a Trenta who went into the water empty never
got a point back and drowned in water it swims for free.

A postfix on UpdateStats adds the regen vanilla held back, with the same
formula, times the new Trenta - Bonemass / Swim Stamina Regen (0.1, slow
on purpose). The compendium line says so in all three languages.
2026-10-29 02:21:24 +01:00
3c81b8f130 fix: Alfar drones and Sverm workers work instead of wandering
HandsToVanilla gave the tick to MonsterAI whenever BaseAI.FindClosestEnemy returned someone. Vanilla takes its first match at any distance and only checks maxDistance after that, so any wild creature in the loaded zones counted. The tamed MonsterAI then idled around and the work loop never ran. Check the distance ourselves.
2026-10-29 01:55:48 +01:00
504e6e83ed fix(forms): a worn headlamp follows the form's head
A form hides the human body and leaves it where it stood, and a Light is
not a renderer, so the Dvergr circlet's lamp (or a torch in hand) kept
shining from the hidden human's head: at a person's height inside the
troll, from the Muspell's feet.

While the body is hidden, every Light under it is put just ahead of the
form's head bone. A form without a bone called head gets the top front
of its own model, and with no form model at all the light sits
centre-forward at head height. The lights go back once the body shows.
Runs for every player, so onlookers see the lamp in the right place too.
2026-10-29 01:54:50 +01:00
4862f47e73 fix(trol): Grab Log works on the game's Use button, gamepad included
A log carries only vanilla's HoverText, which is not an Interactable, so
the game's Use on a log did nothing. Grab Log was read off the keyboard
alone (and the radial menu), and a gamepad had no button for it.

A prefix on Player.Interact grabs the log for a True Form Trol at tier
7+, the way the Aswid's Dominate rides the same button. The Grab Log key
still works on top of it, with a short debounce so the two readers of an
E press grab once. The hover prompt now shows the Use key, which resolves
to the pad's own button.
2026-10-29 01:53:32 +01:00
b7b9cbcbd5 fix(forms): Trol, Skadi, Sverm and Muspell form hits build adrenaline
The same bug the Fenrir forms had until d8dcecb. Vanilla grants a hit's
adrenaline inside Attack; these forms skip Attack and call Damage
directly, so only the stagger bonus in Character.Damage ever reached the
player.

FormMelee.GrantAdrenaline now runs after each hit of the True Form
troll's punch and log swings, the drake's maul, the Ravager's swings and
the Muspell's stomp. The troll's ground slam hits through an Aoe, which
never touches Attack either: the slam marks its Aoe, and a postfix on
Aoe.OnHit grants the adrenaline for each creature it lands on.

Projectiles (Throw Rock, the Muspell spike, drake breath) were never
affected: Projectile grants its own adrenaline on a hit.
2026-10-29 01:52:10 +01:00
99ec4134be fix(trenta): the Muspell no longer swings the weapon in hand
The Muspell was the one form without the attack blocks every other form
has. Each stomp and spike also started the hidden human's attack, and the
Elder clone's CharacterAnimEvent fired a held bow or crossbow through
OnAttackTrigger, several shots a swing.

StartAttack, PlayerAttackInput and OnAttackTrigger are shut while the
Muspell is up, and the guard is cleared after SetControls, since the
spike sits on Right Mouse, which is also Block.
2026-10-29 01:50:33 +01:00
bba81cbbf0 fix: Grafvaettir drones mine copper, scrap and tin
The default Mining Targets list named MineRock_Copper, but Black Forest copper is rock4_copper, so drones thrown at copper found no target and hovered where they spawned. Add rock4_copper and mudpile, and move configs still on the old default.

Drones now measure and aim at the nearest live hit area instead of the deposit root, which sits inside big rocks. Hits carry the drone as attacker: vanilla MineRock reads the attacker's ZDOID without a null check and threw on every tin hit.
2026-10-29 01:26:46 +01:00
373b0069dd Merge branch 'skeleton-show-helmet': Skeletons can show their helmet 2026-10-29 01:23:53 +01:00
e972ca5ea4 feat: Skeletons can show their helmet
New "Show Helmet" option under Skeleton - Visuals, off by default. The owner's
choice is written to the ZDO, so other players see the helmet the way its owner
picked.

On a skull the helmet moves up and back and grows to fit, since the skull is
bigger than the viking head the helmet hangs for. Hoods and the other skinned
helmets can't be moved by their transform: their Head bone is swapped for a
fitted child bone, so the head part follows the skull and the shoulder parts
stay put. A viking body gets the vanilla placement and bones back.
2026-10-29 01:08:07 +01:00
356e0f44d8 Merge remote-tracking branch 'origin/main' into localisation 2026-10-28 13:57:19 +01:00
1aa55984d6 chore(release): v1.6.3 - Trol guard and dressed stations
Version 1.6.3 in the manifests and PluginVersion. README: the New in
v1.6.3 block and the changelog, the True Form controls, the Bone Servant
tables' and the Race Menu Ward's new looks, crediting lexsonn and
sistermilker.
2026-10-28 13:55:36 +01:00
38160d1fa1 Merge branch 'kitbash-race-stations': new looks for the Race Menu Ward, Contract Bank and Bone Servant tables 2026-10-28 13:53:45 +01:00
2e40d45f04 Merge branch 'trol-true-form-block': Trol True Form blocks and rolls 2026-10-28 13:53:44 +01:00
3cc1bee2c0 feat: Trol True Form can block and roll
Right click blocks in True Form with a raised-arms guard, rooted in place.
Block + jump rolls at half distance with the troll's jump animation at
double speed. The slam moves to middle click (secondary attack on a pad).
trolpose is a debug command for trying guard and roll states live.
2026-10-28 13:53:35 +01:00
35476eb8ef feat: chainmail over the map on the Smith's Table
The smith goes back to the cartography table, like the cook. Its map is
painted over with 4-in-1 mail by scripts/paint_smith_mail.py at 512 px:
colour, rusted worn colour, a normal map from the rings' height and a
metallic map so they shine. Both tables now share one Dress/LayCover path.
2026-10-28 13:47:49 +01:00
069e098cf0 feat: red and white tablecloth on the Cook's Table
The cook goes back to the cartography table with its map painted over
offline (scripts/paint_cook_cloth.py from textures pulled by
scripts/extract_carto.py). The three PNGs are embedded in the DLL and
swapped onto copied materials by PieceLook.Retexture. The smith stays on
the black marble table.
2026-10-28 13:38:28 +01:00
b3edb2aed1 feat: marble Bone Servant tables, bigger centred props, fix table hover name
The Smith's and Cook's Tables clone the black marble table: the
cartography table's map is baked into its texture. Anvil or meal and a
skull sit near the centre at the table's measured height. The bank loses
its lantern and its tankard grows. The servant table hover localizes its
title, which showed as a raw token once a servant stood there.
2026-10-28 13:22:56 +01:00
f3d3c0ebb5 feat: new looks for the Race Menu Ward, Contract Bank and Bone Servant tables
Recolour and kitbash from vanilla parts, no new assets. PieceLook copies
materials before tinting so vanilla pieces keep their colours. ModelBorrow
gains activeOnly, which drops hidden snow, fire and broken meshes before
a borrowed piece is measured.
2026-10-28 12:40:33 +01:00
4fe7a9787d Merge remote-tracking branch 'origin/main' into localisation 2026-10-27 19:36:18 +01:00
cb29f54a28 chore(release): v1.6.2 - race eyes and controller fixes
Version 1.6.2 in the manifests and PluginVersion. README: the New in
v1.6.2 block and the changelog, crediting lexsonn's reports; the Aswid
eyes, Alfar levitation and Geisli lines follow the changes.
2026-10-27 19:36:02 +01:00
4cf9f6bee0 Merge branch 'fix-draugh-bear-alfar-gamepad': Draugh meats, Alfar levitation and Geisli on gamepad, rebindable flight keys 2026-10-27 19:35:25 +01:00
db9aac2bf6 fix: Draugh Ashlands meats, rebindable flight keys, Geisli on gamepad
Draugh: add AsksvinMeat and BoneMawSerpentMeat to the shared raw-to-cooked
table; the Aswid blood refinery no longer adds them on its own copy.

DirectedFlight (drake, bat): read ZInput Forward/Backward/Run instead of
raw W, S and Shift, so keys rebound in the settings work.

Geisli: the pad has no free button in vanilla's Classic layout, so the
beam is held on the pad's secondary attack, bare-handed or in the
Archon form, as Skadi's Cold Spell does. The unarmed kick is swallowed
while it fires. RaceInput.EmptyHanded is shared with Skadi. Compendium
text mentions the pad in English, Italian and Russian.
2026-10-27 19:33:17 +01:00
b9ec452e72 fix: Draugh eats Bjorn and Volture meat, Alfar levitation on gamepad
Draugh: add BjornMeat -> CookedBjornMeat to the raw-to-cooked table and
correct VoltureMeat's cooked name (RoastedVoltureMeat does not exist,
CookedVoltureMeat does), so neither raw meat got an EdibleUncooked_ item.
Names checked against the SoftRef manifests.

Alfar: ZInput "Jump" is the keyboard binding only. Read "JoyJump" and
"JoyCrouch" too, as PlayerController does, for levitation and the
Archon's climb and descent.

Reported by lexsonn.
2026-10-27 19:25:03 +01:00
45248acd74 Merge branch 'fix-race-eyes': race eyes on female faces, smaller Dvergar/Aswid eyes, grey Alfar eyes 2026-10-27 17:48:24 +01:00
76085f14b0 Merge remote-tracking branch 'origin/main' into localisation 2026-10-26 16:09:04 +01:00
68b87d181a Merge remote-tracking branch 'origin/main' into localisation 2026-10-25 18:25:22 +01:00
4fcfe6fd7c Merge remote-tracking branch 'origin/main' into localisation 2026-10-25 17:58:37 +01:00
d689834070 Merge remote-tracking branch 'origin/main' into localisation 2026-10-24 18:28:28 +02:00
fe8b3ea270 Merge remote-tracking branch 'origin/main' into localisation 2026-10-23 22:27:37 +02:00
cacc8ead4a Merge branch 'main' into localisation 2026-10-23 19:07:23 +02:00
99f409c8be Merge remote-tracking branch 'origin/main' into localisation 2026-10-19 14:30:42 +02:00
b3bdb0f75a Merge remote-tracking branch 'origin/main' into localisation 2026-10-19 14:26:56 +02:00
92c80e3b87 Merge branch 'main' into localisation 2026-10-18 00:19:25 +02:00
589127b7df Merge branch 'main' into localisation 2026-10-17 20:30:37 +02:00
174e615ed9 Merge branch 'main' into localisation 2026-10-17 20:28:54 +02:00
20e08432b8 Merge branch 'main' into localisation 2026-10-17 19:39:13 +02:00
a28fb19845 Merge branch 'main' into localisation 2026-10-17 19:33:39 +02:00
d28f9e353a Merge branch 'main' into localisation 2026-10-17 19:07:01 +02:00
d120ec8dc2 Merge branch 'main' into localisation 2026-10-17 17:15:54 +02:00
a2a4bcf451 Merge branch 'main' into localisation 2026-10-17 16:24:09 +02:00
b6e085e378 Merge branch 'main' into localisation 2026-10-17 16:22:29 +02:00
268ed47589 Merge branch 'main' into localisation 2026-10-17 15:59:09 +02:00
03cca64a48 Merge branch 'main' into localisation 2026-10-17 15:51:54 +02:00
e38df0b7e0 Merge branch 'main' into localisation 2026-10-17 15:32:06 +02:00
bf63b790f1 Merge branch 'main' into localisation 2026-10-14 16:41:52 +02:00
358b537cef Merge branch 'main' into localisation 2026-10-08 18:22:13 +02:00
128 changed files with 6387 additions and 673 deletions

View file

@ -119,7 +119,10 @@ namespace RacesOfValheim
if (Time.time >= nextPulse) if (Time.time >= nextPulse)
{ {
nextPulse = Time.time + AlfarPowerConfig.ArchonPulseInterval.Value; nextPulse = Time.time + AlfarPowerConfig.ArchonPulseInterval.Value;
AlfarPowers.Pulse(player, AlfarPowerConfig.ArchonPulseRadius.Value, AlfarPowerConfig.ArchonPulseDamage.Value); // The pulse fires on its own while the form lasts, so it earns what an aura does:
// a tenth of a hit per second, once per pulse that struck something.
if (AlfarPowers.Pulse(player, AlfarPowerConfig.ArchonPulseRadius.Value, AlfarPowerConfig.ArchonPulseDamage.Value))
FormMelee.RaiseSkill(Skills.SkillType.ElementalMagic, 0.1f * AlfarPowerConfig.ArchonPulseInterval.Value);
} }
} }

View file

@ -0,0 +1,79 @@
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// The light on the two Alfar chests, which says whether the drones have work there: the fire
/// chest's grate burns while it holds wood they may burn, the entry chest's inlay shines while it
/// holds anything but the sigil. Every client asks its own copy of the inventory, which Container
/// keeps in step with the ZDO, so nothing travels over the network for it.
/// </summary>
public class AlfarChestGlow : MonoBehaviour
{
public Renderer[] Glows;
public ParticleSystem Embers;
public Color GlowColor;
public bool WoodOnly;
private Container m_container;
private Material m_lit;
private Material m_cold;
private bool? m_shown;
private float m_nextCheck;
private void Awake()
{
m_container = GetComponent<Container>();
if (Glows == null || Glows.Length == 0 || Glows[0] == null) return;
m_cold = Glows[0].sharedMaterial;
m_lit = new Material(m_cold) { name = m_cold.name + "_lit" };
m_lit.color = Color.black;
m_lit.EnableKeyword("_EMISSION");
m_lit.SetColor("_EmissionColor", GlowColor);
}
private void Update()
{
if (Time.time < m_nextCheck) return;
m_nextCheck = Time.time + 1f;
bool lit = HasWork();
if (m_shown == lit) return;
m_shown = lit;
if (m_lit != null)
{
foreach (Renderer glow in Glows)
{
if (glow != null) glow.sharedMaterial = lit ? m_lit : m_cold;
}
}
if (Embers != null)
{
if (lit) Embers.Play(true);
else Embers.Stop(true, ParticleSystemStopBehavior.StopEmitting);
}
}
private bool HasWork()
{
Inventory inventory = m_container != null ? m_container.GetInventory() : null;
if (inventory == null) return false;
foreach (ItemDrop.ItemData item in inventory.GetAllItems())
{
if (item == null || item.m_dropPrefab == null) continue;
string name = item.m_dropPrefab.name;
if (WoodOnly ? AlfarDroneAI.IsWood(name) : name != AlfarSigil.PrefabName) return true;
}
return false;
}
private void OnDestroy()
{
if (m_lit != null) Destroy(m_lit);
}
}
}

View file

@ -61,12 +61,15 @@ namespace RacesOfValheim
public static void Register() public static void Register()
{ {
RegisterOne(EntryName, "$rov_piece_alfar_inngangskista_name", "$rov_piece_alfar_inngangskista_desc", RegisterOne(EntryName, "$rov_piece_alfar_inngangskista_name", "$rov_piece_alfar_inngangskista_desc",
new Color(0.62f, 0.80f, 1f, 1f)); "$rov_hover_alfar_inngangskista", new Color(0.62f, 0.80f, 1f, 1f),
AlfarInputChest.Build, "AlfarInputChest_icon.png");
RegisterOne(WoodName, "$rov_piece_alfar_eldividarkista_name", "$rov_piece_alfar_eldividarkista_desc", RegisterOne(WoodName, "$rov_piece_alfar_eldividarkista_name", "$rov_piece_alfar_eldividarkista_desc",
new Color(0.85f, 0.62f, 0.36f, 1f)); "$rov_hover_alfar_eldividarkista", new Color(0.85f, 0.62f, 0.36f, 1f),
AlfarFireChest.Build, "AlfarFireChest_icon.png");
} }
private static void RegisterOne(string pieceName, string display, string description, Color tint) private static void RegisterOne(string pieceName, string display, string description, string hoverName, Color tint,
System.Func<GameObject, bool> build, string iconResource)
{ {
GameObject source = PrefabManager.Cache.GetPrefab<GameObject>("piece_chest_wood"); GameObject source = PrefabManager.Cache.GetPrefab<GameObject>("piece_chest_wood");
if (source == null) if (source == null)
@ -91,15 +94,19 @@ namespace RacesOfValheim
} }
requirements.Add(new RequirementConfig("GreydwarfEye", AlfarNexusConfig.ChestEyes.Value, 0, true)); requirements.Add(new RequirementConfig("GreydwarfEye", AlfarNexusConfig.ChestEyes.Value, 0, true));
// The hover and the chest window say what the chest is for, not only its name.
Container container = prefab.GetComponent<Container>(); Container container = prefab.GetComponent<Container>();
if (container != null) container.m_name = display; if (container != null) container.m_name = hoverName;
Piece piece = prefab.GetComponent<Piece>(); Piece piece = prefab.GetComponent<Piece>();
if (piece == null) { Jotunn.Logger.LogWarning("[Alfar] The chest has no Piece: " + pieceName); return; } if (piece == null) { Jotunn.Logger.LogWarning("[Alfar] The chest has no Piece: " + pieceName); return; }
piece.m_name = display; piece.m_name = display;
piece.m_description = description; piece.m_description = description;
AlfarConstructs.Tint(prefab, tint); // Each chest has a body of its own; the tint stays as the fallback if it cannot be built.
Sprite icon = piece.m_icon;
if (!build(prefab)) AlfarConstructs.Tint(prefab, tint);
else icon = IconFrom(iconResource) ?? icon;
PieceManager.Instance.AddPiece(new CustomPiece(prefab, fixReference: false, new PieceConfig PieceManager.Instance.AddPiece(new CustomPiece(prefab, fixReference: false, new PieceConfig
{ {
@ -107,7 +114,7 @@ namespace RacesOfValheim
Description = description, Description = description,
PieceTable = PieceTables.Hammer, PieceTable = PieceTables.Hammer,
Category = PieceCategories.Crafting, Category = PieceCategories.Crafting,
Icon = piece.m_icon, Icon = icon,
Requirements = requirements.ToArray(), Requirements = requirements.ToArray(),
})); }));
@ -130,5 +137,12 @@ namespace RacesOfValheim
AlfarPieces.Extra.Add(pieceName); AlfarPieces.Extra.Add(pieceName);
} }
internal static Sprite IconFrom(string resource)
{
Texture2D texture = PieceLook.LoadTexture(resource);
if (texture == null) return null;
return Sprite.Create(texture, new Rect(0f, 0f, texture.width, texture.height), new Vector2(0.5f, 0.5f));
}
} }
} }

View file

@ -58,6 +58,13 @@ namespace RacesOfValheim
public const string KeyStatus = "RoV_alfarStatus"; public const string KeyStatus = "RoV_alfarStatus";
public const string KeyDest = "RoV_alfarDest"; public const string KeyDest = "RoV_alfarDest";
// What the drone last said: a counter every client watches, the text key and the item.
// Each client builds the line in its own language, so only the token travels.
public const string KeySaySeq = "RoV_alfarSaySeq";
public const string KeySayKey = "RoV_alfarSayKey";
public const string KeySayItem = "RoV_alfarSayItem";
public const string KeySayStation = "RoV_alfarSayStation";
/// <summary>Every drone alive in the loaded zones: the repairs look at each other through it.</summary> /// <summary>Every drone alive in the loaded zones: the repairs look at each other through it.</summary>
public static readonly List<AlfarDroneAI> All = new List<AlfarDroneAI>(); public static readonly List<AlfarDroneAI> All = new List<AlfarDroneAI>();
@ -141,6 +148,7 @@ namespace RacesOfValheim
private float m_nextFightScan; private float m_nextFightScan;
private float m_fightUntil; private float m_fightUntil;
private bool m_fighting;
private ZNetView m_nview; private ZNetView m_nview;
private Character m_character; private Character m_character;
@ -168,6 +176,11 @@ namespace RacesOfValheim
private ZDOID m_sortDest; private ZDOID m_sortDest;
private float m_scannedAt = -99f; private float m_scannedAt = -99f;
// Speech: the last line this client showed, and when to look for a new one.
private int m_heardSeq;
private float m_nextListen;
private float m_nextKilnCheck;
private Job m_job; private Job m_job;
private float m_nextPlan; private float m_nextPlan;
private float m_jobDeadline; private float m_jobDeadline;
@ -200,6 +213,16 @@ namespace RacesOfValheim
All.Add(this); All.Add(this);
ReadPayload(); ReadPayload();
// A line said before this object loaded is old news: do not replay it on a zone reload.
if (m_nview != null && m_nview.IsValid()) m_heardSeq = m_nview.GetZDO().GetInt(KeySaySeq, 0);
}
private void Update()
{
if (Time.time < m_nextListen) return;
m_nextListen = Time.time + 0.5f;
Listen();
} }
private void OnDestroy() private void OnDestroy()
@ -293,7 +316,17 @@ namespace RacesOfValheim
if (!m_fightsBack || m_ai == null || m_character == null || m_character.IsDead()) return false; 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; if (m_nview == null || !m_nview.IsValid() || !m_nview.IsOwner()) return false;
// A tamed MonsterAI with no patrol point and no follow target never drops its target for
// distance (UpdateTarget, IL): only after 30 s unsensed or 60 s without a swing. The drone
// hears far, so an enemy that ran off kept "being sensed" and held the tick for vanilla.
// Past the leash it is no longer this drone's fight.
Character target = m_ai.GetTargetCreature(); Character target = m_ai.GetTargetCreature();
if (target != null && !target.IsDead() && !InFightReach(target))
{
m_ai.MakeTame();
target = null;
}
if (target != null && !target.IsDead()) if (target != null && !target.IsDead())
{ {
m_fightUntil = Time.time + FightLinger; m_fightUntil = Time.time + FightLinger;
@ -301,20 +334,43 @@ namespace RacesOfValheim
else if (Time.time >= m_nextFightScan) else if (Time.time >= m_nextFightScan)
{ {
m_nextFightScan = Time.time + FightScanInterval; m_nextFightScan = Time.time + FightScanInterval;
if (BaseAI.FindClosestEnemy(m_character, transform.position, FightRange) != null) // FindClosestEnemy takes its first match at ANY distance (it only compares against
// maxDistance once it holds one), so with a deer anywhere in the loaded zones it never
// returned null and vanilla kept the tick: the drone idled about instead of working.
Character enemy = BaseAI.FindClosestEnemy(m_character, transform.position, FightRange);
if (enemy != null && Vector3.Distance(enemy.transform.position, transform.position) <= FightRange)
{ {
m_fightUntil = Time.time + FightLinger; m_fightUntil = Time.time + FightLinger;
} }
} }
if (Time.time >= m_fightUntil) return false; if (Time.time >= m_fightUntil)
{
// The fight is over: clear what vanilla still holds (target, alert), or the next
// GetTargetCreature hands the tick straight back to it. MakeTame is the public door
// that nulls both targets and the alert in one call; the drone is tamed already.
if (m_fighting) { m_fighting = false; m_ai.MakeTame(); }
return false;
}
m_fighting = true;
m_job = null; m_job = null;
m_nextPlan = 0f; // the fight moved it; plan afresh the moment it hands back m_nextPlan = 0f; // the fight moved it; plan afresh the moment it hands back
SetStatus("Fighting."); SetStatus("Fighting.");
return true; return true;
} }
/// <summary>Close to the drone, and not past the edge of the base it works.</summary>
private bool InFightReach(Character enemy)
{
Vector3 at = enemy.transform.position;
if (Vector3.Distance(at, transform.position) > FightRange * 2f) return false;
Vector3? anchor = Anchor;
float leash = AlfarNexusConfig.NexusRadius.Value + m_radiusBonus + FightRange;
return anchor == null || Vector3.Distance(at, anchor.Value) <= leash;
}
// ================================================================ the tick // ================================================================ the tick
/// <summary>Everything. Returns what MonsterAI.UpdateAI would have returned.</summary> /// <summary>Everything. Returns what MonsterAI.UpdateAI would have returned.</summary>
@ -389,17 +445,34 @@ namespace RacesOfValheim
Scan(anchor.Value); Scan(anchor.Value);
ExpirePenalties(); ExpirePenalties();
CheckIdleKiln();
// A harvest is in progress: wait for the drops to land, then gather them and replant. // A harvest is in progress: wait for the drops to land, then gather them and replant.
Job job;
if (m_farmSpot != null) if (m_farmSpot != null)
{ {
m_job = Time.time < m_farmReadyAt job = Time.time < m_farmReadyAt
? new Job { Kind = "wait", Point = transform.position, Label = "Waiting" } ? new Job { Kind = "wait", Point = transform.position, Label = "Waiting" }
: new Job { Kind = "farm_finish", Point = m_farmSpot.Value, Label = "Gathering" }; : new Job { Kind = "farm_finish", Point = m_farmSpot.Value, Label = "Gathering" };
return; }
// A delivery is a job like any other and gets its own clock. It used to return early here
// and inherit the load's deadline: a slow trip, or a fight on the way, left it already late,
// so it timed out on the first tick, was planned again, timed out again, every frame - the
// drone froze with wood in hand next to the kiln (10790 timeouts in one player's log).
else if (m_payload.Count > 0) job = PlanDelivery(anchor.Value);
else job = PlanWork(anchor.Value);
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;
} }
if (m_payload.Count > 0) { m_job = PlanDelivery(anchor.Value); return; } private Job PlanWork(Vector3 anchor)
{
// The forge has no clock: a smelter holds its ore indefinitely and puts its own output on // 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 // the floor, so PlanRescue would ask a question whose answer is always no. The smith is a
@ -415,15 +488,7 @@ namespace RacesOfValheim
// base: repairs, the fields, and last the tidying of the entry chest. // base: repairs, the fields, and last the tidying of the entry chest.
Job job = PlanRescue(); Job job = PlanRescue();
job = job ?? PlanCollect() ?? PlanFuel() ?? PlanLoad(); job = job ?? PlanCollect() ?? PlanFuel() ?? PlanLoad();
job = job ?? PlanRepair(anchor.Value) ?? PlanFarm(anchor.Value) ?? PlanSort(); return job ?? PlanRepair(anchor) ?? PlanFarm(anchor) ?? 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;
} }
/// <summary> /// <summary>
@ -552,7 +617,7 @@ namespace RacesOfValheim
Kind = "collect", Kind = "collect",
Target = best.Id, Target = best.Id,
Claim = best.Id, Claim = best.Id,
Point = best.Position, Point = ApproachPoint(best),
Hurry = true, Hurry = true,
Label = "Saving the food", Label = "Saving the food",
}; };
@ -583,7 +648,7 @@ namespace RacesOfValheim
Kind = "collect", Kind = "collect",
Target = best.Id, Target = best.Id,
Claim = best.Id, Claim = best.Id,
Point = best.Position, Point = ApproachPoint(best),
Label = "Collecting", Label = "Collecting",
}; };
} }
@ -713,20 +778,37 @@ namespace RacesOfValheim
// coal, so gating the delivery on free slots sent the servant back to the chest with // 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, // 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. // forever. AcceptsAnything already asks the right question of both doors.
// A station it could not reach is in the penalty box: asking it again straight away
// is the same failed trip.
bool unreachable = IsPenalised(target);
ButlerStation station = StationById(target); ButlerStation station = StationById(target);
if (station != null && station.Alive && station.Operable && AcceptsAnything(station)) if (station != null && station.Alive && station.Operable && AcceptsAnything(station) && !unreachable)
{ {
return new Job return new Job
{ {
Kind = "deposit_station", Kind = "deposit_station",
Target = target, Target = target,
Point = station.Position, Point = ApproachPoint(station),
Label = "Loading " + Describe(), Label = "Loading " + Describe(),
}; };
} }
// The station is gone, full or cold. The goods are ours to put back, not to hold. // The station is gone, full or cold. The goods are ours to put back, not to hold.
m_nview.GetZDO().Set(KeyTarget, ZDOID.None); m_nview.GetZDO().Set(KeyTarget, ZDOID.None);
// Out of reach, the load goes back where it came from: the Eldividarkista's wood stays
// fuel instead of landing in the entry chest and being sorted away into storage.
Container source = unreachable ? ContainerById(m_nview.GetZDO().GetZDOID(KeySource)) : null;
if (source != null && !IsMarkedOff(source) && !IsPenalised(ZdoOf(source)) && HasRoomFor(source))
{
return new Job
{
Kind = "deposit",
Target = ZdoOf(source),
Point = source.transform.position,
Label = "Storing " + Describe(),
};
}
} }
Container chest = ChestForProduct(); Container chest = ChestForProduct();
@ -759,7 +841,7 @@ namespace RacesOfValheim
{ {
Kind = "deposit_station", Kind = "deposit_station",
Target = consumer.Id, Target = consumer.Id,
Point = consumer.Position, Point = ApproachPoint(consumer),
Label = "Loading " + Describe(), Label = "Loading " + Describe(),
}; };
} }
@ -1418,16 +1500,25 @@ namespace RacesOfValheim
if (inventory == null) return null; if (inventory == null) return null;
string sigil = AlfarSigil.PrefabName; string sigil = AlfarSigil.PrefabName;
bool spoke = false;
foreach (ItemDrop.ItemData item in inventory.GetAllItems()) foreach (ItemDrop.ItemData item in inventory.GetAllItems())
{ {
if (item == null || item.m_dropPrefab == null) continue; if (item == null || item.m_dropPrefab == null) continue;
string name = item.m_dropPrefab.name; string name = item.m_dropPrefab.name;
if (name == sigil) continue; if (name == sigil) continue;
if (!IsWood(name) && AnyStationAccepts(name)) continue; if (!IsWood(name) && AnyStationAccepts(name))
{
if (!spoke) spoke = Say("rov_msg_alfar_drone_sort_keep", name, KeepRepeatSeconds);
continue;
}
Container destination = DestinationFor(name); Container destination = DestinationFor(name);
if (destination == null) continue; if (destination == null)
{
if (!spoke) spoke = Say("rov_msg_alfar_drone_sort_nowhere", name, NowhereRepeatSeconds);
continue;
}
m_sortItem = name; m_sortItem = name;
m_sortDest = ZdoOf(destination); m_sortDest = ZdoOf(destination);
@ -1443,6 +1534,119 @@ namespace RacesOfValheim
return null; return null;
} }
// ================================================================ speech
/// <summary>When each item may be mentioned again, shared by every drone on this client, so
/// five drones looking at the same stone say it once and not five times.</summary>
private static readonly Dictionary<string, float> s_nextMention = new Dictionary<string, float>();
private const float NowhereRepeatSeconds = 300f;
private const float KeepRepeatSeconds = 1800f;
private const float SpeechRange = 40f;
/// <summary>Owner side: says the line once per cooldown per item, by writing it into the ZDO
/// where every client in range picks it up. Returns whether it spoke, so one plan says one
/// line and the bubbles do not overwrite each other.</summary>
private bool Say(string key, string item, float repeatSeconds, string station = "")
{
string mention = key + "|" + item;
float next;
if (s_nextMention.TryGetValue(mention, out next) && Time.time < next) return false;
s_nextMention[mention] = Time.time + repeatSeconds;
ZDO zdo = m_nview.GetZDO();
zdo.Set(KeySayKey, key);
zdo.Set(KeySayItem, item);
zdo.Set(KeySayStation, station);
zdo.Set(KeySaySeq, zdo.GetInt(KeySaySeq, 0) + 1);
return true;
}
/// <summary>Every client: a new line in the ZDO goes over the drone's head, the way vanilla's
/// NPCs talk, and into the chat window, for players close enough to care.</summary>
private void Listen()
{
if (m_nview == null || !m_nview.IsValid()) return;
ZDO zdo = m_nview.GetZDO();
int seq = zdo.GetInt(KeySaySeq, 0);
if (seq == m_heardSeq) return;
m_heardSeq = seq;
Player player = Player.m_localPlayer;
if (player == null || Chat.instance == null) return;
if (Vector3.Distance(player.transform.position, transform.position) > SpeechRange) return;
string item = zdo.GetString(KeySayItem, "");
GameObject prefab = ObjectDB.instance != null ? ObjectDB.instance.GetItemPrefab(item) : null;
ItemDrop drop = prefab != null ? prefab.GetComponent<ItemDrop>() : null;
string itemName = drop != null ? drop.m_itemData.m_shared.m_name : item;
string text = ModText.Get(zdo.GetString(KeySayKey, ""), itemName,
"$rov_piece_alfar_inngangskista_name", "$rov_piece_alfar_eldividarkista_name",
zdo.GetString(KeySayStation, ""));
string speaker = m_character != null ? Localization.instance.Localize(m_character.m_name) : "";
Chat.instance.SetNpcText(gameObject, Vector3.up * 1.5f, SpeechRange, 8f, speaker, text, false);
Chat.instance.AddString(speaker, text, Talker.Type.Normal);
}
/// <summary>
/// The mistake players make with the kiln: the wood is in a plain chest (vanilla even calls
/// one "Wood chest"), and only the Eldividarkista's wood is ever burnt. A station that takes
/// wood, standing idle with nothing for it in the Eldividarkista while the right wood sits in
/// another chest, gets a line explaining that. Every 30 s is plenty for something the player
/// fixes by hand.
/// </summary>
private void CheckIdleKiln()
{
if (Time.time < m_nextKilnCheck) return;
m_nextKilnCheck = Time.time + 30f;
foreach (ButlerStation station in m_stations)
{
if (!station.Alive || !station.Operable || station.HasWork || station.FreeSlots <= 0) continue;
if (m_wood != null && FirstAccepted(station, m_wood) != null) continue;
string misplaced = WoodElsewhereFor(station);
if (misplaced == null) continue;
// The station's own name token, so every language says "kiln" the game's way.
Piece piece = station.Behaviour.GetComponent<Piece>();
string stationName = piece != null ? piece.m_name : "";
if (Say("rov_msg_alfar_drone_kiln_wood", misplaced, NowhereRepeatSeconds, stationName)) return;
}
}
/// <summary>Wood the station would take, lying in the entry chest or a storage chest.</summary>
private string WoodElsewhereFor(ButlerStation station)
{
if (m_entry != null)
{
string found = WoodIn(m_entry, station);
if (found != null) return found;
}
foreach (Container chest in m_chests)
{
string found = WoodIn(chest, station);
if (found != null) return found;
}
return null;
}
private static string WoodIn(Container chest, ButlerStation station)
{
Inventory inventory = chest != null ? chest.GetInventory() : null;
if (inventory == null) return null;
foreach (ItemDrop.ItemData item in inventory.GetAllItems())
{
if (item == null || item.m_dropPrefab == null) continue;
string name = item.m_dropPrefab.name;
if (IsWood(name) && station.Accepts(name)) return name;
}
return null;
}
private bool DoSortFetch() private bool DoSortFetch()
{ {
if (m_sortItem == null || m_sortDest == ZDOID.None) return false; if (m_sortItem == null || m_sortDest == ZDOID.None) return false;
@ -1463,6 +1667,169 @@ namespace RacesOfValheim
// ================================================================ moving // ================================================================ moving
/// <summary>Vanilla pathing, through the private MoveTo. True the moment it has arrived.</summary> /// <summary>Vanilla pathing, through the private MoveTo. True the moment it has arrived.</summary>
/// <summary>F8 readout: what each worker within 60 m is doing and what vanilla still holds, and
/// for the nearest one, why each thing in the entry chest is (or is not) being sorted.</summary>
public static void DebugReport(Player player)
{
var lines = new List<string>();
AlfarDroneAI nearest = null;
float nearestDistance = 60f;
foreach (AlfarDroneAI drone in All)
{
if (drone == null || drone.m_ai == null) continue;
float distance = Vector3.Distance(drone.transform.position, player.transform.position);
if (distance > 60f) continue;
if (distance < nearestDistance) { nearestDistance = distance; nearest = drone; }
Character target = drone.m_ai.GetTargetCreature();
string targetText = target != null
? $"{Utils.GetPrefabName(target.gameObject)} {Vector3.Distance(target.transform.position, drone.transform.position):0}m"
: "none";
lines.Add($"[RoV drone] {distance:0}m: '{drone.Status}' job {(drone.m_job != null ? drone.m_job.Kind : "none")} " +
$"carry {drone.PayloadCount()} fight {drone.m_fighting} vanilla target {targetText} " +
$"alerted {drone.m_ai.IsAlerted()} flying {drone.m_character.IsFlying()} owner {drone.m_nview.IsOwner()}");
// The other half of what holds a fight: the 12 m sweep, and how long the linger has left.
Character near = BaseAI.FindClosestEnemy(drone.m_character, drone.transform.position, FightRange);
string nearText = near != null
? $"{Utils.GetPrefabName(near.gameObject)} {Vector3.Distance(near.transform.position, drone.transform.position):0}m"
: "none";
lines.Add($"[RoV drone] fight left {Mathf.Max(0f, drone.m_fightUntil - Time.time):0.0}s, " +
$"closest enemy {nearText}, in reach {(target != null && drone.InFightReach(target))}");
}
if (nearest == null) lines.Add("[RoV drone] no worker drone within 60m");
else
{
lines.AddRange(nearest.SortReport());
lines.AddRange(nearest.StationReport());
}
foreach (string line in lines)
{
Debug.Log(line);
player.Message(MessageHud.MessageType.TopLeft, line);
}
}
/// <summary>Why a station is (or is not) fed: what the last scan saw, the wood chest, and every
/// smelter, hearth or fermenter within the radius - and the ones just past it, by how much.</summary>
private IEnumerable<string> StationReport()
{
Vector3? anchor = Anchor;
if (anchor == null) { yield return "[RoV station] no anchor"; yield break; }
float radius = AlfarNexusConfig.NexusRadius.Value + m_radiusBonus;
yield return $"[RoV station] anchor {Vector3.Distance(transform.position, anchor.Value):0}m from drone, " +
$"radius {radius:0}, scanned {Time.time - m_scannedAt:0}s ago, {m_stations.Count} stations, {m_chests.Count} chests";
if (m_wood == null) yield return "[RoV station] no Eldividarkista in range (or it is open, or holds the sigil)";
else
{
var wood = new List<string>();
Inventory inventory = m_wood.GetInventory();
if (inventory != null)
{
foreach (ItemDrop.ItemData item in inventory.GetAllItems())
{
wood.Add(item.m_dropPrefab != null ? $"{item.m_dropPrefab.name}x{item.m_stack}" : $"{item.m_shared.m_name}(no prefab)");
}
}
yield return $"[RoV station] Eldividarkista {Vector3.Distance(m_wood.transform.position, anchor.Value):0}m from anchor, " +
$"open {m_wood.IsInUse()}, penalty {IsPenalised(ZdoOf(m_wood))}, holds [{string.Join(", ", wood.ToArray())}]";
}
foreach (ButlerStation station in m_stations)
{
if (!station.Alive) { yield return "[RoV station] (a station that is gone)"; continue; }
Container chest;
string material = FindMaterialFor(station, out chest);
string from = material == null ? "nothing" : $"{material} from {(chest == m_wood ? "Eldividarkista" : "entry")}";
yield return $"[RoV station] {Utils.GetPrefabName(station.Behaviour.gameObject)} " +
$"{Vector3.Distance(station.Position, anchor.Value):0}m: operable {station.Operable} free {station.FreeSlots} " +
$"work {station.HasWork} wood {station.Accepts("Wood")} penalty {IsPenalised(station.Id)} " +
$"claimed {ClaimedByOther(station.Id)} fuel {station.FuelPrefab ?? "-"}/{station.FuelWanted} | load: {from}";
}
// A station the scan cannot see because it stands past the edge.
List<Piece> pieces = AllPiecesField != null ? AllPiecesField.GetValue(null) as List<Piece> : null;
if (pieces == null) yield break;
foreach (Piece piece in pieces)
{
if (piece == null) continue;
float distance = Vector3.Distance(piece.transform.position, anchor.Value);
if (distance <= radius || distance > radius + 15f) continue;
if (ButlerStation.From(piece.gameObject) == null) continue;
yield return $"[RoV station] {Utils.GetPrefabName(piece.gameObject)} {distance:0}m: OUTSIDE the radius by {distance - radius:0.0}m";
}
}
private IEnumerable<string> SortReport()
{
if (m_entry == null) { yield return "[RoV sort] no entry chest in range"; yield break; }
if (m_entry.IsInUse()) yield return "[RoV sort] entry chest is open";
if (IsPenalised(ZdoOf(m_entry))) yield return "[RoV sort] entry chest is set aside (penalty)";
Inventory inventory = m_entry.GetInventory();
if (inventory == null) yield break;
var seen = new HashSet<string>();
foreach (ItemDrop.ItemData item in inventory.GetAllItems())
{
if (item == null) continue;
if (item.m_dropPrefab == null) { yield return $"[RoV sort] {item.m_shared.m_name}: no drop prefab"; continue; }
string name = item.m_dropPrefab.name;
if (!seen.Add(name)) continue;
string verdict;
if (name == AlfarSigil.PrefabName) verdict = "sigil, stays";
else if (!IsWood(name) && AnyStationAccepts(name)) verdict = "a station takes it, stays as work";
else
{
Container destination = DestinationFor(name);
verdict = destination != null
? $"goes to chest at {Vector3.Distance(destination.transform.position, m_entry.transform.position):0}m"
: $"nowhere: no storage chest holds it and none is empty ({m_chests.Count} chests)";
}
yield return $"[RoV sort] {name}: {verdict}";
}
}
/// <summary>
/// Where the drone flies to serve a station: beside it, a metre past its colliders on the side
/// the drone comes from. Vanilla lifts a flyer's goal to m_flyAltitudeMin over the ground under
/// it (BaseAI.MoveTo, IL), and under a charcoal kiln's origin that is inside the dome: the drone
/// pressed against the stone, never came within ArriveDistance, and the kiln went into the
/// penalty box (snakey's log, "Could not reach collect target"). Beside it is open air, and it
/// stays under a roof indoors, where aiming over the top would not. The loading and the sweep
/// still work from the station's own position.
/// </summary>
private Vector3 ApproachPoint(ButlerStation station)
{
Vector3 centre = station.Position;
bool any = false;
Bounds bounds = new Bounds(centre, Vector3.zero);
foreach (Collider collider in station.Behaviour.GetComponentsInChildren<Collider>())
{
if (collider == null || !collider.enabled || collider.isTrigger) continue;
if (any) bounds.Encapsulate(collider.bounds);
else { bounds = collider.bounds; any = true; }
}
if (!any) return centre;
Vector3 away = transform.position - bounds.center;
away.y = 0f;
if (away.sqrMagnitude < 0.01f) away = station.Transform.forward;
float reach = Mathf.Max(bounds.extents.x, bounds.extents.z) + 1f;
Vector3 point = bounds.center + away.normalized * reach;
point.y = centre.y;
return point;
}
private bool MoveToPoint(float dt, Vector3 point, float distance, bool run) private bool MoveToPoint(float dt, Vector3 point, float distance, bool run)
{ {
if (m_ai == null || MoveToMethod == null) return true; // cannot walk: act in place if (m_ai == null || MoveToMethod == null) return true; // cannot walk: act in place
@ -1633,7 +2000,7 @@ namespace RacesOfValheim
"Wood", "FineWood", "RoundLog", "ElderBark", "YggdrasilWood", "Blackwood", "Wood", "FineWood", "RoundLog", "ElderBark", "YggdrasilWood", "Blackwood",
}; };
private static bool IsWood(string prefabName) => s_woodFamily.Contains(prefabName); internal static bool IsWood(string prefabName) => s_woodFamily.Contains(prefabName);
/// <summary> /// <summary>
/// The first thing a station will take, and the chest it is in: raw material from the ENTRY chest /// The first thing a station will take, and the chest it is in: raw material from the ENTRY chest

View file

@ -105,6 +105,10 @@ namespace RacesOfValheim
BaseAI ai = prefab.GetComponent<BaseAI>(); BaseAI ai = prefab.GetComponent<BaseAI>();
if (ai != null) ai.m_randomMoveRange = 5f; if (ai != null) ai.m_randomMoveRange = 5f;
// A flyer's MoveTo lifts its goal to m_flyAltitudeMin above whatever solid is under it,
// the rock top included: at the vanilla height the miners hovered over a deposit out of
// reach and never struck.
if (ai != null && miner) { ai.m_flyAltitudeMin = 0.5f; ai.m_flyAltitudeMax = 2f; }
foreach (CharacterDrop drops in prefab.GetComponentsInChildren<CharacterDrop>(true)) foreach (CharacterDrop drops in prefab.GetComponentsInChildren<CharacterDrop>(true))
{ {
@ -251,34 +255,100 @@ namespace RacesOfValheim
public float Radius = 12f; public float Radius = 12f;
public float LiveSeconds = 120f; public float LiveSeconds = 120f;
private float born; // The job lives in the drone's ZDO, not only in these fields: Valheim destroys a creature
// when its zone unloads and builds a fresh one when the zone comes back, and the fresh
// one had a zero Centre, so it searched around the world origin and stood idle. The
// birth time is network time, so a rebuilt drone does not get a new two minutes either.
private static readonly int CentreKey = "rov_graf_centre".GetStableHashCode();
private static readonly int RadiusKey = "rov_graf_radius".GetStableHashCode();
private static readonly int LifeKey = "rov_graf_life".GetStableHashCode();
private static readonly int BornKey = "rov_graf_born".GetStableHashCode();
private const float Reach = 4f;
private bool loaded;
private double bornAt;
private float nextStrike; private float nextStrike;
private Component target; private Component target;
private float lastDistance = -1f;
private int strikes;
private string lastHit = "none";
public static readonly List<AlfarMiner> All = new List<AlfarMiner>();
private void OnEnable() { All.Add(this); }
private void OnDisable() { All.Remove(this); }
private static readonly System.Reflection.MethodInfo MoveToMethod = private static readonly System.Reflection.MethodInfo MoveToMethod =
AccessTools.Method(typeof(BaseAI), "MoveTo", new[] { typeof(float), typeof(Vector3), typeof(float), typeof(bool) }); AccessTools.Method(typeof(BaseAI), "MoveTo", new[] { typeof(float), typeof(Vector3), typeof(float), typeof(bool) });
private void Start() private static double Now => ZNet.instance != null ? ZNet.instance.GetTimeSeconds() : Time.time;
/// <summary>Called by the throw right after the drone is made: the job, into the ZDO.</summary>
public void Assign(Vector3 centre, float radius, float liveSeconds)
{ {
born = Time.time; Centre = centre;
Radius = radius;
LiveSeconds = liveSeconds;
bornAt = Now;
loaded = true;
ZNetView nview = GetComponent<ZNetView>();
if (nview == null || !nview.IsValid()) return;
ZDO zdo = nview.GetZDO();
zdo.Set(CentreKey, centre);
zdo.Set(RadiusKey, radius);
zdo.Set(LifeKey, liveSeconds);
zdo.Set(BornKey, (long)(bornAt * 1000.0));
}
/// <summary>
/// A drone rebuilt from its ZDO reads its job back. One with no job at all (thrown by an
/// older build) digs around where it stands, which is where it was thrown.
/// </summary>
private void Load()
{
loaded = true;
ZNetView nview = GetComponent<ZNetView>();
ZDO zdo = nview != null && nview.IsValid() ? nview.GetZDO() : null;
long born = zdo != null ? zdo.GetLong(BornKey, 0L) : 0L;
if (born == 0L)
{
Centre = transform.position;
bornAt = Now;
return;
}
Centre = zdo.GetVec3(CentreKey, transform.position);
Radius = zdo.GetFloat(RadiusKey, Radius);
LiveSeconds = zdo.GetFloat(LifeKey, LiveSeconds);
bornAt = born / 1000.0;
} }
public bool Tick(MonsterAI ai, float dt) public bool Tick(MonsterAI ai, float dt)
{ {
if (Time.time - born >= LiveSeconds) if (!loaded) Load();
if (Now - bornAt >= LiveSeconds)
{ {
ZNetView nview = GetComponent<ZNetView>(); ZNetView nview = GetComponent<ZNetView>();
if (nview != null && nview.IsValid() && nview.IsOwner()) ZNetScene.instance.Destroy(gameObject); if (nview != null && nview.IsValid() && nview.IsOwner()) ZNetScene.instance.Destroy(gameObject);
return true; return true;
} }
if (target == null || !target.gameObject.activeInHierarchy) target = FindDeposit(); // A deposit another drone just broke is still there until the end of the frame, with a
if (target == null) { ai.StopMoving(); return true; } // dead network view: drop it and look again.
if (target == null || !target.gameObject.activeInHierarchy || !Live(target)) target = FindDeposit();
Vector3 point = Vector3.zero;
Collider area = target != null ? NearestArea(target, out point) : null;
if (area == null) { target = null; ai.StopMoving(); return true; }
Vector3 point = target.transform.position; // Measured to the closest point of the rock, not to its root: a copper deposit's root
// sits at its base inside the mesh, so a drone aiming there stopped on top of the rock
// and never came within reach.
float distance = Vector3.Distance(transform.position, point); float distance = Vector3.Distance(transform.position, point);
lastDistance = distance;
if (distance > 3.5f) if (distance > Reach)
{ {
if (MoveToMethod != null) MoveToMethod.Invoke(ai, new object[] { dt, point + Vector3.up * 1.5f, 2f, true }); if (MoveToMethod != null) MoveToMethod.Invoke(ai, new object[] { dt, point + Vector3.up * 1.5f, 2f, true });
return true; return true;
@ -287,15 +357,30 @@ namespace RacesOfValheim
ai.StopMoving(); ai.StopMoving();
if (Time.time < nextStrike) return true; if (Time.time < nextStrike) return true;
nextStrike = Time.time + 1f; nextStrike = Time.time + 1f;
Strike(target); Strike(target, area, point);
strikes++;
return true; return true;
} }
private static string[] names; private static string[] names;
private static string[] Deposits => names ?? (names = AlfarNexusConfig.MinerDeposits.Value.Split( private static string namesSource;
new[] { ',' }, System.StringSplitOptions.RemoveEmptyEntries));
private bool IsPrecious(string prefabName) // Read again when the config line changes, so an edit in game counts without a restart.
private static string[] Deposits
{
get
{
string value = AlfarNexusConfig.MinerDeposits.Value;
if (names == null || namesSource != value)
{
namesSource = value;
names = value.Split(new[] { ',' }, System.StringSplitOptions.RemoveEmptyEntries);
}
return names;
}
}
private static bool IsPrecious(string prefabName)
{ {
foreach (string wanted in Deposits) foreach (string wanted in Deposits)
{ {
@ -310,12 +395,11 @@ namespace RacesOfValheim
float bestDistance = float.MaxValue; float bestDistance = float.MaxValue;
foreach (Collider collider in Physics.OverlapSphere(Centre, Radius, ~0, QueryTriggerInteraction.Ignore)) foreach (Collider collider in Physics.OverlapSphere(Centre, Radius, ~0, QueryTriggerInteraction.Ignore))
{ {
Component deposit = collider.GetComponentInParent<MineRock5>(); Component deposit = DepositOf(collider);
if (deposit == null) deposit = collider.GetComponentInParent<MineRock>();
if (deposit == null) deposit = collider.GetComponentInParent<Destructible>();
if (deposit == null) continue; if (deposit == null) continue;
string prefabName = Utils.GetPrefabName(deposit.gameObject); if (!Live(deposit)) continue;
string prefabName = DepositName(deposit);
if (!IsPrecious(prefabName)) continue; if (!IsPrecious(prefabName)) continue;
float distance = Vector3.Distance(transform.position, deposit.transform.position); float distance = Vector3.Distance(transform.position, deposit.transform.position);
@ -324,28 +408,289 @@ namespace RacesOfValheim
return best; return best;
} }
private void Strike(Component deposit) /// <summary>
/// The live hit area of the deposit closest to the drone, and the closest point on it.
/// MineRock and MineRock5 only take a hit on one of their own areas; a MineRock with an area
/// root (tin) keeps its base model collider apart, and a hit on that one is thrown away.
/// Broken areas are switched off, so only active colliders count.
/// </summary>
private Collider NearestArea(Component deposit, out Vector3 point)
{
point = Vector3.zero;
MineRock rock = deposit as MineRock;
GameObject root = rock != null && rock.m_areaRoot != null ? rock.m_areaRoot : deposit.gameObject;
Collider best = null;
float bestDistance = float.MaxValue;
foreach (Collider collider in root.GetComponentsInChildren<Collider>())
{
if (collider == null || !collider.enabled) continue;
Vector3 closest = collider.bounds.ClosestPoint(transform.position);
float distance = Vector3.Distance(transform.position, closest);
if (distance < bestDistance) { best = collider; bestDistance = distance; point = closest; }
}
return best;
}
private void Strike(Component deposit, Collider area, Vector3 point)
{ {
IDestructible destructible = deposit as IDestructible; IDestructible destructible = deposit as IDestructible;
if (destructible == null) return; if (destructible == null) { lastHit = $"{deposit.GetType().Name} is not IDestructible"; return; }
HitData hit = new HitData(); HitData hit = new HitData();
hit.m_damage.m_pickaxe = AlfarNexusConfig.MinerDamage.Value; hit.m_damage.m_pickaxe = AlfarNexusConfig.MinerDamage.Value;
hit.m_toolTier = 100; hit.m_toolTier = 100;
hit.m_dodgeable = false; hit.m_dodgeable = false;
hit.m_blockable = false; hit.m_blockable = false;
hit.m_point = deposit.transform.position; hit.m_hitCollider = area;
hit.m_dir = (deposit.transform.position - transform.position).normalized; hit.m_point = point;
hit.m_dir = (area.bounds.center - transform.position).normalized;
// Vanilla MineRock (tin) reads the attacker's ZDOID for its hit effects without a null
// check: a hit with no attacker throws before the area can break.
hit.SetAttacker(GetComponent<Character>());
// MineRock5 picks the piece of the rock to hurt from the collider that was hit. // Overwritten by the patches below at each step the hit gets through. Vanilla runs the
Collider collider = deposit.GetComponentInChildren<Collider>(); // RPC on this machine at once when we own the deposit, so `striking` is still set then.
if (collider != null) lastHit = "Damage not entered";
striking = this;
rpcRan = false;
try
{ {
hit.m_hitCollider = collider; destructible.Damage(hit);
hit.m_point = collider.bounds.center;
// The F8 readout showed the hit entering Damage with every gate open and this
// machine owning the deposit, and the RPC handler never running: the routed call
// left for the network instead of being handled here. When we own the deposit,
// call its own handler directly - the same resistance, tier and break logic, only
// without the routing.
if (!rpcRan && OwnsDeposit(deposit)) StrikeDirect(deposit, area, hit);
}
finally { striking = null; }
} }
destructible.Damage(hit); private static bool rpcRan;
private static readonly System.Reflection.MethodInfo DestructibleRpc = AccessTools.Method(typeof(Destructible), "RPC_Damage");
private static readonly System.Reflection.MethodInfo MineRockRpc = AccessTools.Method(typeof(MineRock), "RPC_Hit");
private static readonly System.Reflection.MethodInfo MineRockArea = AccessTools.Method(typeof(MineRock), "GetAreaIndex");
private static readonly System.Reflection.MethodInfo MineRock5Rpc = AccessTools.Method(typeof(MineRock5), "RPC_Damage");
private static readonly System.Reflection.MethodInfo MineRock5Area = AccessTools.Method(typeof(MineRock5), "GetAreaIndex");
private static readonly System.Reflection.FieldInfo RpcIdField = AccessTools.Field(typeof(ZRoutedRpc), "m_id");
private static bool OwnsDeposit(Component deposit)
{
ZNetView nview = deposit.GetComponent<ZNetView>();
return nview != null && nview.IsValid() && nview.IsOwner();
}
private void StrikeDirect(Component deposit, Collider area, HitData hit)
{
long sender = ZDOMan.GetSessionID();
string entry = lastHit;
try
{
if (deposit is Destructible && DestructibleRpc != null)
{
DestructibleRpc.Invoke(deposit, new object[] { sender, hit });
}
else if (deposit is MineRock && MineRockRpc != null && MineRockArea != null)
{
int index = (int)MineRockArea.Invoke(deposit, new object[] { area });
if (index < 0) { lastHit = "direct: collider is not a MineRock area"; return; }
MineRockRpc.Invoke(deposit, new object[] { sender, hit, index });
}
else if (deposit is MineRock5 && MineRock5Rpc != null && MineRock5Area != null)
{
int index = (int)MineRock5Area.Invoke(deposit, new object[] { area });
if (index < 0) { lastHit = "direct: collider is not a MineRock5 area"; return; }
MineRock5Rpc.Invoke(deposit, new object[] { sender, hit, index });
}
else
{
lastHit = $"direct: no handler for {deposit.GetType().Name}";
return;
}
lastHit = $"direct, {lastHit} | before: {entry}";
}
catch (System.Exception ex)
{
System.Exception inner = ex.InnerException ?? ex;
lastHit = $"direct failed: {inner.GetType().Name}: {inner.Message}";
Jotunn.Logger.LogWarning($"[Alfar] Grafvaettir direct hit failed: {inner}");
}
}
// ─── F8 diagnostics: what each hit did on arrival ──────────────────────
private static AlfarMiner striking;
private static AlfarMiner MinerOf(HitData hit)
{
if (striking != null) return striking;
Character attacker = hit != null ? hit.GetAttacker() : null;
return attacker != null ? attacker.GetComponent<AlfarMiner>() : null;
}
private static readonly System.Reflection.FieldInfo FirstFrameField = AccessTools.Field(typeof(Destructible), "m_firstFrame");
/// <summary>The gates in front of the RPC: whose deposit it is and whether the view is live.</summary>
private static void RecordEntry(Component deposit, string extra)
{
if (striking == null) return;
ZNetView nview = deposit.GetComponent<ZNetView>();
bool valid = nview != null && nview.IsValid();
long owner = valid ? nview.GetZDO().GetOwner() : -1L;
long me = ZDOMan.GetSessionID();
Character attacker = striking.GetComponent<Character>();
object rpcId = RpcIdField != null && ZRoutedRpc.instance != null ? RpcIdField.GetValue(ZRoutedRpc.instance) : null;
striking.lastHit = $"Damage entered{extra} valid={valid} owner={owner} session={me} rpcId={rpcId} " +
$"attackerZdo={(attacker != null ? attacker.GetZDOID().ToString() : "none")}, no RPC";
}
[HarmonyPatch(typeof(Destructible), nameof(Destructible.Damage))]
public static class Alfar_Miner_DestructibleEnter_Patch
{
public static void Prefix(Destructible __instance)
{
object first = FirstFrameField != null ? FirstFrameField.GetValue(__instance) : null;
RecordEntry(__instance, $" firstFrame={first}");
}
}
[HarmonyPatch(typeof(MineRock), nameof(MineRock.Damage))]
public static class Alfar_Miner_MineRockEnter_Patch
{
public static void Prefix(MineRock __instance) => RecordEntry(__instance, "");
}
[HarmonyPatch(typeof(MineRock5), nameof(MineRock5.Damage))]
public static class Alfar_Miner_MineRock5Enter_Patch
{
public static void Prefix(MineRock5 __instance) => RecordEntry(__instance, "");
}
private static void Record(HitData hit, string kind, float before, float after, int minTier)
{
AlfarMiner miner = MinerOf(hit);
if (miner == null) return;
if (miner == striking) rpcRan = true;
miner.lastHit = $"{kind} hp {before:0.#}->{after:0.#} dmg {hit.GetTotalDamage():0.#} " +
$"pick {hit.m_damage.m_pickaxe:0.#} tier {hit.m_toolTier}/{minTier}";
}
[HarmonyPatch(typeof(Destructible), "RPC_Damage")]
public static class Alfar_Miner_DestructibleHit_Patch
{
private static float Health(Destructible d)
{
ZNetView nview = d.GetComponent<ZNetView>();
return nview != null && nview.IsValid() ? nview.GetZDO().GetFloat(ZDOVars.s_health, d.m_health) : -1f;
}
public static void Prefix(Destructible __instance, HitData hit, out float __state)
{
__state = MinerOf(hit) != null ? Health(__instance) : -1f;
}
public static void Postfix(Destructible __instance, HitData hit, float __state)
{
if (MinerOf(hit) == null) return;
Record(hit, "Destructible", __state, Health(__instance), __instance.m_minToolTier);
}
}
[HarmonyPatch(typeof(MineRock), "RPC_Hit")]
public static class Alfar_Miner_MineRockHit_Patch
{
private static float Health(MineRock rock, int area)
{
ZNetView nview = rock.GetComponent<ZNetView>();
return nview != null && nview.IsValid() ? nview.GetZDO().GetFloat("Health" + area, rock.GetHealth()) : -1f;
}
public static void Prefix(MineRock __instance, HitData hit, int hitAreaIndex, out float __state)
{
__state = MinerOf(hit) != null ? Health(__instance, hitAreaIndex) : -1f;
}
public static void Postfix(MineRock __instance, HitData hit, int hitAreaIndex, float __state)
{
if (MinerOf(hit) == null) return;
Record(hit, $"MineRock area {hitAreaIndex}", __state, Health(__instance, hitAreaIndex), __instance.m_minToolTier);
}
}
[HarmonyPatch(typeof(MineRock5), "DamageArea")]
public static class Alfar_Miner_MineRock5Hit_Patch
{
public static void Postfix(MineRock5 __instance, int hitAreaIndex, HitData hit, bool __result)
{
if (MinerOf(hit) == null) return;
Record(hit, $"MineRock5 area {hitAreaIndex} damaged={__result}", -1f, -1f, __instance.m_minToolTier);
}
}
private static bool Live(Component deposit)
{
ZNetView nview = deposit.GetComponent<ZNetView>();
return nview != null && nview.IsValid();
}
/// <summary>
/// The deposit's prefab name, read from its ZDO. Not from the GameObject: MineRock5 renames
/// its own object to "___MineRock5 m_meshFilter" in Awake, so a broken copper vein
/// (rock4_copper_frac) never matched the list and the drones stopped after the first blow.
/// </summary>
private static string DepositName(Component deposit)
{
ZNetView nview = deposit.GetComponent<ZNetView>();
if (nview != null && nview.IsValid() && ZNetScene.instance != null)
{
GameObject prefab = ZNetScene.instance.GetPrefab(nview.GetZDO().GetPrefab());
if (prefab != null) return prefab.name;
}
return Utils.GetPrefabName(deposit.gameObject);
}
private static Component DepositOf(Collider collider)
{
Component deposit = collider.GetComponentInParent<MineRock5>();
if (deposit == null) deposit = collider.GetComponentInParent<MineRock>();
if (deposit == null) deposit = collider.GetComponentInParent<Destructible>();
return deposit;
}
/// <summary>
/// F8 readout: what the camera looks at (is it a deposit, of which kind, on the list?) and
/// what each live miner is doing (its target, how far, how many strikes).
/// </summary>
public static void DebugReport(Player player)
{
var lines = new List<string>();
Transform aim = GameCamera.instance != null ? GameCamera.instance.transform : player.transform;
if (Physics.Raycast(aim.position, aim.forward, out RaycastHit hit, 50f, ~0, QueryTriggerInteraction.Ignore))
{
Component deposit = DepositOf(hit.collider);
string prefabName = deposit != null ? DepositName(deposit) : Utils.GetPrefabName(hit.collider.transform.root.gameObject);
lines.Add($"[RoV graf] look: {hit.collider.name} on {prefabName} " +
(deposit != null ? $"{deposit.GetType().Name} listed={IsPrecious(prefabName)}" : "not a deposit"));
}
else lines.Add("[RoV graf] look: nothing within 50m");
foreach (AlfarMiner miner in All)
{
if (miner == null) continue;
string targetName = miner.target != null ? DepositName(miner.target) : "none";
lines.Add($"[RoV graf] miner {Vector3.Distance(miner.transform.position, player.transform.position):0}m away: " +
$"target {targetName} dist {miner.lastDistance:0.0} strikes {miner.strikes} " +
$"age {Now - miner.bornAt:0}s centre {miner.Centre} r {miner.Radius:0} | last hit: {miner.lastHit}");
}
foreach (string line in lines)
{
Debug.Log(line);
player.Message(MessageHud.MessageType.TopLeft, line);
}
} }
[HarmonyPatch(typeof(MonsterAI), "UpdateAI")] [HarmonyPatch(typeof(MonsterAI), "UpdateAI")]

View file

@ -0,0 +1,166 @@
using System.Collections.Generic;
using Jotunn.Managers;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// The Eldividarkista's own body. Players kept mistaking a plain "Wood chest" for it, so it must
/// not look like any chest they can build: the box and lid are the Mistlands dvergr crate (a prop
/// nobody can place), repainted as blackened iron with an aged-bronze frame
/// (scripts/paint_fire_chest.py), with an iron grate on the front.
///
/// Behind the grate the fire shows only while the chest holds wood the drones may burn: a dark
/// grate means empty. No light source, on purpose - a base full of chests must not glow.
/// </summary>
public static class AlfarFireChest
{
private const string CrateName = "dvergrprops_crate";
private const string EmbersSource = "fx_Torch_Carried";
// The crate is a 1.02 m cube, stretched into a chest about the size of the vanilla one:
// 1.6 m wide, 0.8 m deep. Its front face (+z, away from the lid's hinge) ends up here.
private static readonly Vector3 Stretch = new Vector3(1.6f, 1f, 0.8f);
private const float FrontZ = 0.515f * 0.8f;
private const float LidY = 0.81f;
private const float GrateWidth = 0.62f * 1.6f;
private const int GrateGaps = 10;
private const float GrateHeight = 0.36f;
private const float GrateY = 0.42f;
private static readonly Color Ember = new Color(1f, 0.42f, 0.1f);
/// <summary>Swaps the cloned wood chest's meshes for the fire chest. False leaves the wood
/// chest's look in place, with a warning, rather than an invisible chest.</summary>
public static bool Build(GameObject prefab)
{
GameObject crate = PrefabManager.Cache.GetPrefab<GameObject>(CrateName);
Transform crateNew = crate != null ? crate.transform.Find("new") : null;
Transform visual = prefab.transform.Find("New");
if (crateNew == null || crateNew.childCount < 3 || visual == null)
{
Jotunn.Logger.LogWarning("[Alfar] No dvergr crate to build the Eldividarkista from; it keeps the wood chest's look.");
return false;
}
// The wood chest's box, lids and LOD group go; "New" itself stays, because WearNTear
// switches it as the piece's healthy look.
for (int i = visual.childCount - 1; i >= 0; i--) Object.DestroyImmediate(visual.GetChild(i).gameObject);
LODGroup lod = visual.GetComponent<LODGroup>();
if (lod != null) Object.DestroyImmediate(lod);
// The crate's high meshes, in the order the prefab keeps them: box, contents, lid. The
// contents are the glowing dvergr cargo and stay behind.
GameObject body = Object.Instantiate(crateNew.GetChild(0).gameObject, visual, false);
body.name = "body";
body.transform.localScale = Vector3.Scale(body.transform.localScale, Stretch);
GameObject lidClosed = Object.Instantiate(crateNew.GetChild(2).gameObject, visual, false);
lidClosed.name = "lid_closed";
lidClosed.transform.localScale = Vector3.Scale(lidClosed.transform.localScale, Stretch);
// The open lid: the closed one turned up 100 degrees about its back edge.
GameObject lidOpen = Object.Instantiate(lidClosed, visual, false);
lidOpen.name = "lid_open";
foreach (Collider collider in lidOpen.GetComponentsInChildren<Collider>(true)) Object.DestroyImmediate(collider);
Vector3 hinge = new Vector3(0f, LidY, -FrontZ);
Quaternion turn = Quaternion.Euler(-100f, 0f, 0f);
lidOpen.transform.localPosition = hinge + turn * (lidClosed.transform.localPosition - hinge);
lidOpen.transform.localRotation = turn * lidClosed.transform.localRotation;
lidOpen.SetActive(false);
Container container = prefab.GetComponent<Container>();
if (container != null)
{
container.m_open = lidOpen;
container.m_closed = lidClosed;
}
// Only a retextured material is a copy; without the paint, writing to it would change every
// dvergr crate in the Mistlands too.
Texture2D paint = PieceLook.LoadTexture("AlfarFireChest_d.png");
if (paint != null) PieceLook.Retexture(visual, new Dictionary<string, Texture> { { "Crate_d", paint } });
Material iron = paint != null ? body.GetComponent<MeshRenderer>()?.sharedMaterial : null;
if (iron != null)
{
// The crate's normal map is wood planks; on plates it would draw seams that are not there.
if (iron.HasProperty("_BumpMap")) iron.SetTexture("_BumpMap", null);
if (iron.HasProperty("_Metallic")) iron.SetFloat("_Metallic", 0.6f);
if (iron.HasProperty("_Glossiness")) iron.SetFloat("_Glossiness", 0.45f);
}
Transform grate = BuildGrate(visual, iron, out Renderer glow);
ParticleSystem embers = AddEmbers(grate);
AlfarChestGlow look = prefab.AddComponent<AlfarChestGlow>();
look.Glows = new[] { glow };
look.Embers = embers;
look.GlowColor = Ember * 2f;
look.WoodOnly = true;
return true;
}
/// <summary>The grate: a glowing plate just off the front face, a frame and bars in front of it.</summary>
private static Transform BuildGrate(Transform visual, Material iron, out Renderer glow)
{
Transform grate = new GameObject("grate").transform;
grate.SetParent(visual, false);
grate.gameObject.layer = visual.gameObject.layer;
Material bars = iron != null ? new Material(iron) { name = "AlfarFireChest_bars" } : null;
if (bars != null)
{
bars.SetTexture("_MainTex", null);
bars.color = new Color(0.16f, 0.15f, 0.15f);
}
glow = Block(grate, "glow", new Vector3(0f, GrateY, FrontZ + 0.005f), new Vector3(GrateWidth, GrateHeight, 0.01f), bars).GetComponent<Renderer>();
const float frame = 0.035f;
foreach (float x in new[] { -GrateWidth / 2f, GrateWidth / 2f })
Block(grate, "frame", new Vector3(x, GrateY, FrontZ + 0.02f), new Vector3(frame, GrateHeight + frame, 0.04f), bars);
foreach (float y in new[] { GrateY - GrateHeight / 2f, GrateY + GrateHeight / 2f })
Block(grate, "frame", new Vector3(0f, y, FrontZ + 0.02f), new Vector3(GrateWidth + frame, frame, 0.04f), bars);
for (int i = 1; i < GrateGaps; i++)
{
float x = -GrateWidth / 2f + GrateWidth * i / GrateGaps;
Block(grate, "bar", new Vector3(x, GrateY, FrontZ + 0.02f), new Vector3(0.022f, GrateHeight, 0.03f), bars);
}
Block(grate, "bar", new Vector3(0f, GrateY, FrontZ + 0.022f), new Vector3(GrateWidth, 0.022f, 0.03f), bars);
return grate;
}
/// <summary>A plain box with no collider, for trim the borrowed meshes do not have.</summary>
internal static GameObject Block(Transform parent, string name, Vector3 position, Vector3 size, Material material)
{
GameObject block = GameObject.CreatePrimitive(PrimitiveType.Cube);
Object.DestroyImmediate(block.GetComponent<Collider>());
block.name = name;
block.layer = parent.gameObject.layer;
block.transform.SetParent(parent, false);
block.transform.localPosition = position;
block.transform.localScale = size;
if (material != null) block.GetComponent<Renderer>().sharedMaterial = material;
return block;
}
/// <summary>The carried torch's embers, rising off the top of the grate.</summary>
private static ParticleSystem AddEmbers(Transform grate)
{
GameObject torch = PrefabManager.Cache.GetPrefab<GameObject>(EmbersSource);
Transform source = torch != null ? torch.transform.Find("Embers") : null;
if (source == null)
{
Jotunn.Logger.LogWarning("[Alfar] No torch embers for the Eldividarkista; its grate glows without sparks.");
return null;
}
GameObject embers = Object.Instantiate(source.gameObject, grate, false);
embers.name = "embers";
embers.transform.localPosition = new Vector3(0f, GrateY + GrateHeight / 2f, FrontZ + 0.05f);
embers.transform.localRotation = Quaternion.identity;
return embers.GetComponent<ParticleSystem>();
}
}
}

View file

@ -0,0 +1,137 @@
using System.Collections.Generic;
using Jotunn.Managers;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// The Inngangskista's own body, the cold twin of <see cref="AlfarFireChest"/>: the dvergr loot
/// chest of the Mistlands towns (seen, never built), its panels repainted navy steel
/// (scripts/paint_input_chest.py) and its copper trim turned silver. A cyan line set into the
/// lid shines while the chest holds anything for the drones, and goes dark once they have
/// emptied it.
/// </summary>
public static class AlfarInputChest
{
private const string SourceName = "TreasureChest_dvergrtown";
// The town chest is placed at 1.2 and its meshes at 1.5 on top: 1.66 m wide, a vanilla chest's size.
private const float SourceScale = 1.2f;
private const float MeshScale = 1.5f * SourceScale;
private const float LidTop = 0.48f * MeshScale;
private const float LidHalfX = 0.42f * MeshScale;
private const float LidHalfZ = 0.24f * MeshScale;
private const float InlayInset = 0.10f;
private const float InlayWidth = 0.03f;
private static readonly Color Trim = new Color(0.9f, 0.95f, 1f);
private static readonly Color Inlay = new Color(0.35f, 0.9f, 1f);
/// <summary>Swaps the cloned wood chest's meshes for the input chest. False leaves the wood
/// chest's look in place, with a warning.</summary>
public static bool Build(GameObject prefab)
{
GameObject source = PrefabManager.Cache.GetPrefab<GameObject>(SourceName);
Transform sourceNew = source != null ? source.transform.Find("New") : null;
Transform box = sourceNew != null ? sourceNew.Find("stonechest") : null;
Transform closed = sourceNew != null ? sourceNew.Find("stonechesttop_closed") : null;
Transform open = sourceNew != null ? sourceNew.Find("stonechesttop_open") : null;
Transform visual = prefab.transform.Find("New");
if (box == null || closed == null || open == null || visual == null)
{
Jotunn.Logger.LogWarning("[Alfar] No dvergr chest to build the Inngangskista from; it keeps the wood chest's look.");
return false;
}
for (int i = visual.childCount - 1; i >= 0; i--) Object.DestroyImmediate(visual.GetChild(i).gameObject);
LODGroup lod = visual.GetComponent<LODGroup>();
if (lod != null) Object.DestroyImmediate(lod);
GameObject body = Copy(box, visual, "body");
GameObject lidClosed = Copy(closed, visual, "lid_closed");
GameObject lidOpen = Copy(open, visual, "lid_open");
lidOpen.SetActive(false);
Container container = prefab.GetComponent<Container>();
if (container != null)
{
container.m_open = lidOpen;
container.m_closed = lidClosed;
}
Texture2D paint = PieceLook.LoadTexture("AlfarInputChest_d.png");
if (paint == null) return true; // the dvergr chest as it is: still not a vanilla chest
PieceLook.Retexture(visual, new Dictionary<string, Texture> { { "dvergrchestWorn_d", paint } });
// The trim shares the anvil's texture, so it is recoloured on a copy instead; the panels'
// material is already a copy from Retexture.
var copies = new Dictionary<Material, Material>();
Material panel = null;
foreach (Renderer renderer in visual.GetComponentsInChildren<Renderer>(true))
{
Material[] materials = renderer.sharedMaterials;
for (int i = 0; i < materials.Length; i++)
{
Material material = materials[i];
if (material == null) continue;
if (material.name.EndsWith("_rov")) { panel = panel ?? material; continue; }
if (!material.name.StartsWith("dvergr_metal_furnmiture")) continue;
if (!copies.TryGetValue(material, out Material trim))
{
trim = new Material(material) { name = material.name + "_rov" };
trim.color = Trim;
if (trim.HasProperty("_MetalColor")) trim.SetColor("_MetalColor", Trim);
copies[material] = trim;
}
materials[i] = trim;
}
renderer.sharedMaterials = materials;
}
AlfarChestGlow look = prefab.AddComponent<AlfarChestGlow>();
look.Glows = BuildInlay(lidClosed.transform, panel);
look.GlowColor = Inlay * 1.6f;
look.WoodOnly = false;
return true;
}
/// <summary>A copy of one of the town chest's parts, at the town chest's size and on the piece layer.</summary>
private static GameObject Copy(Transform part, Transform parent, string name)
{
GameObject copy = Object.Instantiate(part.gameObject, parent, false);
copy.name = name;
copy.transform.localPosition = part.localPosition * SourceScale;
copy.transform.localScale = part.localScale * SourceScale;
foreach (Transform t in copy.GetComponentsInChildren<Transform>(true)) t.gameObject.layer = parent.gameObject.layer;
return copy;
}
/// <summary>The cyan line on the lid: four thin strips just above it, inset from the edge. They
/// hang off the closed lid, so they go with it when the chest opens. The lid is scaled, so the
/// sizes are divided back out of it.</summary>
private static Renderer[] BuildInlay(Transform lid, Material panel)
{
Material cold = panel != null ? new Material(panel) { name = "AlfarInputChest_inlay" } : null;
if (cold != null)
{
cold.SetTexture("_MainTex", null);
cold.color = new Color(0.08f, 0.12f, 0.16f);
}
float k = 1f / lid.localScale.x;
float x = LidHalfX - InlayInset, z = LidHalfZ - InlayInset, y = LidTop + 0.004f;
var strips = new List<Renderer>();
foreach (float side in new[] { -z, z })
strips.Add(Strip(lid, new Vector3(0f, y, side) * k, new Vector3(2f * x + InlayWidth, 0.01f, InlayWidth) * k, cold));
foreach (float side in new[] { -x, x })
strips.Add(Strip(lid, new Vector3(side, y, 0f) * k, new Vector3(InlayWidth, 0.01f, 2f * z) * k, cold));
return strips.ToArray();
}
private static Renderer Strip(Transform lid, Vector3 position, Vector3 size, Material material)
{
return AlfarFireChest.Block(lid, "inlay", position, size, material).GetComponent<Renderer>();
}
}
}

View file

@ -48,7 +48,7 @@ namespace RacesOfValheim
float target = 0f; float target = 0f;
if (Time.time - AlfarArchon.StartedAt < 0.6f) target = 4f; // lift off if (Time.time - AlfarArchon.StartedAt < 0.6f) target = 4f; // lift off
else if (RaceInput.Allowed && JumpHeld()) target = speed; else if (RaceInput.Allowed && JumpHeld()) target = speed;
else if (RaceInput.Allowed && ZInput.GetButton("Crouch")) target = -speed; else if (RaceInput.Allowed && CrouchHeld()) target = -speed;
Vector3 velocity = flyer.linearVelocity; Vector3 velocity = flyer.linearVelocity;
velocity.y = Mathf.Lerp(velocity.y, target, 0.25f); velocity.y = Mathf.Lerp(velocity.y, target, 0.25f);
@ -97,9 +97,15 @@ namespace RacesOfValheim
private static bool JumpHeld() private static bool JumpHeld()
{ {
// ZInput's "Jump" covers the space bar and the pad's jump button alike, and respects the // "Jump" is the keyboard binding only; the pad's button is a separate "JoyJump", read
// controls the player picked in the settings. // the way PlayerController reads it, kept off while a radial menu has the pad.
return ZInput.GetButton("Jump"); return ZInput.GetButton("Jump") || (ZInput.GetButton("JoyJump") && !Hud.InRadial());
}
private static bool CrouchHeld()
{
// Same split as jump: PlayerController ORs "Crouch" with "JoyCrouch".
return ZInput.GetButton("Crouch") || (ZInput.GetButton("JoyCrouch") && !Hud.InRadial());
} }
private static void FlushSpend(Player player) private static void FlushSpend(Player player)

View file

@ -22,7 +22,11 @@ namespace RacesOfValheim
public static void Throw(Player player) public static void Throw(Player player)
{ {
if (Time.time < readyAt) return; if (Time.time < readyAt)
{
player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_alfar_graf_cooldown", Mathf.CeilToInt(readyAt - Time.time)));
return;
}
Transform aim = GameCamera.instance != null ? GameCamera.instance.transform : player.transform; Transform aim = GameCamera.instance != null ? GameCamera.instance.transform : player.transform;
Vector3 origin = aim.position; Vector3 origin = aim.position;
@ -76,12 +80,7 @@ namespace RacesOfValheim
GameObject spawned = Object.Instantiate(prefab, where, Quaternion.identity); GameObject spawned = Object.Instantiate(prefab, where, Quaternion.identity);
AlfarMiner miner = spawned.GetComponent<AlfarMiner>(); AlfarMiner miner = spawned.GetComponent<AlfarMiner>();
if (miner != null) if (miner != null) miner.Assign(point, AlfarPowerConfig.GrafRadius.Value, AlfarPowerConfig.GrafSeconds.Value);
{
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. // Tame at once so nothing flees them and they flee nothing; no anchor, no leash.
MonsterAI ai = spawned.GetComponent<MonsterAI>(); MonsterAI ai = spawned.GetComponent<MonsterAI>();

View file

@ -46,7 +46,9 @@ namespace RacesOfValheim
Object.DestroyImmediate(behaviour); Object.DestroyImmediate(behaviour);
} }
AlfarConstructs.Tint(prefab, new Color(0.62f, 0.8f, 1f, 1f)); // The floating pyramid; the blue table stays as the fallback if it cannot be built.
bool pyramid = AlfarNexusLook.Build(prefab);
if (!pyramid) AlfarConstructs.Tint(prefab, new Color(0.62f, 0.8f, 1f, 1f));
AlfarNexusBehaviour nexus = prefab.AddComponent<AlfarNexusBehaviour>(); AlfarNexusBehaviour nexus = prefab.AddComponent<AlfarNexusBehaviour>();
nexus.m_switch = prefab.AddComponent<Switch>(); nexus.m_switch = prefab.AddComponent<Switch>();
@ -71,7 +73,7 @@ namespace RacesOfValheim
trader.m_randomUseItemAlreadyRecieved = new List<string>(); trader.m_randomUseItemAlreadyRecieved = new List<string>();
trader.m_randomTalkConditionals = new List<Trader.ConditionalDialog>(); trader.m_randomTalkConditionals = new List<Trader.ConditionalDialog>();
Sprite icon = BorrowIcon("Eitr") ?? BorrowIcon("SurtlingCore"); Sprite icon = (pyramid ? AlfarChests.IconFrom("AlfarNexus_icon.png") : null) ?? BorrowIcon("Eitr") ?? BorrowIcon("SurtlingCore");
Piece piece = prefab.GetComponent<Piece>() ?? prefab.AddComponent<Piece>(); Piece piece = prefab.GetComponent<Piece>() ?? prefab.AddComponent<Piece>();
piece.m_craftingStation = null; piece.m_craftingStation = null;

View file

@ -89,8 +89,13 @@ namespace RacesOfValheim
DroneZapDamage = config.Bind(drone, "Zap Damage", 1f, new ConfigDescription("Lightning damage of a drone's defensive zap.", new AcceptableValueRange<float>(0f, 100f))); DroneZapDamage = config.Bind(drone, "Zap Damage", 1f, new ConfigDescription("Lightning damage of a drone's defensive zap.", new AcceptableValueRange<float>(0f, 100f)));
DroneZapInterval = config.Bind(drone, "Zap Interval", 2f, new ConfigDescription("Seconds between a drone's zaps.", new AcceptableValueRange<float>(0.2f, 30f))); DroneZapInterval = config.Bind(drone, "Zap Interval", 2f, new ConfigDescription("Seconds between a drone's zaps.", new AcceptableValueRange<float>(0.2f, 30f)));
MinerDeposits = config.Bind(drone, "Mining Targets", "MineRock_Copper,MineRock_Tin,MineRock_Iron,silvervein,rock3_silver,giant_brain", // Copper deposits are rock4_copper (and rock4_copper_frac once hit), crypt scrap is mudpile;
// the first default missed both, so a config still holding it is moved to the new one.
const string oldTargets = "MineRock_Copper,MineRock_Tin,MineRock_Iron,silvervein,rock3_silver,giant_brain";
const string targets = "rock4_copper,MineRock_Copper,MineRock_Tin,MineRock_Iron,mudpile,silvervein,rock3_silver,giant_brain";
MinerDeposits = config.Bind(drone, "Mining Targets", targets,
new ConfigDescription("Comma separated parts of prefab names the mining drones dig (case does not matter). Soft tissue comes from giant_brain.")); new ConfigDescription("Comma separated parts of prefab names the mining drones dig (case does not matter). Soft tissue comes from giant_brain."));
if (MinerDeposits.Value == oldTargets) MinerDeposits.Value = targets;
MinerDamage = config.Bind(drone, "Mining Damage", 40f, new ConfigDescription("Pickaxe damage each mining drone does per second to a deposit.", new AcceptableValueRange<float>(1f, 1000f))); MinerDamage = config.Bind(drone, "Mining Damage", 40f, new ConfigDescription("Pickaxe damage each mining drone does per second to a deposit.", new AcceptableValueRange<float>(1f, 1000f)));
WildPickables = config.Bind(drone, "Wild Plants Harvested", "Pickable_Mushroom,Pickable_Dandelion,Pickable_Thistle,RaspberryBush,BlueberryBush,CloudberryBush", WildPickables = config.Bind(drone, "Wild Plants Harvested", "Pickable_Mushroom,Pickable_Dandelion,Pickable_Thistle,RaspberryBush,BlueberryBush,CloudberryBush",

View file

@ -0,0 +1,217 @@
using Jotunn.Managers;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// The Ljoskjarne's body: a stone pyramid, 2 m to a side and 2 m tall, floating 0.8 m above the
/// ground. Dark steel carved with Valheim's own runes (the Ashlands rune tile's glyphs, laid out by
/// scripts/paint_nexus.py), and a cyan seam down the middle of each face.
///
/// The seam is painted into the faces' glow map, not built. Bars standing on the faces, lit or
/// unlit, lost part of their length to the face on whichever side looked one way in the world,
/// as the pyramid turned; a line in the face's own pixels has nothing to hide behind.
///
/// Only the look moves. The piece keeps one still collider from the ground up, so building on it,
/// support, hovering and the E key behave as before; the pyramid bobs and turns on each client by
/// itself, nothing over the network. The seam breathes, and burns brighter while crystals wait.
/// </summary>
public static class AlfarNexusLook
{
private const float Height = 2f;
private const float HalfBase = 1f;
private const float Lift = 0.8f;
private const string SourceMaterialPrefab = "piece_cartographytable";
private const string EmbersSource = "fx_Torch_Carried";
private static readonly Color Seam = new Color(0.35f, 0.75f, 1f);
/// <summary>Strips the cartography table's body and puts the pyramid in its place. False leaves
/// the table, with a warning, so the Nexus is never invisible.</summary>
public static bool Build(GameObject prefab)
{
Texture2D face = PieceLook.LoadTexture("AlfarNexus_face.png");
Texture2D glow = PieceLook.LoadTexture("AlfarNexus_glow.png");
Texture2D bumps = PieceLook.LoadTexture("AlfarNexus_n.png", true);
Renderer tableRenderer = prefab.transform.Find("new/high")?.GetComponent<Renderer>();
if (face == null || glow == null || tableRenderer == null || tableRenderer.sharedMaterial == null)
{
Jotunn.Logger.LogWarning("[Alfar] Could not build the Ljoskjarne's pyramid; it keeps the cartography table's look.");
return false;
}
Material stone = new Material(tableRenderer.sharedMaterial) { name = "AlfarNexus_stone" };
stone.color = Color.white;
stone.SetTexture("_MainTex", face);
// Forged, not polished: the plate's own grain in the normal map, and a dull sheen.
stone.SetTexture("_BumpMap", bumps);
if (bumps != null) stone.EnableKeyword("_NORMALMAP");
else stone.DisableKeyword("_NORMALMAP");
if (stone.HasProperty("_MetallicGlossMap")) stone.SetTexture("_MetallicGlossMap", null);
if (stone.HasProperty("_Metallic")) stone.SetFloat("_Metallic", 0.6f);
if (stone.HasProperty("_Glossiness")) stone.SetFloat("_Glossiness", 0.3f);
// Custom/Piece samples its noise in world space unless told the object moves, as boats and
// carts do; on a turning pyramid the blotches would slide across the faces.
stone.EnableKeyword("_MOVEABLEOBJECT_ON");
if (stone.HasProperty("_MoveableObject")) stone.SetFloat("_MoveableObject", 1f);
stone.SetTexture("_EmissionMap", glow);
stone.EnableKeyword("_EMISSION");
stone.SetColor("_EmissionColor", Seam);
// The table goes whole: its meshes, its damage states, its fragments and its four colliders.
for (int i = prefab.transform.childCount - 1; i >= 0; i--)
Object.DestroyImmediate(prefab.transform.GetChild(i).gameObject);
WearNTear wear = prefab.GetComponent<WearNTear>();
if (wear != null)
{
wear.m_new = null;
wear.m_worn = null;
wear.m_broken = null;
wear.m_fragmentRoots = new GameObject[0];
}
// One still collider, from the ground to the tip, a little inside the faces.
GameObject solid = new GameObject("collider") { layer = prefab.layer };
solid.transform.SetParent(prefab.transform, false);
BoxCollider box = solid.AddComponent<BoxCollider>();
box.center = new Vector3(0f, (Lift + Height) / 2f, 0f);
box.size = new Vector3(HalfBase * 1.4f, Lift + Height, HalfBase * 1.4f);
Transform floating = new GameObject("float").transform;
floating.SetParent(prefab.transform, false);
floating.gameObject.layer = prefab.layer;
MeshRenderer pyramid = Part(floating, "pyramid", PyramidMesh(), stone).GetComponent<MeshRenderer>();
NexusLook look = prefab.AddComponent<NexusLook>();
look.Float = floating;
look.SeamRenderer = pyramid;
look.Motes = AddMotes(prefab.transform);
return true;
}
private static GameObject Part(Transform parent, string name, Mesh mesh, Material material)
{
GameObject part = new GameObject(name) { layer = parent.gameObject.layer };
part.transform.SetParent(parent, false);
part.AddComponent<MeshFilter>().sharedMesh = mesh;
part.AddComponent<MeshRenderer>().sharedMaterial = material;
return part;
}
private static Vector3 Apex => new Vector3(0f, Lift + Height, 0f);
private static Vector3[] BaseCorners => new[]
{
new Vector3(-HalfBase, Lift, -HalfBase), new Vector3(HalfBase, Lift, -HalfBase),
new Vector3(HalfBase, Lift, HalfBase), new Vector3(-HalfBase, Lift, HalfBase),
};
/// <summary>Four faces, each with its own three corners so the shading stays flat and every face
/// shows the whole carving (u along the base, v = 1 at the tip), and the underside.</summary>
private static Mesh PyramidMesh()
{
Vector3[] c = BaseCorners;
var vertices = new Vector3[16];
var uvs = new Vector2[16];
var triangles = new int[18];
for (int i = 0; i < 4; i++)
{
// Wound clockwise seen from outside, which is Unity's front face.
vertices[i * 3] = c[(i + 1) % 4];
vertices[i * 3 + 1] = c[i];
vertices[i * 3 + 2] = Apex;
uvs[i * 3] = new Vector2(1f, 0f);
uvs[i * 3 + 1] = new Vector2(0f, 0f);
uvs[i * 3 + 2] = new Vector2(0.5f, 1f);
triangles[i * 3] = i * 3;
triangles[i * 3 + 1] = i * 3 + 1;
triangles[i * 3 + 2] = i * 3 + 2;
}
for (int i = 0; i < 4; i++) { vertices[12 + i] = c[i]; uvs[12 + i] = new Vector2(0.1f, 0.02f); }
int[] under = { 12, 13, 14, 12, 14, 15 };
System.Array.Copy(under, 0, triangles, 12, 6);
Mesh mesh = new Mesh { name = "AlfarNexus_pyramid", vertices = vertices, uv = uvs, triangles = triangles };
mesh.RecalculateNormals();
mesh.RecalculateBounds();
return mesh;
}
/// <summary>A few cyan motes drifting up from the ground under it: the torch's embers, recoloured,
/// spread over the pyramid's shadow and slowed down.</summary>
private static ParticleSystem AddMotes(Transform root)
{
GameObject torch = PrefabManager.Cache.GetPrefab<GameObject>(EmbersSource);
Transform source = torch != null ? torch.transform.Find("Embers") : null;
if (source == null) return null;
GameObject motes = Object.Instantiate(source.gameObject, root, false);
motes.name = "motes";
motes.transform.localPosition = new Vector3(0f, 0.05f, 0f);
motes.transform.localRotation = Quaternion.identity;
PieceLook.Rehue(motes.transform, Seam * 2f);
ParticleSystem particles = motes.GetComponent<ParticleSystem>();
if (particles != null)
{
ParticleSystem.ShapeModule shape = particles.shape;
shape.enabled = true;
shape.shapeType = ParticleSystemShapeType.Circle;
shape.radius = HalfBase;
shape.rotation = new Vector3(-90f, 0f, 0f);
ParticleSystem.MainModule main = particles.main;
main.simulationSpeed = 0.5f;
}
return particles;
}
/// <summary>The motion and the seam's light, per client.</summary>
public class NexusLook : MonoBehaviour
{
public Transform Float;
public Renderer SeamRenderer;
public ParticleSystem Motes;
private const float BobHeight = 0.08f;
private const float BobSeconds = 4.5f;
private const float TurnSeconds = 40f;
private const float BreathSeconds = 3.5f;
private AlfarNexusBehaviour m_nexus;
private Material m_seam;
private float m_phase;
private float m_ready; // eases between 0 (no crystals) and 1, so the brightening is not a jump
private void Awake()
{
m_nexus = GetComponent<AlfarNexusBehaviour>();
if (SeamRenderer != null) m_seam = SeamRenderer.material; // this one's own copy, to animate
// Two Nexuses side by side must not bob in step.
m_phase = (Mathf.Abs(transform.position.x * 0.37f + transform.position.z * 0.71f)) % 10f;
}
private void Update()
{
float t = Time.time + m_phase;
if (Float != null)
{
Float.localPosition = new Vector3(0f, Mathf.Sin(t * 2f * Mathf.PI / BobSeconds) * BobHeight, 0f);
Float.localRotation = Quaternion.Euler(0f, t * 360f / TurnSeconds, 0f);
}
if (m_seam == null) return;
bool ready = m_nexus != null && m_nexus.Crystals > 0;
m_ready = Mathf.MoveTowards(m_ready, ready ? 1f : 0f, Time.deltaTime * 0.5f);
float breath = 0.75f + 0.25f * Mathf.Sin(t * 2f * Mathf.PI / BreathSeconds);
Color glow = Seam * breath * Mathf.Lerp(1f, 2.2f, m_ready);
m_seam.SetColor("_EmissionColor", glow);
}
private void OnDestroy()
{
if (m_seam != null) Destroy(m_seam);
}
}
}
}

View file

@ -38,6 +38,37 @@ namespace RacesOfValheim
} }
} }
/// <summary>
/// Hair and beard never attach to an Alfr. Every equipment change makes the game write the
/// profile's hair back (Humanoid.SetupVisEquipment), and ApplyHairless only clears it on its
/// 0.5s pass, so players saw the hair flash in for a moment. Zeroing the hash here, where
/// VisEquipment spawns the model, means it never appears. Covers remote players too, since
/// their visuals go through the same call.
/// </summary>
[HarmonyPatch(typeof(VisEquipment), "SetHairEquipped")]
public static class Alfar_SetHairEquipped_Patch
{
public static void Prefix(VisEquipment __instance, ref int hash)
{
if (hash != 0 && IsAlfarVis(__instance)) hash = 0;
}
}
[HarmonyPatch(typeof(VisEquipment), "SetBeardEquipped")]
public static class Alfar_SetBeardEquipped_Patch
{
public static void Prefix(VisEquipment __instance, ref int hash)
{
if (hash != 0 && IsAlfarVis(__instance)) hash = 0;
}
}
private static bool IsAlfarVis(VisEquipment vis)
{
Player player = vis.GetComponent<Player>();
return player != null && AlfarVisuals.IsAlfarPlayer(player);
}
/// <summary> /// <summary>
/// The character preview on the main menu is a Player too, with the saved race in its custom data /// The character preview on the main menu is a Player too, with the saved race in its custom data
/// and no ZNetView. Its Update may never run, so a small driver on it keeps the look: skin, hair, /// and no ZNetView. Its Update may never run, so a small driver on it keeps the look: skin, hair,

View file

@ -148,12 +148,17 @@ namespace RacesOfValheim
} }
/// <summary>A pulse of lightning on every hostile creature within a radius of the Alfr.</summary> /// <summary>A pulse of lightning on every hostile creature within a radius of the Alfr.</summary>
public static void Pulse(Player player, float radius, float damage) /// <returns>True if it struck at least one creature.</returns>
public static bool Pulse(Player player, float radius, float damage)
{ {
bool struck = false;
foreach (Character character in CharactersIn(player.transform.position, radius)) foreach (Character character in CharactersIn(player.transform.position, radius))
{ {
if (IsHostile(player, character)) Strike(player, character, damage, character.GetCenterPoint()); if (!IsHostile(player, character)) continue;
Strike(player, character, damage, character.GetCenterPoint());
struck = true;
} }
return struck;
} }
private static IEnumerable<Character> CharactersIn(Vector3 center, float radius) private static IEnumerable<Character> CharactersIn(Vector3 center, float radius)
@ -177,35 +182,64 @@ namespace RacesOfValheim
Vector3 direction = aim.forward; Vector3 direction = aim.forward;
float distance = AlfarPowerConfig.SkridDistance.Value; float distance = AlfarPowerConfig.SkridDistance.Value;
if (!Pay(player, AlfarPowerConfig.SkridCost.Value)) return;
// Stop short of whatever is in the way, so the blink never ends inside a wall. // Stop short of whatever is in the way, so the blink never ends inside a wall.
Vector3 destination = origin + direction * distance; Vector3 destination = origin + direction * distance;
RaycastHit[] hits = Physics.RaycastAll(origin, direction, distance, ~0, QueryTriggerInteraction.Ignore); if (NearestHit(player, origin, direction, distance, out RaycastHit wall))
float nearest = float.MaxValue;
foreach (RaycastHit hit in hits)
{ {
if (hit.collider.GetComponentInParent<Player>() == player) continue; destination = wall.point - direction * 0.6f;
if (hit.distance < nearest)
{
nearest = hit.distance;
destination = hit.point - direction * 0.6f;
}
} }
// Back down to the player's own height: the origin was at the chest. // Back down to the player's own height: the origin was at the chest. The floor is found
// with a short ray down from the landing point, never with GetSolidHeight: that one casts
// from 1000 m up, so under any roof (a crypt, a cave, a house) it returned the roof and
// put the Alfr on top of it. A flat 1 m drop also sank the feet under the floor when the
// blink was aimed at it.
const float FloorSearch = 3f;
if (NearestHit(player, destination, Vector3.down, FloorSearch, out RaycastHit floor))
{
destination.y = floor.point.y + 0.05f;
}
else if (player.InInterior())
{
// No floor under the landing point inside a dungeon: it would end in the void the
// dungeon floats in. Cancel before paying.
return;
}
else
{
destination.y -= 1.0f; destination.y -= 1.0f;
if (ZoneSystem.instance != null) if (ZoneSystem.instance != null)
{ {
float ground = ZoneSystem.instance.GetSolidHeight(destination); // Terrain only, so a roof overhead is never mistaken for the ground.
float ground = ZoneSystem.instance.GetGroundHeight(destination);
if (destination.y < ground) destination.y = ground + 0.1f; if (destination.y < ground) destination.y = ground + 0.1f;
} }
}
if (!Pay(player, AlfarPowerConfig.SkridCost.Value)) return;
Teleport(player, destination); Teleport(player, destination);
StartCooldown("skrid", AlfarPowerConfig.SkridCooldown.Value); StartCooldown("skrid", AlfarPowerConfig.SkridCooldown.Value);
AlfarFx.Spawn("fx_JotunWitch_LightningBolt_Explosion", origin); AlfarFx.Spawn("fx_JotunWitch_LightningBolt_Explosion", origin);
} }
/// <summary>The nearest solid hit along a ray, skipping the caster's own colliders.</summary>
private static bool NearestHit(Player player, Vector3 origin, Vector3 direction, float distance, out RaycastHit nearest)
{
nearest = default;
bool found = false;
foreach (RaycastHit hit in Physics.RaycastAll(origin, direction, distance, ~0, QueryTriggerInteraction.Ignore))
{
if (hit.collider.GetComponentInParent<Player>() == player) continue;
if (!found || hit.distance < nearest.distance)
{
nearest = hit;
found = true;
}
}
return found;
}
/// <summary> /// <summary>
/// Moves the body without the teleport fade: the rigidbody is repositioned and its velocity /// Moves the body without the teleport fade: the rigidbody is repositioned and its velocity
/// zeroed, and the fall tracker is reset so a blink up a cliff does not count as a fall. /// zeroed, and the fall tracker is reset so a blink up a cliff does not count as a fall.
@ -305,6 +339,34 @@ namespace RacesOfValheim
// ─── Geisli: the beam ──────────────────────────────────────────────── // ─── Geisli: the beam ────────────────────────────────────────────────
/// <summary>
/// The pad's way to hold the beam. Every pad button is taken in vanilla's Classic layout, so,
/// like Skadi's Cold Spell, the beam borrows the secondary attack: bare-handed, or in the
/// archon form, which has no weapons anyway. The radial entry only gives a single press,
/// which cannot hold a beam.
/// </summary>
private static bool PadBeamHeld(Player player) =>
!RaceInput.RadialOpen && RaceInput.PadAttackHeld(2) &&
(AlfarArchon.Active || RaceInput.EmptyHanded(player));
/// <summary>
/// Swallows the unarmed secondary (the kick) while the pad's secondary attack is the beam,
/// the same way SkadiAttackPatch does for the Cold Spell.
/// </summary>
[HarmonyPatch(typeof(Humanoid), "StartAttack")]
public static class Alfar_GeisliPadKick_Patch
{
public static bool Prefix(Humanoid __instance, bool secondaryAttack, ref bool __result)
{
if (!secondaryAttack || __instance != Player.m_localPlayer) return true;
Player player = (Player)__instance;
if (!AlfarVisuals.IsAlfarPlayer(player) || !Unlocked(AlfarPowerConfig.GeisliState)) return true;
if (!PadBeamHeld(player)) return true;
__result = false;
return false;
}
}
private static LineRenderer beamLine; private static LineRenderer beamLine;
private static readonly List<LineRenderer> beamArcs = new List<LineRenderer>(); private static readonly List<LineRenderer> beamArcs = new List<LineRenderer>();
private static GameObject beamFx; private static GameObject beamFx;
@ -324,7 +386,7 @@ namespace RacesOfValheim
private static void TickBeam(Player player) private static void TickBeam(Player player)
{ {
bool wanted = RaceInput.Allowed && !player.IsDead() && Unlocked(AlfarPowerConfig.GeisliState) && bool wanted = RaceInput.Allowed && !player.IsDead() && Unlocked(AlfarPowerConfig.GeisliState) &&
AlfarPowerConfig.GeisliKey.Value.IsPressedIgnoringHeldKeys(); (AlfarPowerConfig.GeisliKey.Value.IsPressedIgnoringHeldKeys() || PadBeamHeld(player));
if (!wanted) if (!wanted)
{ {
@ -368,7 +430,11 @@ namespace RacesOfValheim
AlfarEitr.Spend(player, cost); AlfarEitr.Spend(player, cost);
} }
if (IsHostile(player, target)) Strike(player, target, AlfarPowerConfig.BeamDps.Value * tick, end); if (IsHostile(player, target))
{
Strike(player, target, AlfarPowerConfig.BeamDps.Value * tick, end);
FormMelee.RaiseSkill(Skills.SkillType.ElementalMagic, tick); // a full hit per second on target
}
} }
private static void RaiseHand(Player player) private static void RaiseHand(Player player)
@ -520,14 +586,19 @@ namespace RacesOfValheim
const float tick = 0.5f; const float tick = 0.5f;
nextTick = Time.time + tick; nextTick = Time.time + tick;
bool struck = false;
foreach (Collider collider in Physics.OverlapSphere(transform.position, Radius, ~0, QueryTriggerInteraction.Ignore)) foreach (Collider collider in Physics.OverlapSphere(transform.position, Radius, ~0, QueryTriggerInteraction.Ignore))
{ {
Character character = collider.GetComponentInParent<Character>(); Character character = collider.GetComponentInParent<Character>();
if (character == null || character == Owner || character.IsDead() || character.IsTamed()) continue; if (character == null || character == Owner || character.IsDead() || character.IsTamed()) continue;
if (!BaseAI.IsEnemy(Owner, character)) continue; if (!BaseAI.IsEnemy(Owner, character)) continue;
AlfarPowers.Strike(Owner, character, DamagePerSecond * tick, character.GetCenterPoint()); AlfarPowers.Strike(Owner, character, DamagePerSecond * tick, character.GetCenterPoint());
struck = true;
} }
// Once per tick, not per creature: a full hit per second the storm strikes something.
if (struck && Owner == Player.m_localPlayer) FormMelee.RaiseSkill(Skills.SkillType.ElementalMagic, tick);
Vector2 offset = Random.insideUnitCircle * Radius; Vector2 offset = Random.insideUnitCircle * Radius;
AlfarFx.Spawn("fx_JotunWitch_LightningBolt_Explosion", transform.position + new Vector3(offset.x, 0f, offset.y)); AlfarFx.Spawn("fx_JotunWitch_LightningBolt_Explosion", transform.position + new Vector3(offset.x, 0f, offset.y));
} }

Binary file not shown.

After

Width:  |  Height:  |  Size: 53 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 216 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 259 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 65 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 100 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 72 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 19 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 340 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 441 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 339 KiB

View file

@ -6,11 +6,22 @@ namespace RacesOfValheim
/// <summary> /// <summary>
/// Whether a player is a bat, on any client. /// Whether a player is a bat, on any client.
/// ///
/// This file used to be AswidBatAggro: while the bat flew on vanilla's debug-fly flag, vanilla /// Stamina Flight flies on m_flying (DirectedFlight.cs), which vanilla's AI and damage never
/// read that flag as "this player is not really here" - no monster could see, hear or wake for /// look at, so monsters notice and hurt that bat with no help.
/// it, and every hit on it was dropped - and six patches here lied about the flag in exactly ///
/// those places. The bat now flies on m_flying (DirectedFlight.cs), which vanilla's AI and /// Free Flight flies on vanilla's debug-fly flag, and vanilla reads that flag as "this player
/// damage never look at, so monsters notice and hurt it with no help, and the lie went. /// is not really here". Six places, read out of assembly_valheim:
///
/// BaseAI.CanHearTarget, BaseAI.CanSeeTarget and BaseAI's HuntPlayer fallback ask
/// Player.InDebugFlyMode() and drop the player.
/// MonsterAI.UpdateSleep asks IsDebugFlying() and will not wake, twice over.
/// Character.ApplyDamage and Character.RPC_Damage ask IsDebugFlying() and drop the hit.
///
/// The patches below keep the flag (it IS the flight) and lie about it in exactly those
/// places, for bats only. InDebugFlyMode() is forced false flat: those three AI paths are its
/// only callers. IsDebugFlying() cannot be: Character.UpdateMotion reads it to hold the bat in
/// the air, so it reads false only while the call stack is inside one of the methods that push
/// the counter. The patches were removed with the old flight in v1.6.1 and came back with it.
/// </summary> /// </summary>
public static class AswidBatForm public static class AswidBatForm
{ {
@ -22,6 +33,14 @@ namespace RacesOfValheim
private static readonly int BatFormHash = "SE_BatForm".GetStableHashCode(); private static readonly int BatFormHash = "SE_BatForm".GetStableHashCode();
// How deep we are inside vanilla calls that must not see the debug-fly flag. A counter,
// not a bool: ApplyDamage runs inside RPC_Damage, so the frames nest.
private static int unmaskDepth;
public static bool Unmasked => unmaskDepth > 0;
public static void PushUnmask() { unmaskDepth++; }
public static void PopUnmask() { if (unmaskDepth > 0) unmaskDepth--; }
/// <summary> /// <summary>
/// The ZDO first and the status effect only as a fallback: the ZDO is the one that is true /// The ZDO first and the status effect only as a fallback: the ZDO is the one that is true
/// on every client, and the status effect covers the local player during the frames of the /// on every client, and the status effect covers the local player during the frames of the
@ -40,6 +59,98 @@ namespace RacesOfValheim
} }
} }
/// <summary>Free Flight: monsters see and hear a bat. See AswidBatForm for why this one is safe flat.</summary>
[HarmonyPatch(typeof(Player), "InDebugFlyMode")]
public static class Aswid_BatIsVisibleToAI_Patch
{
public static void Postfix(Player __instance, ref bool __result)
{
if (__result && AswidBatForm.IsBat(__instance)) __result = false;
}
}
/// <summary>
/// The scoped half: false only inside the methods that push the counter, so flight, motion,
/// the camera and UpdateStats still read the flag as true.
/// </summary>
[HarmonyPatch(typeof(Player), "IsDebugFlying")]
public static class Aswid_BatIsDebugFlying_Patch
{
public static void Postfix(Player __instance, ref bool __result)
{
if (!__result || !AswidBatForm.Unmasked) return;
if (AswidBatForm.IsBat(__instance)) __result = false;
}
}
/// <summary>
/// A hit landing on a free-flying bat. Finalizer rather than Postfix: the counter has to come
/// down even when the method throws, and a void Finalizer leaves the exception alone.
/// </summary>
[HarmonyPatch(typeof(Character), "ApplyDamage")]
public static class Aswid_BatTakesDamage_Patch
{
public static void Prefix(Character __instance, ref bool __state)
{
__state = __instance is Player player && AswidBatForm.IsBat(player);
if (__state) AswidBatForm.PushUnmask();
}
public static void Finalizer(bool __state)
{
if (__state) AswidBatForm.PopUnmask();
}
}
/// <summary>The networked half of the same thing: a hit sent by another machine.</summary>
[HarmonyPatch(typeof(Character), "RPC_Damage")]
public static class Aswid_BatTakesRemoteDamage_Patch
{
public static void Prefix(Character __instance, ref bool __state)
{
__state = __instance is Player player && AswidBatForm.IsBat(player);
if (__state) AswidBatForm.PushUnmask();
}
public static void Finalizer(bool __state)
{
if (__state) AswidBatForm.PopUnmask();
}
}
/// <summary>
/// Notes when the local player last lost health, for the bat's combat lock. ApplyDamage is the
/// one final stage for direct hits, burning, poison and bleeding, so comparing health around it
/// catches them all, and a hit fully blocked or absorbed (Alfar shield, Heimkall) is no hurt.
/// </summary>
[HarmonyPatch(typeof(Character), "ApplyDamage",
new[] { typeof(HitData), typeof(bool), typeof(bool), typeof(HitData.DamageModifier) })]
public static class Aswid_BatCombatLock_Patch
{
public static void Prefix(Character __instance, ref float __state)
{
__state = __instance == Player.m_localPlayer ? __instance.GetHealth() : -1f;
}
public static void Postfix(Character __instance, float __state)
{
if (__state < 0f) return;
if (__instance.GetHealth() < __state) AswidRace.LastHurtTime = Time.time;
}
}
/// <summary>
/// Sleepers. UpdateSleep picks the closest player itself, possibly a remote bat, so the counter
/// goes up for the whole call and the bat test happens in the IsDebugFlying postfix, which only
/// runs its test for a player already debug flying.
/// </summary>
[HarmonyPatch(typeof(MonsterAI), "UpdateSleep")]
public static class Aswid_BatWakesSleepers_Patch
{
public static void Prefix() { AswidBatForm.PushUnmask(); }
public static void Finalizer() { AswidBatForm.PopUnmask(); }
}
/// <summary> /// <summary>
/// The revert path cannot handle a bat that dies: AswidRace.Update() returns early on IsDead(), /// The revert path cannot handle a bat that dies: AswidRace.Update() returns early on IsDead(),
/// so the coroutine that takes the form down never starts. The flight flag would stay on and /// so the coroutine that takes the form down never starts. The flight flag would stay on and

View file

@ -338,8 +338,6 @@ namespace RacesOfValheim
// The raw -> cooked table the Draugh already maintains is the source of truth. // The raw -> cooked table the Draugh already maintains is the source of truth.
meatToCooked = new Dictionary<string, string>(DraughFoodPatches.rawToCookedMapping); meatToCooked = new Dictionary<string, string>(DraughFoodPatches.rawToCookedMapping);
meatToCooked.Remove("GreydwarfEye"); // stew ingredient, not flesh meatToCooked.Remove("GreydwarfEye"); // stew ingredient, not flesh
meatToCooked["AsksvinMeat"] = "CookedAsksvinMeat";
meatToCooked["BoneMawSerpentMeat"] = "CookedBoneMawSerpentMeat";
foreach (string stationName in CookingStationPrefabs) foreach (string stationName in CookingStationPrefabs)
{ {

View file

@ -74,8 +74,24 @@ namespace RacesOfValheim
// The bat flies on the same directed flight as the Skadi's drakes (DirectedFlight.cs), // The bat flies on the same directed flight as the Skadi's drakes (DirectedFlight.cs),
// with its own numbers. It used to fly on vanilla's debug-fly flag: 50 m/s, free, blind // with its own numbers. It used to fly on vanilla's debug-fly flag: 50 m/s, free, blind
// to carry weight, and ignored by every monster until AswidBatAggro lied to six vanilla // to carry weight, and ignored by every monster until AswidBatAggro lied to six vanilla
// methods about it. None of that is left. // methods about it. The old flight came back as Free Flight, for players who want it
// (building tall); AswidBatForm holds the aggro patches it needs.
public enum EncumberedMode { Allowed, Blocked } public enum EncumberedMode { Allowed, Blocked }
public enum BatFlightRuleMode { PlayerChoice, AlwaysStaminaFlight, AlwaysFreeFlight }
public static ConfigEntry<bool> FreeBatFlight;
public static ConfigEntry<BatFlightRuleMode> BatFlightRule;
/// <summary>Which flight a bat taken now gets: the server's rule first, then the player's own pick.</summary>
public static bool UsesFreeBatFlight()
{
switch (BatFlightRule.Value)
{
case BatFlightRuleMode.AlwaysStaminaFlight: return false;
case BatFlightRuleMode.AlwaysFreeFlight: return true;
default: return FreeBatFlight.Value;
}
}
public static ConfigEntry<float> BatTurnSpeed; public static ConfigEntry<float> BatTurnSpeed;
public static ConfigEntry<float> BatGlideSpeed; public static ConfigEntry<float> BatGlideSpeed;
@ -91,6 +107,7 @@ namespace RacesOfValheim
public static ConfigEntry<float> BatMaxDuration; public static ConfigEntry<float> BatMaxDuration;
public static ConfigEntry<float> BatDurationPerState; public static ConfigEntry<float> BatDurationPerState;
public static ConfigEntry<float> BatCooldown; public static ConfigEntry<float> BatCooldown;
public static ConfigEntry<float> BatCombatLock;
// ─── Vampiric Aura (passive, always active) ────────────────────────────── // ─── Vampiric Aura (passive, always active) ──────────────────────────────
public static ConfigEntry<float> AuraTickInterval; public static ConfigEntry<float> AuraTickInterval;
@ -240,6 +257,10 @@ namespace RacesOfValheim
new ConfigDescription("How far the camera rolls. 1 is about 4 degrees. Local.", new AcceptableValueRange<float>(0f, 3f))); new ConfigDescription("How far the camera rolls. 1 is about 4 degrees. Local.", new AcceptableValueRange<float>(0f, 3f)));
const string batform = "Aswid - Bat Form"; const string batform = "Aswid - Bat Form";
FreeBatFlight = config.Bind(batform, "Free Bat Flight", false,
new ConfigDescription("Off: Stamina Flight, the settings below. On: the old Free Flight, up to 50 m/s with no stamina cost and no weight limit; Jump rises, Left Ctrl sinks. Your own choice, unless the server's Bat Flight Rule forces one. Takes effect the next time you become a bat."));
BatFlightRule = config.Bind(batform, "Bat Flight Rule", BatFlightRuleMode.PlayerChoice,
new ConfigDescription("Server rule. PlayerChoice: each player's Free Bat Flight setting decides. AlwaysStaminaFlight / AlwaysFreeFlight: every bat flies that way. On a server only the host's or the server's value counts."));
// Same controls as the Skadi's drake: aim with the camera, W beats forward, Shift // Same controls as the Skadi's drake: aim with the camera, W beats forward, Shift
// sprints, S beats backwards, and letting go hovers briefly before gliding down. // sprints, S beats backwards, and letting go hovers briefly before gliding down.
BatTurnSpeed = config.Bind(batform, "Turn Speed", 180f, BatTurnSpeed = config.Bind(batform, "Turn Speed", 180f,
@ -272,6 +293,8 @@ namespace RacesOfValheim
new ConfigDescription("Seconds added to the max duration per progression state. Does nothing while the max duration is 0.", new AcceptableValueRange<float>(0f, 600f))); new ConfigDescription("Seconds added to the max duration per progression state. Does nothing while the max duration is 0.", new AcceptableValueRange<float>(0f, 600f)));
BatCooldown = config.Bind(batform, "Cooldown", 0f, BatCooldown = config.Bind(batform, "Cooldown", 0f,
new ConfigDescription("Seconds after leaving bat form before you can take it again. 0 means none.", new AcceptableValueRange<float>(0f, 3600f))); new ConfigDescription("Seconds after leaving bat form before you can take it again. 0 means none.", new AcceptableValueRange<float>(0f, 3600f)));
BatCombatLock = config.Bind(batform, "Combat Lock", 2.5f,
new ConfigDescription("Seconds after you last lost health (a hit, or a tick of fire, poison or bleeding) before you can take bat form. Turning back from bat form is never blocked. 0 means none.", new AcceptableValueRange<float>(0f, 30f)));
const string aura = "Aswid - Vampiric Aura"; const string aura = "Aswid - Vampiric Aura";
AuraTickInterval = config.Bind(aura, "Tick Interval", 0.25f, AuraTickInterval = config.Bind(aura, "Tick Interval", 0.25f,

View file

@ -931,6 +931,30 @@ namespace RacesOfValheim
} }
} }
/// <summary>
/// Pukeberries empty the fourth stomach too.
///
/// SE_Puke calls RemoveOneFood once a second, and vanilla only ever picks from its own three
/// slots, so the Aswid's fourth meal survived the berries. It now goes into the same random
/// draw as the other three, the way the Trol's extra slots do.
/// </summary>
[HarmonyPatch(typeof(Player), "RemoveOneFood")]
public static class Aswid_PlayerRemoveOneFood_Patch
{
public static bool Prefix(Player __instance, System.Collections.Generic.List<Player.Food> ___m_foods, ref bool __result)
{
if (__instance != Player.m_localPlayer || !AswidRace.IsAswid()) return true;
if (!AswidFoodManager.ExtraFoods.TryGetValue(__instance, out Player.Food extraFood) || extraFood == null) return true;
int vanillaCount = ___m_foods != null ? ___m_foods.Count : 0;
if (Random.Range(0, vanillaCount + 1) < vanillaCount) return true; // one of vanilla's three
AswidFoodManager.ClearFood(__instance);
__result = true;
return false;
}
}
[HarmonyPatch(typeof(Player), "ClearFood")] [HarmonyPatch(typeof(Player), "ClearFood")]
public static class Aswid_Player_ClearFood_Patch public static class Aswid_Player_ClearFood_Patch
{ {

View file

@ -329,9 +329,6 @@ namespace RacesOfValheim
} }
private float m_tintCheckTimer = 0f; private float m_tintCheckTimer = 0f;
private float sensesCheckTimer = 0f;
private Dictionary<Character, GameObject> activeSensesLight = new Dictionary<Character, GameObject>();
public static float GetEnslaveCooldown() public static float GetEnslaveCooldown()
{ {
@ -373,6 +370,7 @@ namespace RacesOfValheim
{ {
seman.RemoveStatusEffect(myHash); seman.RemoveStatusEffect(myHash);
} }
HunterSenses.Clear();
return; return;
} }
@ -381,64 +379,8 @@ namespace RacesOfValheim
seman.AddStatusEffect(myHash, true); seman.AddStatusEffect(myHash, true);
} }
sensesCheckTimer -= Time.deltaTime;
if (sensesCheckTimer <= 0f)
{
sensesCheckTimer = AswidConfig.SensesRefreshInterval.Value; // TTL is 2s
List<Character> allChars = Character.GetAllCharacters();
Vector3 myPos = Player.m_localPlayer.transform.position;
int markHash = "SE_AswidSensesMark".GetStableHashCode(); int markHash = "SE_AswidSensesMark".GetStableHashCode();
HashSet<Character> inRangeChars = new HashSet<Character>(); HunterSenses.Tick(AswidConfig.SensesRadius.Value, c => c.GetSEMan().AddStatusEffect(markHash, true));
foreach (var c in allChars)
{
if (c == null || c == Player.m_localPlayer || c.IsDead() || c.IsTamed()) continue;
float dist = Vector3.Distance(c.transform.position, myPos);
if (dist <= AswidConfig.SensesRadius.Value)
{
try
{
inRangeChars.Add(c);
c.GetSEMan().AddStatusEffect(markHash, true); // Keep the malus as requested
// Locally generate the visual
if (!activeSensesLight.ContainsKey(c))
{
GameObject lightObj = new GameObject("AswidSensesLight");
lightObj.transform.SetParent(c.transform);
lightObj.transform.position = c.GetCenterPoint();
Light pLight = lightObj.AddComponent<Light>();
pLight.type = LightType.Point;
pLight.color = Color.green;
pLight.range = AswidConfig.SensesLightRange.Value;
pLight.intensity = AswidConfig.SensesLightIntensity.Value;
pLight.shadows = LightShadows.None;
activeSensesLight[c] = lightObj;
}
}
catch (Exception ex)
{
Jotunn.Logger.LogError($"[Aswid] Error processing mob {c.name}: {ex}");
}
}
}
List<Character> keysToRemove = new List<Character>();
foreach (var kvp in activeSensesLight)
{
if (kvp.Key == null || kvp.Key.IsDead() || !inRangeChars.Contains(kvp.Key))
{
if (kvp.Value != null) Destroy(kvp.Value);
keysToRemove.Add(kvp.Key);
}
}
foreach (var k in keysToRemove) activeSensesLight.Remove(k);
}
} }
catch (Exception ex) catch (Exception ex)
{ {
@ -446,15 +388,6 @@ namespace RacesOfValheim
} }
} }
private void ClearSuperhumanSenses()
{
foreach (var kvp in activeSensesLight)
{
if (kvp.Value != null) Destroy(kvp.Value);
}
activeSensesLight.Clear();
}
private bool? wasNight = null; private bool? wasNight = null;
private void Update() private void Update()
@ -682,6 +615,14 @@ namespace RacesOfValheim
return; return;
} }
// No escaping a fight by taking wing mid-blow: the form waits until the hits stop.
float hurtLeft = AswidConfig.BatCombatLock.Value - (Time.time - LastHurtTime);
if (hurtLeft > 0f)
{
Player.m_localPlayer.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_aswid_bat_combat_lock", Mathf.CeilToInt(hurtLeft)));
return;
}
float cooldownLeft = AswidConfig.BatCooldown.Value - (Time.time - lastBatEndTime); float cooldownLeft = AswidConfig.BatCooldown.Value - (Time.time - lastBatEndTime);
if (cooldownLeft > 0f) if (cooldownLeft > 0f)
{ {
@ -696,6 +637,10 @@ namespace RacesOfValheim
// fresh session never begins on cooldown. // fresh session never begins on cooldown.
private float lastBatEndTime = -100000f; private float lastBatEndTime = -100000f;
// When the local player last lost health, for the bat's combat lock. Written by
// Aswid_BatCombatLock_Patch for every race; only the Aswid reads it.
public static float LastHurtTime = -100000f;
// The one bat or mist routine in flight, if any. Kept so ResetRace can stop it: a // 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 // TransformIntoBatRoutine left running through a reset finishes its 1.1s gesture and
// turns a freshly reset Human into a bat. // turns a freshly reset Human into a bat.
@ -1246,6 +1191,7 @@ namespace RacesOfValheim
int layerMask = LayerMask.GetMask("character", "character_net", "character_ghost"); int layerMask = LayerMask.GetMask("character", "character_net", "character_ghost");
var colliders = Physics.OverlapSphere(center, radius, layerMask); var colliders = Physics.OverlapSphere(center, radius, layerMask);
bool hitCreature = false;
foreach (var col in colliders) foreach (var col in colliders)
{ {
@ -1296,10 +1242,16 @@ namespace RacesOfValheim
// kill). ApplyDamage() skipped all of that: it edited the local copy of a // kill). ApplyDamage() skipped all of that: it edited the local copy of a
// character we usually do not own, and the owner overwrote it on the next sync. // character we usually do not own, and the owner overwrote it on the next sync.
c.Damage(hd); c.Damage(hd);
hitCreature = true;
SpawnBloodVFX(c); SpawnBloodVFX(c);
} }
} }
// The aura scales with Blood Magic but called Damage directly, so it never paid
// the skill back. Passive and always on, so it earns what the Skadi's Frost Aura
// does: a tenth of a hit per second of draining, once per tick, not per victim.
if (hitCreature) FormMelee.RaiseSkill(Skills.SkillType.BloodMagic, 0.1f * AswidConfig.AuraTickInterval.Value);
} }
catch (Exception ex) catch (Exception ex)
{ {

View file

@ -14,17 +14,25 @@ namespace RacesOfValheim
/// ///
/// Other clients learn the bat is airborne from Aswid_IsBatForm in the ZDO, which /// Other clients learn the bat is airborne from Aswid_IsBatForm in the ZDO, which
/// Aswid_MultiplayerVisuals_Patch mirrors into their copy's m_flying. /// Aswid_MultiplayerVisuals_Patch mirrors into their copy's m_flying.
///
/// FREE FLIGHT. A player who picks it (or a server that forces it, AswidConfig.UsesFreeBatFlight)
/// gets the old flight back: vanilla's debug fly, both halves (the field for the local physics,
/// s_debugFly in the ZDO for everyone else), and no DirectedFlight. The mode is read once, when
/// the form goes up. AswidBatForm keeps monsters seeing and hurting a free-flying bat.
/// </summary> /// </summary>
public class BatFormBehavior : MonoBehaviour, IDirectedFlyer public class BatFormBehavior : MonoBehaviour, IDirectedFlyer
{ {
private static readonly System.Reflection.FieldInfo FlyingField = private static readonly System.Reflection.FieldInfo FlyingField =
AccessTools.Field(typeof(Character), "m_flying"); AccessTools.Field(typeof(Character), "m_flying");
private static readonly System.Reflection.FieldInfo DebugFlyField =
AccessTools.Field(typeof(Player), "m_debugFly");
private Animator anim; private Animator anim;
private AswidProgression.FormRules formRules; private AswidProgression.FormRules formRules;
private float startTime; private float startTime;
private bool warnedTooHeavy; private bool warnedTooHeavy;
private bool expired; private bool expired;
private bool free;
public void Initialize(AswidProgression.FormRules rules) public void Initialize(AswidProgression.FormRules rules)
{ {
@ -73,8 +81,9 @@ namespace RacesOfValheim
anim = GetComponentInChildren<Animator>(); anim = GetComponentInChildren<Animator>();
startTime = Time.time; startTime = Time.time;
LastPoweredTime = Time.time; LastPoweredTime = Time.time;
DirectedFlight.Register(this); free = AswidConfig.UsesFreeBatFlight();
SetFlying(true); if (!free) DirectedFlight.Register(this);
Hold();
} }
private void Update() private void Update()
@ -85,8 +94,11 @@ namespace RacesOfValheim
// Held every frame rather than set once, for the same reason the debug-fly flag was: // Held every frame rather than set once, for the same reason the debug-fly flag was:
// anything that clears it mid-form (a vanilla reset, another mod) would drop the bat // anything that clears it mid-form (a vanilla reset, another mod) would drop the bat
// into walking with the model still on. // into walking with the model still on.
SetFlying(true); Hold();
// Free Flight ignores weight, so only Stamina Flight warns about it.
if (!free)
{
if (!CanPower && !warnedTooHeavy) if (!CanPower && !warnedTooHeavy)
{ {
warnedTooHeavy = true; warnedTooHeavy = true;
@ -96,6 +108,7 @@ namespace RacesOfValheim
{ {
warnedTooHeavy = false; warnedTooHeavy = false;
} }
}
float max = MaxDuration(); float max = MaxDuration();
if (max > 0f && !expired && Time.time - startTime >= max && AswidRace.Instance != null) if (max > 0f && !expired && Time.time - startTime >= max && AswidRace.Instance != null)
@ -120,15 +133,37 @@ namespace RacesOfValheim
SetFlying(false); SetFlying(false);
} }
private void Hold()
{
if (free) SetDebugFly(true);
else SetFlying(true);
}
/// <summary> /// <summary>
/// The local half of flight. The remote half is the Aswid_IsBatForm ZDO flag AswidRace /// The local half of Stamina Flight. The remote half is the Aswid_IsBatForm ZDO flag
/// already writes, so there is nothing to replicate here. /// AswidRace already writes, so there is nothing to replicate here. Turning it off also
/// turns debug fly off, so every exit path ends both flights whichever one was up.
/// </summary> /// </summary>
public static void SetFlying(bool flying) public static void SetFlying(bool flying)
{ {
Player player = Player.m_localPlayer; Player player = Player.m_localPlayer;
if (player == null || FlyingField == null) return; if (player == null) return;
FlyingField.SetValue(player, flying); if (FlyingField != null) FlyingField.SetValue(player, flying);
if (!flying) SetDebugFly(false);
}
/// <summary>
/// Both halves of debug fly, for Free Flight. The ZDO write every frame is not network
/// spam: ZDO.Set returns early when the value is unchanged.
/// </summary>
private static void SetDebugFly(bool flying)
{
Player player = Player.m_localPlayer;
if (player == null) return;
if (DebugFlyField != null) DebugFlyField.SetValue(player, flying);
ZNetView nview = player.GetComponent<ZNetView>();
if (nview != null && nview.IsValid() && nview.IsOwner()) nview.GetZDO().Set(ZDOVars.s_debugFly, flying);
} }
} }
} }

Binary file not shown.

Binary file not shown.

View file

@ -218,6 +218,7 @@ namespace RacesOfValheim
} }
prefab.transform.localScale = Vector3.one * TableScale; prefab.transform.localScale = Vector3.one * TableScale;
Dress(prefab, family);
ServantTableBehaviour table = prefab.AddComponent<ServantTableBehaviour>(); ServantTableBehaviour table = prefab.AddComponent<ServantTableBehaviour>();
table.m_switch = prefab.AddComponent<Switch>(); table.m_switch = prefab.AddComponent<Switch>();
@ -255,6 +256,65 @@ namespace RacesOfValheim
})); }));
} }
// The look, in the table's own space BEFORE TableScale, so sizes are divided by it to come out
// in real metres. The cover lies where the map was: x -2.06 to 0.62, read off the mesh. Its top
// is the Dvergar bank's PileHeight, on the same vanilla mesh; the mesh's own height is no use
// here, since the writing desk stands taller than the map.
private const float CoverTop = 1.05f;
private static readonly Vector3 TradeSpot = new Vector3(-0.75f, CoverTop, 0.2f);
private static readonly Vector3 SkullSpot = new Vector3(-1.55f, CoverTop, 0.35f);
private const float AnvilSize = 0.75f;
private const float MealSize = 0.6f;
private const float SkullSize = 0.45f;
/// <summary>
/// The map painted over - a sheet of chainmail for the smith, a red and white tablecloth for the
/// cook - with the trade's own work on it (an anvil, a meal) and a skeleton's skull beside it.
/// </summary>
private static void Dress(GameObject prefab, ButlerFamily family)
{
bool forge = family == ButlerFamily.Forge;
LayCover(prefab, forge ? "SmithMail" : "CookCloth", metal: forge);
float metres = 1f / TableScale;
if (forge)
{
ModelBorrow.Attach(prefab.transform, "TableAnvil", "forge_ext2",
TradeSpot, Quaternion.identity, AnvilSize * metres, "Butler", activeOnly: true);
}
else
{
ModelBorrow.Attach(prefab.transform, "TableMeal", "MeatPlatter",
TradeSpot, Quaternion.identity, MealSize * metres, "Butler", activeOnly: true);
}
ModelBorrow.Attach(prefab.transform, "TableSkull", "TrophySkeleton",
SkullSpot, Quaternion.Euler(0f, -150f, 0f), SkullSize * metres, "Butler", activeOnly: true);
}
/// <summary>
/// The cartography table's own textures with the map painted over, offline:
/// scripts/paint_cook_cloth.py (CookCloth) and scripts/paint_smith_mail.py (SmithMail). Each set
/// has its own worn texture for a damaged table (a stained cloth, rusted mail) and its own normal
/// map, so the coastline's relief does not show through. The mail also brings a metallic map,
/// which is what makes the rings shine; the cloth keeps vanilla's, which is metal nowhere.
/// </summary>
private static void LayCover(GameObject prefab, string set, bool metal)
{
var cover = new System.Collections.Generic.Dictionary<string, Texture>();
AddCover(cover, "Cartographer_d", set + "_d.png", false);
AddCover(cover, "Cartographer_worn_d", set + "_worn_d.png", false);
AddCover(cover, "Cartographer_n", set + "_n.png", true);
if (metal) AddCover(cover, "Cartographer_m", set + "_m.png", true);
PieceLook.Retexture(prefab.transform, cover);
}
private static void AddCover(System.Collections.Generic.Dictionary<string, Texture> cover,
string vanilla, string resource, bool linear)
{
Texture2D texture = PieceLook.LoadTexture(resource, linear);
if (texture != null) cover[vanilla] = texture;
}
public static void EnsureKnown(Player player) public static void EnsureKnown(Player player)
{ {
if (player == null) return; if (player == null) return;

View file

@ -270,7 +270,11 @@ namespace RacesOfValheim
else if (Time.time >= m_nextFightScan) else if (Time.time >= m_nextFightScan)
{ {
m_nextFightScan = Time.time + FightScanInterval; m_nextFightScan = Time.time + FightScanInterval;
if (BaseAI.FindClosestEnemy(m_character, transform.position, FightRange) != null) // FindClosestEnemy takes its first match at ANY distance (it only compares against
// maxDistance once it holds one), so with a deer anywhere in the loaded zones it never
// returned null and vanilla kept the tick: the worker idled about instead of working.
Character enemy = BaseAI.FindClosestEnemy(m_character, transform.position, FightRange);
if (enemy != null && Vector3.Distance(enemy.transform.position, transform.position) <= FightRange)
{ {
m_fightUntil = Time.time + FightLinger; m_fightUntil = Time.time + FightLinger;
} }
@ -359,8 +363,22 @@ namespace RacesOfValheim
Scan(anchor.Value); Scan(anchor.Value);
ExpirePenalties(); ExpirePenalties();
if (m_payload.Count > 0) { m_job = PlanDelivery(anchor.Value); return; } // A delivery gets its own clock like any other job. Returning early here left it with the
// load's deadline: a slow trip, or a fight on the way, made it late before it started, and
// it timed out and was planned again on every tick, frozen with the goods in hand.
Job job;
if (m_payload.Count > 0) job = PlanDelivery(anchor.Value);
else job = PlanWork();
if (job != null && (m_job == null || m_job.Kind != job.Kind || m_job.Target != job.Target))
{
m_jobDeadline = Time.time + JobTimeout;
}
m_job = job;
}
private Job PlanWork()
{
// The forge has no clock: a smelter holds its ore indefinitely and puts its own output on // 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 // 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 // four-state machine and the cook is a five-state one, and that is the whole of the
@ -372,13 +390,7 @@ namespace RacesOfValheim
// in return, because FuelWanted is zero for a station with no work: an empty furnace asks // 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. // for no coal, gets filled, and only then becomes worth stoking.
Job job = m_family == ButlerFamily.Kitchen ? PlanRescue() : null; Job job = m_family == ButlerFamily.Kitchen ? PlanRescue() : null;
job = job ?? PlanCollect() ?? PlanFuel() ?? PlanLoad(); return job ?? PlanCollect() ?? PlanFuel() ?? PlanLoad();
if (job != null && (m_job == null || m_job.Kind != job.Kind || m_job.Target != job.Target))
{
m_jobDeadline = Time.time + JobTimeout;
}
m_job = job;
} }
/// <summary> /// <summary>
@ -630,8 +642,10 @@ namespace RacesOfValheim
// coal, so gating the delivery on free slots sent the servant back to the chest with // 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, // 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. // forever. AcceptsAnything already asks the right question of both doors.
// A station it could not reach is in the penalty box: asking it again straight away
// is the same failed trip.
ButlerStation station = StationById(target); ButlerStation station = StationById(target);
if (station != null && station.Alive && station.Operable && AcceptsAnything(station)) if (station != null && station.Alive && station.Operable && AcceptsAnything(station) && !IsPenalised(target))
{ {
return new Job return new Job
{ {

View file

@ -143,7 +143,8 @@ namespace RacesOfValheim
string status = servant.Status; string status = servant.Status;
if (string.IsNullOrEmpty(status)) status = ModText.Get("rov_hover_butler_waiting"); if (string.IsNullOrEmpty(status)) status = ModText.Get("rov_hover_butler_waiting");
return m_title + "\n" + status; // m_title is a $token, and a hover text goes to the HUD as it is: nothing localizes it later.
return Localization.instance.Localize(m_title) + "\n" + status;
} }
/// <summary> /// <summary>

View file

@ -31,6 +31,8 @@ namespace RacesOfValheim
"Aswid - Eyes", "Aswid - Eyes",
"Fenrir - Appearance", "Fenrir - Appearance",
"Skeleton - Visuals", "Skeleton - Visuals",
// Food and stamina for a Skeleton who wants them: each only gives up an advantage.
"Skeleton - Mortal Habits",
"Sverm - Dorsal Spines", "Sverm - Dorsal Spines",
"Sverm - Emberform", "Sverm - Emberform",
"Trol - Appearance", "Trol - Appearance",
@ -47,6 +49,8 @@ namespace RacesOfValheim
// Each player picks their own True Form: a player model mod (VRM and the like) breaks // 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. // under the troll costume, so a server cannot be allowed to force the costume on.
"legacy true form", "legacy true form",
// The player's own pick of bat flight; the synced Bat Flight Rule can override it.
"free bat flight",
}; };
public static void Apply(ConfigFile config) public static void Apply(ConfigFile config)

View file

@ -0,0 +1,32 @@
using UnityEngine;
using BepInEx.Configuration;
namespace RacesOfValheim
{
/// <summary>
/// The mod-wide debug switches, in one "Debug" section rather than one per race. Bound last
/// from RacesOfValheim.Awake(), so Configuration Manager lists the section at the bottom.
///
/// Every entry stays local (never synced from the server): ConfigSync leaves KeyboardShortcut
/// entries and any key containing "debug" alone, so keep "Debug" in the key names.
/// </summary>
public static class DebugConfig
{
public static ConfigEntry<bool> EnableDebugKey;
public static ConfigEntry<KeyboardShortcut> DebugKey;
public static ConfigEntry<bool> LogFormHits;
public static void Bind(ConfigFile config)
{
const string section = "Debug";
EnableDebugKey = config.Bind(section, "Debug: Enable Debug Key", false,
new ConfigDescription("Turns on the debug key below. Leave it off unless you are sending a bug report."));
DebugKey = config.Bind(section, "Debug Key", new KeyboardShortcut(KeyCode.F8),
new ConfigDescription("Toggles the melee reach readout (top left and log) and writes what the Alfar drones and the camera's target are doing to the log."));
// Was "Fenrir - Debug" / "Debug: Log Form Hits" until v1.6.10. It covers the Skadi,
// Sverm and Trol forms too (FormMelee.LogHit), so it moved here.
LogFormHits = config.Bind(section, "Debug: Log Form Hits", false,
new ConfigDescription("Writes one log line per form claw, bite or swing: what was in reach, what it hit, and why anything was skipped. For bug reports about attacks that do no damage."));
}
}
}

View file

@ -112,12 +112,13 @@ namespace RacesOfValheim
// Flight only knows powered forward, reverse or neither, so the stick is a // Flight only knows powered forward, reverse or neither, so the stick is a
// threshold, not a throttle. Steering stays on the camera, i.e. the right stick. // threshold, not a throttle. Steering stays on the camera, i.e. the right stick.
float stick = -JoyLeftStickY(); float stick = -JoyLeftStickY();
bool forward = input && (Input.GetKey(KeyCode.W) || stick > StickThreshold); // The keyboard side reads vanilla's own Forward/Backward/Run actions, so a key the
// player rebound in the settings flies too, not just W, S and Shift.
bool forward = input && (ZInput.GetButton("Forward") || stick > StickThreshold);
// Forward wins a W+S mash rather than the two cancelling into a dead hover. // Forward wins a W+S mash rather than the two cancelling into a dead hover.
bool backward = input && !forward && (Input.GetKey(KeyCode.S) || stick < -StickThreshold); bool backward = input && !forward && (ZInput.GetButton("Backward") || stick < -StickThreshold);
// Sprint on a pad is vanilla's run button, wherever the chosen layout puts it. // Sprint on a pad is vanilla's run button, wherever the chosen layout puts it.
bool sprintKey = input && (Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift) || bool sprintKey = input && (ZInput.GetButton("Run") || ZInput.GetButton("JoyRun"));
ZInput.GetButton("JoyRun"));
bool onGround = __instance.IsOnGround(); bool onGround = __instance.IsOnGround();
// IsSwimming is the exact test UpdateMotion uses to hand the frame to UpdateSwimming // IsSwimming is the exact test UpdateMotion uses to hand the frame to UpdateSwimming
// instead of UpdateFlying, so it is also the one condition DirectedFlightWaterPatch has // instead of UpdateFlying, so it is also the one condition DirectedFlightWaterPatch has

View file

@ -24,11 +24,16 @@ namespace RacesOfValheim
{ "HareMeat", "CookedHareMeat" }, { "HareMeat", "CookedHareMeat" },
{ "ChickenMeat", "CookedChickenMeat" }, { "ChickenMeat", "CookedChickenMeat" },
{ "BugMeat", "CookedBugMeat" }, { "BugMeat", "CookedBugMeat" },
{ "VoltureMeat", "RoastedVoltureMeat" }, { "VoltureMeat", "CookedVoltureMeat" },
{ "GreydwarfEye", "DeerStew" }, { "GreydwarfEye", "DeerStew" },
{ "Entrails", "Sausages" }, { "Entrails", "Sausages" },
{ "Bloodbag", "BloodPudding" }, { "Bloodbag", "BloodPudding" },
{ "MooseMeat", "CookedMooseMeat" }, { "MooseMeat", "CookedMooseMeat" },
// Bjorn, the Valheim 1.0 bear.
{ "BjornMeat", "CookedBjornMeat" },
// Ashlands.
{ "AsksvinMeat", "CookedAsksvinMeat" },
{ "BoneMawSerpentMeat", "CookedBoneMawSerpentMeat" },
// Raw blubber keeps its own name and icon (EdibleUncooked_ copies them from the raw // Raw blubber keeps its own name and icon (EdibleUncooked_ copies them from the raw
// item) and gives the stats of Seal Meat Soup. // item) and gives the stats of Seal Meat Soup.
{ "SealBlubber", "SealSoup" } { "SealBlubber", "SealSoup" }

View file

@ -76,6 +76,12 @@ namespace RacesOfValheim
private const float PileHeight = 1.05f; private const float PileHeight = 1.05f;
private const float PileSize = 0.45f; private const float PileSize = 0.45f;
// The dressing, in the same unscaled table space as the pile. The pile owns the centre, so the
// tankard stands just clear of it, on the near side.
private static readonly Color BankWoodTint = new Color(0.62f, 0.55f, 0.5f, 1f);
private static readonly Vector3 TankardSpot = new Vector3(0.45f, PileHeight, -0.25f);
private const float TankardSize = 0.38f;
public class Troop public class Troop
{ {
public string Id; public string Id;
@ -276,6 +282,12 @@ namespace RacesOfValheim
prefab.transform.localScale = Vector3.one * TableScale; prefab.transform.localScale = Vector3.one * TableScale;
// A counting table, not a map table: darker wood and a dvergr tankard beside the coin.
// Tinted BEFORE the tankard goes on, or it would be darkened too.
PieceLook.Tint(prefab.transform, BankWoodTint);
ModelBorrow.Attach(prefab.transform, "BankTankard", "Tankard_dvergr",
TankardSpot, Quaternion.identity, TankardSize, "Dvergar", activeOnly: true);
DvergarBancoBehaviour bank = prefab.AddComponent<DvergarBancoBehaviour>(); DvergarBancoBehaviour bank = prefab.AddComponent<DvergarBancoBehaviour>();
foreach (Switch existing in prefab.GetComponentsInChildren<Switch>(true)) foreach (Switch existing in prefab.GetComponentsInChildren<Switch>(true))

View file

@ -0,0 +1,275 @@
using System.Collections.Generic;
using HarmonyLib;
using UnityEngine;
using UnityEngine.UI;
namespace RacesOfValheim
{
/// <summary>
/// A Dvergar builds the black marble and Yggdrasil wood building pieces with stone and fine
/// wood (Wargles' suggestion). Only structural pieces: stations, furniture, containers and
/// fires keep their cost, so nothing with a progression role gets cheaper.
///
/// The swap is done on the piece prefabs of the Dvergar's own client. The build menu, the
/// "known piece" check and ConsumeResources all read the prefab's m_resources, so the menu
/// lists the pieces once stone or fine wood is known, and the player pays the swapped cost.
///
/// The refund is the catch. Piece.DropResources gives back whatever m_resources says on the
/// machine that destroys the piece; vanilla never records what was paid. Without help a human
/// deconstructing a Dvergar's stone wall would get black marble, and a Dvergar deconstructing a
/// vanilla wall would get stone. So a cheap piece is tagged on its ZDO when placed, with the
/// ratios it was paid at, and DropResources is given the matching cost on every client.
/// </summary>
public static class DvergarCheapBuilding
{
// The ratios a cheap piece was paid at. Absent (0) on every piece placed at full cost.
public const string StoneRatioZdoKey = "RacesOfValheim_DvergarCheapStone";
public const string WoodRatioZdoKey = "RacesOfValheim_DvergarCheapWood";
private const string BlackMarble = "BlackMarble";
private const string YggdrasilWood = "YggdrasilWood";
private const string Stone = "Stone";
private const string FineWood = "FineWood";
private const string LabelName = "rov_dvergar_cheap";
private const Piece.UsageTagFlags StructuralTags =
Piece.UsageTagFlags.Building | Piece.UsageTagFlags.Floor | Piece.UsageTagFlags.Wall |
Piece.UsageTagFlags.Roof | Piece.UsageTagFlags.Architecture | Piece.UsageTagFlags.Stairs |
Piece.UsageTagFlags.Doors;
// Piece prefab name -> its vanilla cost. Collected once and kept: the prefabs live for the
// whole session, and the originals must survive every swap.
private static Dictionary<string, Piece.Requirement[]> originals;
private static Dictionary<string, Piece> prefabs;
private static ItemDrop stoneItem, fineWoodItem;
// "" while the prefabs carry their vanilla cost, otherwise the ratios they were swapped at.
private static string appliedKey = "";
private static bool Collect()
{
if (originals != null) return true;
if (ObjectDB.instance == null) return false;
GameObject hammer = ObjectDB.instance.GetItemPrefab("Hammer");
PieceTable table = hammer != null ? hammer.GetComponent<ItemDrop>()?.m_itemData?.m_shared?.m_buildPieces : null;
stoneItem = ObjectDB.instance.GetItemPrefab(Stone)?.GetComponent<ItemDrop>();
fineWoodItem = ObjectDB.instance.GetItemPrefab(FineWood)?.GetComponent<ItemDrop>();
if (table == null || stoneItem == null || fineWoodItem == null) return false;
originals = new Dictionary<string, Piece.Requirement[]>();
prefabs = new Dictionary<string, Piece>();
foreach (GameObject go in table.m_pieces)
{
Piece piece = go != null ? go.GetComponent<Piece>() : null;
if (piece == null || piece.m_resources == null || !UsesSwappedMaterial(piece) || !IsBuildingPiece(piece)) continue;
originals[go.name] = piece.m_resources;
prefabs[go.name] = piece;
// The list to read once in game: every piece that changes cost, and where it is built.
Jotunn.Logger.LogInfo($"[Dvergar] Cheap building: {go.name} at {(piece.m_craftingStation != null ? piece.m_craftingStation.name : "no station")}, {Describe(piece.m_resources)} -> {Describe(BuildCheap(piece.m_resources, 3, 2))} (at 3/2)");
}
Jotunn.Logger.LogInfo($"[Dvergar] Cheap building: {originals.Count} pieces.");
return true;
}
private static bool UsesSwappedMaterial(Piece piece)
{
foreach (Piece.Requirement req in piece.m_resources)
{
if (req.m_resItem == null) continue;
string name = req.m_resItem.name;
if (name == BlackMarble || name == YggdrasilWood) return true;
}
return false;
}
private static bool IsBuildingPiece(Piece piece)
{
bool structural = piece.m_category == Piece.PieceCategory.BuildingWorkbench
|| piece.m_category == Piece.PieceCategory.BuildingStonecutter
|| (piece.m_usage & StructuralTags) != 0;
if (!structural) return false;
if ((piece.m_usage & Piece.UsageTagFlags.Crafting) != 0) return false;
// Anything that does a job keeps its cost, whatever its tags say.
return piece.GetComponentInChildren<CraftingStation>() == null
&& piece.GetComponentInChildren<StationExtension>() == null
&& piece.GetComponentInChildren<Container>() == null
&& piece.GetComponentInChildren<Fireplace>() == null
&& piece.GetComponentInChildren<Smelter>() == null
&& piece.m_comfort <= 0;
}
/// <summary>
/// The cost with black marble and Yggdrasil wood swapped out. New Requirement objects
/// throughout: the originals are shared with the prefab and must stay untouched. A
/// material the piece already had (some marble pieces also ask for stone) is merged.
/// </summary>
private static Piece.Requirement[] BuildCheap(Piece.Requirement[] original, int stoneRatio, int woodRatio)
{
var result = new List<Piece.Requirement>();
foreach (Piece.Requirement req in original)
{
ItemDrop item = req.m_resItem;
int amount = req.m_amount;
if (item != null && item.name == BlackMarble) { item = stoneItem; amount *= stoneRatio; }
else if (item != null && item.name == YggdrasilWood) { item = fineWoodItem; amount *= woodRatio; }
Piece.Requirement same = item != null ? result.Find(r => r.m_resItem == item) : null;
if (same != null)
{
same.m_amount += amount;
continue;
}
result.Add(new Piece.Requirement
{
m_resItem = item,
m_amount = amount,
m_extraAmountOnlyOneIngredient = req.m_extraAmountOnlyOneIngredient,
m_amountPerLevel = req.m_amountPerLevel,
m_upgraderResource = req.m_upgraderResource,
m_recover = req.m_recover,
});
}
return result.ToArray();
}
private static string Describe(Piece.Requirement[] reqs)
{
var parts = new List<string>();
foreach (Piece.Requirement req in reqs)
{
if (req.m_resItem != null) parts.Add($"{req.m_amount} {req.m_resItem.name}");
}
return string.Join(", ", parts);
}
/// <summary>
/// Puts the cost the local player should see on the prefabs. Returns whether anything
/// changed, so the caller knows to refresh the build menu.
/// </summary>
private static bool Apply(bool cheap)
{
int stone = DvergarConfigManagement.CheapStonePerBlackMarble.Value;
int wood = DvergarConfigManagement.CheapFineWoodPerYggdrasil.Value;
string key = cheap ? stone + "/" + wood : "";
if (key == appliedKey) return false;
foreach (var pair in originals)
{
if (!prefabs.TryGetValue(pair.Key, out Piece prefab) || prefab == null) continue;
prefab.m_resources = cheap ? BuildCheap(pair.Value, stone, wood) : pair.Value;
}
appliedKey = key;
return true;
}
private static bool IsSwapped(Piece piece)
{
return appliedKey != "" && piece != null && originals != null
&& originals.ContainsKey(Utils.GetPrefabName(piece.gameObject.name));
}
/// <summary>
/// Keeps the prefabs in step with the local player: a Dvergar with the option on sees the
/// cheap cost, anyone else the vanilla one. Checked every frame because the race can change
/// mid-session (resetrace) and the ratios with the server's config; the check is a string
/// compare unless something changed.
/// </summary>
[HarmonyPatch(typeof(Player), "Update")]
public static class Dvergar_CheapBuildingSync_Patch
{
public static void Postfix(Player __instance)
{
if (__instance != Player.m_localPlayer || !Collect()) return;
bool cheap = DvergarConfigManagement.CheapBuildingEnabled.Value && DvergarRace.IsDvergar();
if (Apply(cheap)) Traverse.Create(__instance).Method("UpdateAvailablePiecesList").GetValue();
}
}
/// <summary>
/// Tags a piece placed at the cheap cost. SetCreator is called once, by PlacePiece, on the
/// placing client, right after the piece was paid for from the same prefab cost.
/// </summary>
[HarmonyPatch(typeof(Piece), nameof(Piece.SetCreator))]
public static class Dvergar_CheapBuildingTag_Patch
{
public static void Postfix(Piece __instance)
{
if (!IsSwapped(__instance)) return;
ZNetView nview = __instance.GetComponent<ZNetView>();
if (nview == null || !nview.IsValid() || !nview.IsOwner()) return;
nview.GetZDO().Set(StoneRatioZdoKey, DvergarConfigManagement.CheapStonePerBlackMarble.Value);
nview.GetZDO().Set(WoodRatioZdoKey, DvergarConfigManagement.CheapFineWoodPerYggdrasil.Value);
}
}
/// <summary>
/// Gives back what the piece cost: the cheap materials at the ratios it was paid at for a
/// tagged piece, the vanilla cost for every other one, whoever destroys it and whatever
/// cost this client's prefab carries right now.
/// </summary>
[HarmonyPatch(typeof(Piece), nameof(Piece.DropResources))]
public static class Dvergar_CheapBuildingRefund_Patch
{
public static void Prefix(Piece __instance)
{
if (!Collect()) return;
if (!originals.TryGetValue(Utils.GetPrefabName(__instance.gameObject.name), out Piece.Requirement[] original)) return;
ZNetView nview = __instance.GetComponent<ZNetView>();
ZDO zdo = nview != null && nview.IsValid() ? nview.GetZDO() : null;
int stone = zdo != null ? zdo.GetInt(StoneRatioZdoKey, 0) : 0;
int wood = zdo != null ? zdo.GetInt(WoodRatioZdoKey, 0) : 0;
__instance.m_resources = stone > 0 && wood > 0 ? BuildCheap(original, stone, wood) : original;
}
}
/// <summary>
/// The Dvergar icon on every swapped piece in the hammer menu. Valheim 1.0
/// draws that menu with BuildUi, one pooled BuildUiPieceButton per piece, and Setup is
/// where a button takes its piece. The old Hud.UpdatePieceList grid still runs but is
/// hidden, so a label there is never seen.
/// </summary>
[HarmonyPatch(typeof(BuildUiPieceButton), nameof(BuildUiPieceButton.Setup))]
public static class Dvergar_CheapBuildingLabel_Patch
{
public static void Postfix(BuildUiPieceButton __instance, Piece pieceInfo)
{
bool cheap = IsSwapped(pieceInfo);
Transform label = __instance.transform.Find(LabelName);
if (label == null)
{
if (!cheap) return;
label = CreateLabel(__instance.transform);
}
if (label.gameObject.activeSelf != cheap) label.gameObject.SetActive(cheap);
}
private static Transform CreateLabel(Transform button)
{
var obj = new GameObject(LabelName, typeof(RectTransform));
obj.transform.SetParent(button, false);
// The race's own icon in the bottom-right corner, as the race menu and the build
// panel's race requirement show it: no text, so it fits in every language.
var rect = (RectTransform)obj.transform;
rect.anchorMin = rect.anchorMax = rect.pivot = new Vector2(1f, 0f);
rect.anchoredPosition = new Vector2(-2f, 2f);
rect.sizeDelta = new Vector2(22f, 22f);
var image = obj.AddComponent<Image>();
image.sprite = RacesOfValheim.RaceIcon(DvergarConfig.RaceId);
image.preserveAspect = true;
image.raycastTarget = false;
return obj.transform;
}
}
}
}

View file

@ -57,6 +57,11 @@ namespace RacesOfValheim
public static ConfigEntry<float> RunicOverchargeWindow; public static ConfigEntry<float> RunicOverchargeWindow;
public static ConfigEntry<float> RunicOverchargeCooldown; public static ConfigEntry<float> RunicOverchargeCooldown;
// ─── Cheap Building ───────────────────────────────────────────────────────
public static ConfigEntry<bool> CheapBuildingEnabled;
public static ConfigEntry<int> CheapStonePerBlackMarble;
public static ConfigEntry<int> CheapFineWoodPerYggdrasil;
public static void Bind(ConfigFile config) public static void Bind(ConfigFile config)
{ {
const string keybinds = "Dvergar - Keybinds"; const string keybinds = "Dvergar - Keybinds";
@ -106,6 +111,14 @@ namespace RacesOfValheim
new ConfigDescription("Seconds a loaded charge is held before it lapses unused.", new AcceptableValueRange<float>(1f, 60f))); new ConfigDescription("Seconds a loaded charge is held before it lapses unused.", new AcceptableValueRange<float>(1f, 60f)));
RunicOverchargeCooldown = config.Bind(overcharge, "Cooldown", 60f, RunicOverchargeCooldown = config.Bind(overcharge, "Cooldown", 60f,
new ConfigDescription("Seconds between casts.", new AcceptableValueRange<float>(0f, 300f))); new ConfigDescription("Seconds between casts.", new AcceptableValueRange<float>(0f, 300f)));
const string building = "Dvergar - Cheap Building";
CheapBuildingEnabled = config.Bind(building, "Enabled", true,
new ConfigDescription("A Dvergar builds the black marble and Yggdrasil wood building pieces (walls, floors, beams, roofs, arches, stairs) with stone and fine wood instead. Stations and furniture keep their cost. A deconstructed piece gives back what was paid for it."));
CheapStonePerBlackMarble = config.Bind(building, "Stone per Black Marble", 3,
new ConfigDescription("Stone a Dvergar pays for each black marble in a piece's cost.", new AcceptableValueRange<int>(1, 10)));
CheapFineWoodPerYggdrasil = config.Bind(building, "Fine Wood per Yggdrasil Wood", 2,
new ConfigDescription("Fine wood a Dvergar pays for each Yggdrasil wood in a piece's cost.", new AcceptableValueRange<int>(1, 10)));
} }
} }
} }

View file

@ -54,9 +54,17 @@ namespace RacesOfValheim
// //
// Skeleton_Hildir stays out deliberately, on the same rule that keeps GoblinKing and the // Skeleton_Hildir stays out deliberately, on the same rule that keeps GoblinKing and the
// Hildir brothers out of the Black Forest set: a quest boss is not somebody's kin. // Hildir brothers out of the Black Forest set: a quest boss is not somebody's kin.
//
// Valheim 1.0 added a skeleton per region (the green swamp ones and the blue mountain ones
// players noticed first), each with a melee-only twin, and spawners place those instead
// of the plain Skeleton. Left out, they fought a Skeleton player the plain ones ignored.
private static readonly HashSet<string> PaludeMobs = new HashSet<string> private static readonly HashSet<string> PaludeMobs = new HashSet<string>
{ {
"Ghost", "Skeleton", "Skeleton_NoArcher", "Skeleton_Poison", // Skeleton, Rancid remains "Ghost", "Skeleton", "Skeleton_NoArcher", "Skeleton_Poison", // Skeleton, Rancid remains
"Skeleton_Meadows", "Skeleton_Meadows_noarcher",
"Skeleton_Swamps", "Skeleton_Swamps_noarcher",
"Skeleton_Mountains", "Skeleton_Mountains_noarcher",
"Skeleton_DeepNorth",
"Draugr", "Draugr_Elite", "Draugr_Ranged", "Draugr", "Draugr_Elite", "Draugr_Ranged",
"Wraith", "Leech", "Abomination", "Wraith", "Leech", "Abomination",
"Blob", "BlobElite", "BlobTar", // Blob, Oozer, Growth "Blob", "BlobElite", "BlobTar", // Blob, Oozer, Growth
@ -157,6 +165,10 @@ namespace RacesOfValheim
if (!__result) return; // already not enemies, nothing to add if (!__result) return; // already not enemies, nothing to add
if (a == null || b == null) return; if (a == null || b == null) return;
// The player's own blow. Peace is the creature's choice, not a shield. See
// RaceGrudge.StrikeScope.
if (RaceGrudge.PlayerStrikes(a)) return;
if (IsThrallTruce(a, b) || IsThrallTruce(b, a)) if (IsThrallTruce(a, b) || IsThrallTruce(b, a))
{ {
__result = false; __result = false;

View file

@ -337,7 +337,16 @@ namespace RacesOfValheim
{ "Draugr_Elite", DraugrShop }, { "Draugr_Elite", DraugrShop },
{ "Skeleton", SkeletonShop }, { "Skeleton", SkeletonShop },
{ "Skeleton_NoArcher", SkeletonShop },
{ "Skeleton_Poison", SkeletonShop }, { "Skeleton_Poison", SkeletonShop },
// Valheim 1.0's regional skeletons, the ones its spawners actually place.
{ "Skeleton_Meadows", SkeletonShop },
{ "Skeleton_Meadows_noarcher", SkeletonShop },
{ "Skeleton_Swamps", SkeletonShop },
{ "Skeleton_Swamps_noarcher", SkeletonShop },
{ "Skeleton_Mountains", SkeletonShop },
{ "Skeleton_Mountains_noarcher", SkeletonShop },
{ "Skeleton_DeepNorth", SkeletonShop },
{ "Ghost", GhostShop }, { "Ghost", GhostShop },
{ "Wraith", WraithShop }, { "Wraith", WraithShop },

View file

@ -21,6 +21,8 @@ namespace RacesOfValheim
public static ConfigEntry<bool> HostilityEnabled; public static ConfigEntry<bool> HostilityEnabled;
public static ConfigEntry<bool> MerchantsEnabled; public static ConfigEntry<bool> MerchantsEnabled;
public static ConfigEntry<float> GrudgeDuration; public static ConfigEntry<float> GrudgeDuration;
public static ConfigEntry<bool> GrudgeSpreadEnabled;
public static ConfigEntry<float> GrudgeSpreadRadius;
// Null-safe, defaulting to ON, for the same reason WarVultureConfig guards its own reads: // Null-safe, defaulting to ON, for the same reason WarVultureConfig guards its own reads:
// a patch that somehow runs before Bind() should behave like the shipped default rather // a patch that somehow runs before Bind() should behave like the shipped default rather
@ -28,6 +30,8 @@ namespace RacesOfValheim
public static bool Hostility => HostilityEnabled?.Value ?? true; public static bool Hostility => HostilityEnabled?.Value ?? true;
public static bool Merchants => MerchantsEnabled?.Value ?? true; public static bool Merchants => MerchantsEnabled?.Value ?? true;
public static float GrudgeSeconds => GrudgeDuration?.Value ?? 60f; public static float GrudgeSeconds => GrudgeDuration?.Value ?? 60f;
public static bool GrudgeSpreads => GrudgeSpreadEnabled?.Value ?? false;
public static float GrudgeSpreadMeters => GrudgeSpreadRadius?.Value ?? 20f;
public static void Bind(ConfigFile config) public static void Bind(ConfigFile config)
{ {
@ -55,11 +59,24 @@ namespace RacesOfValheim
"Without this the truce is absolute in both directions: MonsterAI.UpdateTarget " + "Without this the truce is absolute in both directions: MonsterAI.UpdateTarget " +
"throws away any target BaseAI.IsEnemy calls a non-enemy, so a truced mob could " + "throws away any target BaseAI.IsEnemy calls a non-enemy, so a truced mob could " +
"not fight back even after being struck - it stood still, or fled because it " + "not fight back even after being struck - it stood still, or fled because it " +
"was hurt and had no enemy it was allowed to have. The grudge is per attacker " + "was hurt and had no enemy it was allowed to have. Each creature holds one " +
"and per creature, on whichever machine runs that creature's AI. 0 restores the " + "grudge, against the last player who hit it, and keeps it when another player's " +
"game takes over running that creature. 0 restores the " +
"old absolute truce.", "old absolute truce.",
new AcceptableValueRange<float>(0f, 600f))); new AcceptableValueRange<float>(0f, 600f)));
// Joacwoo's request: the truce made the swamp and the crypts a walk for a Skeleton,
// since only the one creature you hit ever fought back.
GrudgeSpreadEnabled = config.Bind(factions, "Grudge spreads to kin", false,
new ConfigDescription("Off: only the creature you hit fights back. On: hit a creature of your " +
"own faction and every creature of that faction near it turns on you too, " +
"for the same Faction grudge time, the way vanilla's Dvergr treat a human. " +
"Peace still holds until you strike first."));
GrudgeSpreadRadius = config.Bind(factions, "Grudge spread radius", 20f,
new ConfigDescription("Meters around the creature you hit within which its kin join the fight, " +
"with Grudge spreads to kin on.",
new AcceptableValueRange<float>(5f, 60f)));
MerchantsEnabled = config.Bind(factions, "Faction merchants", true, MerchantsEnabled = config.Bind(factions, "Faction merchants", true,
new ConfigDescription("Certain mobs of your own faction can be traded with - 'E - Talk' opens a shop " + new ConfigDescription("Certain mobs of your own faction can be traded with - 'E - Talk' opens a shop " +
"where you sell them what their kind wants. Turn this off and they are ordinary " + "where you sell them what their kind wants. Turn this off and they are ordinary " +

View file

@ -323,17 +323,72 @@ namespace RacesOfValheim
GameObject fireVfx = ZNetScene.instance.GetPrefab("fx_fenring_flames"); GameObject fireVfx = ZNetScene.instance.GetPrefab("fx_fenring_flames");
if (fireVfx == null) return null; if (fireVfx == null) return null;
GameObject instance = Object.Instantiate(fireVfx, player.transform.position + Vector3.up * 1.5f + player.transform.forward, player.transform.rotation, player.transform); GameObject instance = Object.Instantiate(fireVfx, MouthPoint(player), player.transform.rotation, player.transform);
instance.AddComponent<CultistFlameFollow>().Player = player;
// The vanilla effect is one throw, not a held breath: its emitters do not loop (2 s) and
// a TimedDestruction removes it after 5 s, so a long hold went on draining eitr with no
// fire. It loops here and lives until StopFire takes it down.
TimedDestruction timer = instance.GetComponent<TimedDestruction>();
if (timer != null)
{
timer.CancelInvoke();
Object.Destroy(timer);
}
// Aumentiamo la durata delle particelle del 20% // Aumentiamo la durata delle particelle del 20%
foreach (ParticleSystem ps in instance.GetComponentsInChildren<ParticleSystem>()) foreach (ParticleSystem ps in instance.GetComponentsInChildren<ParticleSystem>())
{ {
var main = ps.main; var main = ps.main;
main.startLifetimeMultiplier *= 1.2f; main.startLifetimeMultiplier *= 1.2f;
main.loop = true;
}
// The roar of the fire, the same one-throw story: set before its ZSFX first plays.
foreach (ZSFX sfx in instance.GetComponentsInChildren<ZSFX>())
{
sfx.m_fadeOutOnAwake = false;
AudioSource source = sfx.GetComponent<AudioSource>();
if (source != null) source.loop = true;
} }
return instance; return instance;
} }
// Bone names the breath leaves from, mouth first. Matched by name anywhere under the form.
private static readonly string[] MouthBones = { "Jaw", "Head" };
/// <summary>
/// Where the Cultist's breath starts: just ahead of the form's jaw (or head), so it leaves the
/// mouth at whatever size the form stands. It used to be a fixed 1.5 m above the player's
/// feet, chest height on a Cultist, which is the "fire starts too low" report. Falls back on
/// that fixed point if the form has neither bone.
/// </summary>
public static Vector3 MouthPoint(Player player) => MouthPoint(player, FindMouth(player));
public static Vector3 MouthPoint(Player player, Transform bone)
{
Transform body = player.transform;
return bone != null
? bone.position + body.forward * 0.3f
: body.position + Vector3.up * 1.5f + body.forward;
}
public static Transform FindMouth(Player player)
{
foreach (string wanted in MouthBones)
{
foreach (Transform child in player.transform)
{
if (child.name == "Visual" || !child.gameObject.activeInHierarchy) continue;
foreach (Transform t in child.GetComponentsInChildren<Transform>())
{
if (string.Equals(t.name, wanted, System.StringComparison.OrdinalIgnoreCase)) return t;
}
}
}
return null;
}
public static void PublishFire(bool on) public static void PublishFire(bool on)
{ {
Player player = Player.m_localPlayer; Player player = Player.m_localPlayer;
@ -393,6 +448,8 @@ namespace RacesOfValheim
private ZNetView nview; private ZNetView nview;
private string lastAttack; private string lastAttack;
private GameObject flames; private GameObject flames;
private bool breathing;
private float breathStarted;
private readonly FormLocomotion locomotion = new FormLocomotion(); private readonly FormLocomotion locomotion = new FormLocomotion();
// The flames hang off the player, not this model, so they outlive it unless taken down. // The flames hang off the player, not this model, so they outlive it unless taken down.
@ -433,18 +490,31 @@ namespace RacesOfValheim
bool fire = nview.GetZDO().GetBool(FenrirAttackSync.FireKey, false); bool fire = nview.GetZDO().GetBool(FenrirAttackSync.FireKey, false);
// The breath itself: up while the flag is, gone when it drops. Only the cultist ever // The flag is up for the whole hold, wind-up included, as on the owner's side; the
// sets the flag, so no other form can grow flames here. // flames come at the same point of the same clip (CultistBreathClip). Only the cultist
if (fire && flames == null) // ever sets the flag, so no other form can grow flames here.
if (fire && !breathing)
{ {
flames = FenrirAttackSync.SpawnFlames(player); breathing = true;
breathStarted = Time.time;
// The roar that opens the breath, once per start, the same cue the owner hears. // The roar that opens the breath, once per start, the same cue the owner hears.
// "sfx_cultist_attack_fire_start" was asked for here and there is no sfx_cultist_* // "sfx_cultist_attack_fire_start" was asked for here and there is no sfx_cultist_*
// prefab in the game at all; the fenring's own fire-claw snarl is the real one. // prefab in the game at all; the fenring's own fire-claw snarl is the real one.
FenrirCreatureSound.PlayFireRoar(player.transform.position); FenrirCreatureSound.PlayFireRoar(player.transform.position);
} }
else if (!fire && flames != null) { Destroy(flames); flames = null; } if (fire)
{
CultistBreathClip.Hold(formAnim);
if (flames == null && CultistBreathClip.FlamesDue(formAnim, breathStarted))
flames = FenrirAttackSync.SpawnFlames(player);
}
else if (breathing)
{
breathing = false;
CultistBreathClip.Release(formAnim, player);
if (flames != null) { Destroy(flames); flames = null; }
}
foreach (AnimatorControllerParameter p in formAnim.parameters) foreach (AnimatorControllerParameter p in formAnim.parameters)
{ {
@ -550,15 +620,15 @@ namespace RacesOfValheim
{ {
StartCoroutine(HowlRoutine()); StartCoroutine(HowlRoutine());
} }
else if (RaceInput.AttackDown(1)) // Tasto destro (Heavy Claw) else if (RaceInput.AttackDown(1) && FormMelee.TrySpendStamina(Player.m_localPlayer, FenrirConfig.FenringHeavyClawStamina.Value, Skills.SkillType.Unarmed)) // Tasto destro (Heavy Claw)
{ {
StartCoroutine(ClawRoutine("attack_claw1", FenrirConfig.FenringHeavyClawDamage.Value, 1.2f, 0.5f)); StartCoroutine(ClawRoutine("attack_claw1", FenrirConfig.FenringHeavyClawDamage.Value, 1.2f, 0.5f));
} }
else if (RaceInput.AttackDown(0)) // Tasto sinistro else if (RaceInput.AttackDown(0) && FormMelee.TrySpendStamina(Player.m_localPlayer, FenrirConfig.FenringLightClawStamina.Value, Skills.SkillType.Unarmed)) // Tasto sinistro
{ {
StartCoroutine(ClawRoutine("attack_claw0", FenrirConfig.FenringLightClawDamage.Value, 1.0f, 0.4f)); StartCoroutine(ClawRoutine("attack_claw0", FenrirConfig.FenringLightClawDamage.Value, 1.0f, 0.4f));
} }
else if (RaceInput.AttackDown(2)) // Tasto centrale else if (RaceInput.AttackDown(2) && FormMelee.TrySpendStamina(Player.m_localPlayer, FenrirConfig.FenringJumpAttackStamina.Value, Skills.SkillType.Unarmed)) // Tasto centrale
{ {
StartCoroutine(JumpAttackRoutine()); StartCoroutine(JumpAttackRoutine());
} }
@ -690,7 +760,7 @@ namespace RacesOfValheim
private void ExecuteClawDamage(float baseDamage) private void ExecuteClawDamage(float baseDamage)
{ {
if (Player.m_localPlayer == null) return; if (Player.m_localPlayer == null || FormStagger.AttackInterrupted) return;
Vector3 playerPos = Player.m_localPlayer.transform.position; Vector3 playerPos = Player.m_localPlayer.transform.position;
Vector3 attackPoint = playerPos + Player.m_localPlayer.transform.forward * 1.5f + Vector3.up * 1f; Vector3 attackPoint = playerPos + Player.m_localPlayer.transform.forward * 1.5f + Vector3.up * 1f;
@ -704,6 +774,7 @@ namespace RacesOfValheim
Collider[] hits = Physics.OverlapSphere(attackPoint, attackRadius, layerMask); Collider[] hits = Physics.OverlapSphere(attackPoint, attackRadius, layerMask);
FormMelee.LogSwing(FormLabel, hits.Length); FormMelee.LogSwing(FormLabel, hits.Length);
System.Collections.Generic.HashSet<GameObject> hitObjects = new System.Collections.Generic.HashSet<GameObject>(); System.Collections.Generic.HashSet<GameObject> hitObjects = new System.Collections.Generic.HashSet<GameObject>();
bool hitCreature = false;
foreach (Collider hit in hits) foreach (Collider hit in hits)
{ {
@ -753,10 +824,13 @@ namespace RacesOfValheim
FormMelee.LogHit(FormLabel, target, totalDamage); FormMelee.LogHit(FormLabel, target, totalDamage);
target.Damage(hitData); target.Damage(hitData);
FormMelee.GrantAdrenaline(target); FormMelee.GrantAdrenaline(target);
if (target is Character) hitCreature = true;
} }
} }
} }
} }
if (hitCreature) FormMelee.RaiseSkill(Skills.SkillType.Unarmed);
} }
} }
@ -805,47 +879,40 @@ namespace RacesOfValheim
// still falls through to StopFire() instead of leaving the flames running. // still falls through to StopFire() instead of leaving the flames running.
bool canAct = RaceInput.Allowed; bool canAct = RaceInput.Allowed;
// Fire attack on Right Click // Fire attack on Right Click, held.
if (canAct && RaceInput.AttackHeld(1)) bool wantFire = canAct && RaceInput.AttackHeld(1) && !Player.m_localPlayer.IsStaggering();
{ if (wantFire && Player.m_localPlayer.GetEitr() <= 0f)
if (Player.m_localPlayer.GetEitr() > 0)
{
if (!isShootingFire)
{
StartFire();
}
else
{
UpdateFire();
}
}
else
{ {
// Held with an empty pool. Until now this did nothing whatsoever: no // Held with an empty pool. Until now this did nothing whatsoever: no
// flames, no sound, no reason given - and the form's own tier is Yagluth // flames, no sound, no reason given - and the form's own tier is Yagluth
// while eitr is a Mistlands thing, so a Cultist meets this before it ever // while eitr is a Mistlands thing, so a Cultist meets this before it ever
// meets the fire. // meets the fire.
SayNoEitr(); SayNoEitr();
if (isShootingFire) StopFire(); wantFire = false;
} }
if (wantFire)
{
if (!isShootingFire) StartFire();
else UpdateFire();
} }
else if (isShootingFire) else if (isShootingFire)
{ {
StopFire(); StopFire();
} }
if (canAct && FenrirConfig.HowlKey.Value.IsDownIgnoringHeldKeys()) if (canAct && !isShootingFire && FenrirConfig.HowlKey.Value.IsDownIgnoringHeldKeys())
{ {
StartCoroutine(HowlRoutine()); StartCoroutine(HowlRoutine());
} }
// Attacks on Left Click // Attacks on Left Click
if (canAct && RaceInput.AttackDown(0) && !isShootingFire) if (canAct && RaceInput.AttackDown(0) && !isShootingFire && FormMelee.TrySpendStamina(Player.m_localPlayer, FenrirConfig.CultistClawStamina.Value, Skills.SkillType.Unarmed))
{ {
StartCoroutine(ClawRoutine()); // Single claw StartCoroutine(ClawRoutine()); // Single claw
} }
// Double claw on Middle Click // Double claw on Middle Click
else if (canAct && RaceInput.AttackDown(2) && !isShootingFire) else if (canAct && RaceInput.AttackDown(2) && !isShootingFire && FormMelee.TrySpendStamina(Player.m_localPlayer, FenrirConfig.CultistDoubleClawStamina.Value, Skills.SkillType.Unarmed))
{ {
StartCoroutine(DoubleClawRoutine()); StartCoroutine(DoubleClawRoutine());
} }
@ -907,30 +974,53 @@ namespace RacesOfValheim
ModText.Get("rov_msg_fenrir_only_breath_comes_out_fire")); ModText.Get("rov_msg_fenrir_only_breath_comes_out_fire"));
} }
// The breath runs on the flame clip (CultistBreathClip): pressed, the clip starts; the flames,
// the eitr drain and the damage begin at its own Hit point; released, the clip is cut.
private bool flaming;
private float fireStarted;
/// <summary>True while the local Cultist holds its breath attack, wind-up included. Read by
/// Cultist_BreathFacesCamera_Patch.</summary>
public static bool LocalBreathing { get; private set; }
private void StartFire() private void StartFire()
{ {
if (Player.m_localPlayer == null || isShootingFire) return; if (Player.m_localPlayer == null || isShootingFire) return;
isShootingFire = true; isShootingFire = true;
LocalBreathing = true;
// Planted while it breathes, as the vanilla Cultist is: its controller has no walking
// version of the cast, so a moving Cultist slid along in the casting pose.
// Fenrir_FormHoldStill_Patch holds the player; turning to the camera still works.
FenrirForms.LocalAttacking = true;
flaming = false;
fireStarted = Time.time;
fireTimer = 0f;
FormAnimGuard.LeaveHowl(cultistAnim); FormAnimGuard.LeaveHowl(cultistAnim);
cultistAnim.SetFloat("forward_speed", 0f); cultistAnim.SetFloat("forward_speed", 0f);
cultistAnim.SetFloat("sideway_speed", 0f); cultistAnim.SetFloat("sideway_speed", 0f);
cultistAnim.SetBool("attack_fire", true);
FenrirAttackSync.PublishFire(true); FenrirAttackSync.PublishFire(true);
// Same cue the remote mirror plays - see the fire branch in the sync behaviour above. // Same cue the remote mirror plays - see the fire branch in the sync behaviour above.
FenrirCreatureSound.PlayFireRoar(Player.m_localPlayer.transform.position); FenrirCreatureSound.PlayFireRoar(Player.m_localPlayer.transform.position);
cultistAnim.SetTrigger("attack_flames"); cultistAnim.SetTrigger("attack_flames");
FenrirAttackSync.Publish("attack_flames"); FenrirAttackSync.Publish("attack_flames");
if (fireEffectInstance == null) fireEffectInstance = FenrirAttackSync.SpawnFlames(Player.m_localPlayer);
} }
private void UpdateFire() private void UpdateFire()
{ {
Player.m_localPlayer.UseEitr(FenrirConfig.CultistFireEitrDrainPerSecond.Value * Time.deltaTime);
cultistAnim.SetFloat("forward_speed", 0f); cultistAnim.SetFloat("forward_speed", 0f);
cultistAnim.SetFloat("sideway_speed", 0f); cultistAnim.SetFloat("sideway_speed", 0f);
CultistBreathClip.Hold(cultistAnim);
if (!flaming)
{
if (!CultistBreathClip.FlamesDue(cultistAnim, fireStarted)) return;
flaming = true;
if (fireEffectInstance == null) fireEffectInstance = FenrirAttackSync.SpawnFlames(Player.m_localPlayer);
}
Player.m_localPlayer.UseEitr(FenrirConfig.CultistFireEitrDrainPerSecond.Value * Time.deltaTime);
fireTimer += Time.deltaTime; fireTimer += Time.deltaTime;
if (fireTimer >= 0.2f) // Damage tick every 0.2s if (fireTimer >= 0.2f) // Damage tick every 0.2s
@ -944,13 +1034,19 @@ namespace RacesOfValheim
private void OnDestroy() private void OnDestroy()
{ {
if (isShootingFire) FenrirAttackSync.PublishFire(false); if (isShootingFire) FenrirAttackSync.PublishFire(false);
if (isShootingFire) FenrirForms.LocalAttacking = false;
LocalBreathing = false;
} }
private void StopFire() private void StopFire()
{ {
isShootingFire = false; isShootingFire = false;
LocalBreathing = false;
FenrirForms.LocalAttacking = false;
flaming = false;
cultistAnim.ResetTrigger("attack_flames"); cultistAnim.ResetTrigger("attack_flames");
FenrirAttackSync.PublishFire(false); FenrirAttackSync.PublishFire(false);
CultistBreathClip.Release(cultistAnim, Player.m_localPlayer);
if (fireEffectInstance != null) if (fireEffectInstance != null)
{ {
@ -975,6 +1071,7 @@ namespace RacesOfValheim
Collider[] hits = Physics.OverlapSphere(attackPoint, attackRadius, layerMask); Collider[] hits = Physics.OverlapSphere(attackPoint, attackRadius, layerMask);
FormMelee.LogSwing(FormLabel, hits.Length); FormMelee.LogSwing(FormLabel, hits.Length);
System.Collections.Generic.HashSet<GameObject> hitObjects = new System.Collections.Generic.HashSet<GameObject>(); System.Collections.Generic.HashSet<GameObject> hitObjects = new System.Collections.Generic.HashSet<GameObject>();
bool hitCreature = false;
foreach (Collider hit in hits) foreach (Collider hit in hits)
{ {
@ -1014,6 +1111,7 @@ namespace RacesOfValheim
FormMelee.LogHit(FormLabel, target, totalDamage); FormMelee.LogHit(FormLabel, target, totalDamage);
target.Damage(hitData); target.Damage(hitData);
FormMelee.GrantAdrenaline(target, 0.2f); // one 0.2s tick: a full hit per second of breath FormMelee.GrantAdrenaline(target, 0.2f); // one 0.2s tick: a full hit per second of breath
if (target is Character) hitCreature = true;
if (ZNetScene.instance != null) if (ZNetScene.instance != null)
{ {
@ -1023,6 +1121,8 @@ namespace RacesOfValheim
} }
} }
} }
if (hitCreature) FormMelee.RaiseSkill(Skills.SkillType.ElementalMagic, 0.2f); // one 0.2s tick: a full swing's worth per second of breath
} }
private IEnumerator ClawRoutine() private IEnumerator ClawRoutine()
@ -1034,25 +1134,30 @@ namespace RacesOfValheim
cultistAnim.SetFloat("sideway_speed", 0f); cultistAnim.SetFloat("sideway_speed", 0f);
// Per il Cultista usiamo esplicitamente il trigger dell'artigliata // Per il Cultista usiamo esplicitamente il trigger dell'artigliata
int baseline = FenrirForms.AttackEvents;
float started = Time.time;
cultistAnim.SetTrigger("attack_claw"); cultistAnim.SetTrigger("attack_claw");
FenrirAttackSync.Publish("attack_claw", "sfx_fenring_claw_start"); FenrirAttackSync.Publish("attack_claw", "sfx_fenring_claw_start");
yield return new WaitForSeconds(0.4f); // The blow lands on the clip's own Hit event (ClawAttackCultist: 0.64 s of 1.33 s), and
// the lock holds until the clip is over. A fixed 0.4 s hit and a 0.5 s lock used to land
// the damage before the claw swung and let the next click start a new one mid-swing.
yield return null;
float length = ClipLength(1.33f);
yield return WaitForHit(baseline, started);
PlaySFX("sfx_fenring_claw_start"); PlaySFX("sfx_fenring_claw_start");
ExecuteClawDamage(FenrirConfig.CultistClawDamage.Value); ExecuteClawDamage(FenrirConfig.CultistClawDamage.Value);
float remainingTimeToIdle = 0.5f - 0.4f; yield return WaitUntilClipEnds(length, started);
if (remainingTimeToIdle > 0)
{
yield return new WaitForSeconds(remainingTimeToIdle);
}
cultistAnim.ResetTrigger("attack_claw"); cultistAnim.ResetTrigger("attack_claw");
isAttacking = false; isAttacking = false;
} }
// Each swipe of the double claw deals this share of Double Claw Damage. Two swipes give
// 120% of what the old single hit dealt: a little more, for a slower swing that can be cut short.
private const float DoubleClawHitShare = 0.6f;
private IEnumerator DoubleClawRoutine() private IEnumerator DoubleClawRoutine()
{ {
isAttacking = true; isAttacking = true;
@ -1061,27 +1166,66 @@ namespace RacesOfValheim
cultistAnim.SetFloat("forward_speed", 0f); cultistAnim.SetFloat("forward_speed", 0f);
cultistAnim.SetFloat("sideway_speed", 0f); cultistAnim.SetFloat("sideway_speed", 0f);
int baseline = FenrirForms.AttackEvents;
float started = Time.time;
cultistAnim.SetTrigger("attack_claw_double"); cultistAnim.SetTrigger("attack_claw_double");
FenrirAttackSync.Publish("attack_claw_double", "sfx_fenring_claw_start"); FenrirAttackSync.Publish("attack_claw_double", "sfx_fenring_claw_start");
// L'animazione double claw è più lunga, facciamo il danno un po' dopo // DoubleClawAttackCultist carries two Hit events (0.64 s and 1.21 s of 1.83 s), one per
yield return new WaitForSeconds(0.6f); // swipe. It used to deal one hit at a fixed 0.6 s, so the second swipe did nothing.
yield return null;
float length = ClipLength(1.83f);
float damage = FenrirConfig.CultistDoubleClawDamage.Value * DoubleClawHitShare;
yield return WaitForHit(baseline, started);
PlaySFX("sfx_fenring_claw_start"); PlaySFX("sfx_fenring_claw_start");
ExecuteClawDamage(damage);
ExecuteClawDamage(FenrirConfig.CultistDoubleClawDamage.Value); yield return WaitForHit(baseline + 1, started, HitEventTimeout + 0.6f);
PlaySFX("sfx_fenring_claw_start");
// Attendiamo che l'animazione finisca (locking del giocatore) ExecuteClawDamage(damage);
// L'animazione doppia del cultista dura circa 1.5 - 2 secondi
yield return new WaitForSeconds(1.2f);
yield return WaitUntilClipEnds(length, started);
cultistAnim.ResetTrigger("attack_claw_double"); cultistAnim.ResetTrigger("attack_claw_double");
isAttacking = false; isAttacking = false;
} }
// Longest a swipe waits for its Hit event before landing anyway, measured from the trigger:
// a clip that never sends one must not leave the Cultist swinging at nothing.
private const float HitEventTimeout = 1.5f;
/// <summary>Waits until the clip has sent more than <paramref name="seen"/> hit events since
/// the trigger, or until the timeout.</summary>
private IEnumerator WaitForHit(int seen, float started, float timeout = HitEventTimeout)
{
while (FenrirForms.AttackEvents <= seen && Time.time - started < timeout)
{
yield return null;
}
}
/// <summary>The attack clip's length, read a frame after its trigger, when the transition
/// into it has begun. <paramref name="fallback"/> is the clip's length in the game files.</summary>
private float ClipLength(float fallback)
{
AnimatorClipInfo[] clips = cultistAnim.IsInTransition(0)
? cultistAnim.GetNextAnimatorClipInfo(0)
: cultistAnim.GetCurrentAnimatorClipInfo(0);
if (clips != null && clips.Length > 0 && clips[0].clip != null) return clips[0].clip.length;
return fallback;
}
/// <summary>Holds the lock until the clip has played out, clamped so a wrong reading can
/// neither cut a swing short nor freeze the form.</summary>
private IEnumerator WaitUntilClipEnds(float length, float started)
{
float remaining = Mathf.Clamp(length, 0.6f, 3f) - (Time.time - started);
if (remaining > 0f) yield return new WaitForSeconds(remaining);
}
private void ExecuteClawDamage(float baseDamage) private void ExecuteClawDamage(float baseDamage)
{ {
if (Player.m_localPlayer == null) return; if (Player.m_localPlayer == null || FormStagger.AttackInterrupted) return;
Vector3 playerPos = Player.m_localPlayer.transform.position; Vector3 playerPos = Player.m_localPlayer.transform.position;
Vector3 attackPoint = playerPos + Player.m_localPlayer.transform.forward * 1.5f + Vector3.up * 1f; Vector3 attackPoint = playerPos + Player.m_localPlayer.transform.forward * 1.5f + Vector3.up * 1f;
@ -1095,6 +1239,7 @@ namespace RacesOfValheim
Collider[] hits = Physics.OverlapSphere(attackPoint, attackRadius, layerMask); Collider[] hits = Physics.OverlapSphere(attackPoint, attackRadius, layerMask);
FormMelee.LogSwing(FormLabel, hits.Length); FormMelee.LogSwing(FormLabel, hits.Length);
System.Collections.Generic.HashSet<GameObject> hitObjects = new System.Collections.Generic.HashSet<GameObject>(); System.Collections.Generic.HashSet<GameObject> hitObjects = new System.Collections.Generic.HashSet<GameObject>();
bool hitCreature = false;
foreach (Collider hit in hits) foreach (Collider hit in hits)
{ {
@ -1144,10 +1289,13 @@ namespace RacesOfValheim
FormMelee.LogHit(FormLabel, target, totalDamage); FormMelee.LogHit(FormLabel, target, totalDamage);
target.Damage(hitData); target.Damage(hitData);
FormMelee.GrantAdrenaline(target); FormMelee.GrantAdrenaline(target);
if (target is Character) hitCreature = true;
} }
} }
} }
} }
if (hitCreature) FormMelee.RaiseSkill(Skills.SkillType.Unarmed);
} }
} }
@ -1194,15 +1342,15 @@ namespace RacesOfValheim
{ {
StartCoroutine(WolfHowlRoutine()); StartCoroutine(WolfHowlRoutine());
} }
else if (RaceInput.AttackDown(0)) // Left Click else if (RaceInput.AttackDown(0) && FormMelee.TrySpendStamina(Player.m_localPlayer, FenrirConfig.WolfAttack1Stamina.Value, Skills.SkillType.Unarmed)) // Left Click
{ {
StartCoroutine(WolfAttackRoutine("attack1", FenrirConfig.WolfAttack1Damage.Value, 0.6f, 0.2f)); StartCoroutine(WolfAttackRoutine("attack1", FenrirConfig.WolfAttack1Damage.Value, 0.6f, 0.2f));
} }
else if (RaceInput.AttackDown(1)) // Right Click else if (RaceInput.AttackDown(1) && FormMelee.TrySpendStamina(Player.m_localPlayer, FenrirConfig.WolfAttack2Stamina.Value, Skills.SkillType.Unarmed)) // Right Click
{ {
StartCoroutine(WolfAttackRoutine("attack2", FenrirConfig.WolfAttack2Damage.Value, 0.8f, 0.3f)); StartCoroutine(WolfAttackRoutine("attack2", FenrirConfig.WolfAttack2Damage.Value, 0.8f, 0.3f));
} }
else if (RaceInput.AttackDown(2)) // Middle Click else if (RaceInput.AttackDown(2) && FormMelee.TrySpendStamina(Player.m_localPlayer, FenrirConfig.WolfAttack3Stamina.Value, Skills.SkillType.Unarmed)) // Middle Click
{ {
StartCoroutine(WolfAttackRoutine("attack3", FenrirConfig.WolfAttack3Damage.Value, 1.0f, 0.4f)); StartCoroutine(WolfAttackRoutine("attack3", FenrirConfig.WolfAttack3Damage.Value, 1.0f, 0.4f));
} }
@ -1295,7 +1443,7 @@ namespace RacesOfValheim
private void ExecuteBiteDamage(float baseDamage) private void ExecuteBiteDamage(float baseDamage)
{ {
if (Player.m_localPlayer == null) return; if (Player.m_localPlayer == null || FormStagger.AttackInterrupted) return;
Vector3 playerPos = Player.m_localPlayer.transform.position; Vector3 playerPos = Player.m_localPlayer.transform.position;
// Il lupo è basso, abbassiamo l'altezza dell'attacco // Il lupo è basso, abbassiamo l'altezza dell'attacco
@ -1310,6 +1458,7 @@ namespace RacesOfValheim
Collider[] hits = Physics.OverlapSphere(attackPoint, attackRadius, layerMask); Collider[] hits = Physics.OverlapSphere(attackPoint, attackRadius, layerMask);
FormMelee.LogSwing(FormLabel, hits.Length); FormMelee.LogSwing(FormLabel, hits.Length);
System.Collections.Generic.HashSet<GameObject> hitObjects = new System.Collections.Generic.HashSet<GameObject>(); System.Collections.Generic.HashSet<GameObject> hitObjects = new System.Collections.Generic.HashSet<GameObject>();
bool hitCreature = false;
foreach (Collider hit in hits) foreach (Collider hit in hits)
{ {
@ -1359,10 +1508,13 @@ namespace RacesOfValheim
FormMelee.LogHit(FormLabel, target, totalDamage); FormMelee.LogHit(FormLabel, target, totalDamage);
target.Damage(hitData); target.Damage(hitData);
FormMelee.GrantAdrenaline(target); FormMelee.GrantAdrenaline(target);
if (target is Character) hitCreature = true;
} }
} }
} }
} }
if (hitCreature) FormMelee.RaiseSkill(Skills.SkillType.Unarmed);
} }
} }
@ -1410,16 +1562,16 @@ namespace RacesOfValheim
{ {
StartCoroutine(UlvHowlRoutine()); StartCoroutine(UlvHowlRoutine());
} }
else if (RaceInput.AttackDown(0)) // Left Click else if (RaceInput.AttackDown(0) && FormMelee.TrySpendStamina(Player.m_localPlayer, FenrirConfig.UlvBiteStamina.Value, Skills.SkillType.Unarmed)) // Left Click
{ {
StartCoroutine(UlvAttackRoutine("attack_bite", FenrirConfig.UlvBiteDamage.Value, 0.6f, 0.2f)); StartCoroutine(UlvAttackRoutine("attack_bite", FenrirConfig.UlvBiteDamage.Value, 0.6f, 0.2f));
} }
else if (RaceInput.AttackDown(1)) // Right Click else if (RaceInput.AttackDown(1) && FormMelee.TrySpendStamina(Player.m_localPlayer, FenrirConfig.UlvHeavyBiteStamina.Value, Skills.SkillType.Unarmed)) // Right Click
{ {
// Right click uses bite but as a heavier attack since slash is moved to jump // Right click uses bite but as a heavier attack since slash is moved to jump
StartCoroutine(UlvAttackRoutine("attack_bite", FenrirConfig.UlvHeavyBiteDamage.Value, 0.8f, 0.3f)); StartCoroutine(UlvAttackRoutine("attack_bite", FenrirConfig.UlvHeavyBiteDamage.Value, 0.8f, 0.3f));
} }
else if (RaceInput.AttackDown(2)) // Middle Click else if (RaceInput.AttackDown(2) && FormMelee.TrySpendStamina(Player.m_localPlayer, FenrirConfig.UlvJumpAttackStamina.Value, Skills.SkillType.Unarmed)) // Middle Click
{ {
StartCoroutine(UlvJumpAttackRoutine()); StartCoroutine(UlvJumpAttackRoutine());
} }
@ -1504,7 +1656,7 @@ namespace RacesOfValheim
private void ExecuteBiteDamage(float baseDamage) private void ExecuteBiteDamage(float baseDamage)
{ {
if (Player.m_localPlayer == null) return; if (Player.m_localPlayer == null || FormStagger.AttackInterrupted) return;
Vector3 playerPos = Player.m_localPlayer.transform.position; Vector3 playerPos = Player.m_localPlayer.transform.position;
Vector3 attackPoint = playerPos + Player.m_localPlayer.transform.forward * 1.5f + Vector3.up * 0.5f; Vector3 attackPoint = playerPos + Player.m_localPlayer.transform.forward * 1.5f + Vector3.up * 0.5f;
@ -1518,6 +1670,7 @@ namespace RacesOfValheim
Collider[] hits = Physics.OverlapSphere(attackPoint, attackRadius, layerMask); Collider[] hits = Physics.OverlapSphere(attackPoint, attackRadius, layerMask);
FormMelee.LogSwing(FormLabel, hits.Length); FormMelee.LogSwing(FormLabel, hits.Length);
System.Collections.Generic.HashSet<GameObject> hitObjects = new System.Collections.Generic.HashSet<GameObject>(); System.Collections.Generic.HashSet<GameObject> hitObjects = new System.Collections.Generic.HashSet<GameObject>();
bool hitCreature = false;
foreach (Collider hit in hits) foreach (Collider hit in hits)
{ {
@ -1567,10 +1720,13 @@ namespace RacesOfValheim
FormMelee.LogHit(FormLabel, target, totalDamage); FormMelee.LogHit(FormLabel, target, totalDamage);
target.Damage(hitData); target.Damage(hitData);
FormMelee.GrantAdrenaline(target); FormMelee.GrantAdrenaline(target);
if (target is Character) hitCreature = true;
} }
} }
} }
} }
if (hitCreature) FormMelee.RaiseSkill(Skills.SkillType.Unarmed);
} }
private IEnumerator UlvJumpAttackRoutine() private IEnumerator UlvJumpAttackRoutine()
@ -1621,4 +1777,160 @@ namespace RacesOfValheim
} }
} }
/// <summary>
/// The Cultist's breath, timed by its own clip. fenring_cultist_animator's attack_flames state
/// plays "Flame Spell Attack" (read offline with UnityPy, bundle c4210710): 3.5 s, the hands
/// light at 1.094 s (TrailOn), the vanilla flames come at 1.245 s (Hit) and are taken down at
/// 3.193 s. The state leaves for Movement only when the clip ends, so a short click used to
/// leave the Cultist standing with its arms up for the rest of the 3.5 s, breathing nothing.
///
/// Now the flames wait for the clip's Hit point, the arms are held in the casting pose for as
/// long as the button is, and letting go blends straight back to Movement. Shared by the
/// owner's Cultist and every onlooker's copy, so both play the same breath.
/// </summary>
internal static class CultistBreathClip
{
private static readonly int State = Animator.StringToHash("Base Layer.attack_flames");
private const string MovementState = "Base Layer.Movement";
// The clip's Hit event, where the vanilla Cultist's flames come out.
private const float FlamesAt = 1.245f;
// The throw itself: the Animator stops here while held. After it the vanilla Cultist lowers
// its arms while its fire flies on alone, so a pin at 2.6 s held an idle-looking pose.
private const float PinAt = 1.3f;
private const float Fade = 0.25f;
/// <summary>Seconds into the flame clip, or -1 while the Animator is in another state.</summary>
private static float ClipTime(Animator anim)
{
AnimatorStateInfo info = anim.IsInTransition(0) ? anim.GetNextAnimatorStateInfo(0) : anim.GetCurrentAnimatorStateInfo(0);
return info.fullPathHash == State ? info.normalizedTime * info.length : -1f;
}
/// <summary>True once the clip has reached its Hit point. If the clip never started (another
/// state took the Animator), the same delay counted from the press stands in for it.</summary>
public static bool FlamesDue(Animator anim, float started)
{
float t = ClipTime(anim);
return t >= FlamesAt || (t < 0f && Time.time - started >= FlamesAt + 0.2f);
}
/// <summary>
/// Holds the arms in the casting pose: once the clip reaches PinAt it is put back there every
/// frame. Not with Animator.speed = 0, which is what the troll's pin uses: the creature's own
/// CharacterAnimEvent sits on this model and sets speed back to 1 on every physics step while
/// the player is not in a vanilla attack, so the clip ran on to its end and the Cultist went
/// back to idle with the fire still pouring out.
/// </summary>
public static void Hold(Animator anim)
{
if (anim.IsInTransition(0)) return;
AnimatorStateInfo info = anim.GetCurrentAnimatorStateInfo(0);
if (info.fullPathHash != State || info.length <= 0f) return;
if (info.normalizedTime * info.length >= PinAt) anim.Play(State, 0, PinAt / info.length);
}
/// <summary>Blends out of the clip, unless a stagger has taken over (FormStagger has fired
/// the form's own).</summary>
public static void Release(Animator anim, Player player)
{
if (anim == null) return;
if (ClipTime(anim) >= 0f && (player == null || !player.IsStaggering()))
anim.CrossFadeInFixedTime(MovementState, Fade, 0);
}
}
/// <summary>
/// Keeps the Cultist's breath in its hands, where the vanilla Cultist casts it from. fx_fenring_flames
/// has two emitters, "flames_world left" and "flames_world right", set 1.2 to 1.6 m ahead of
/// its own origin; spawned at the creature, the fire began that far in front of it. Each
/// emitter goes on its hand bone (fenring_cultist rig: .../LeftForeArm/LeftHand and the right
/// one), pointing where the player faces, so the two streams leave the palms and run forward.
/// The embers and the light sit between the hands. Placed every LateUpdate, after the form's
/// Animator has moved the arms. The same on every client's copy.
///
/// A form without hand bones keeps the whole effect at its mouth, as before.
/// </summary>
internal class CultistFlameFollow : MonoBehaviour
{
// Ahead of the palm, so the stream does not start inside the hand.
private const float AheadOfHand = 0.15f;
// The light, further ahead along the stream.
private const float LightAhead = 1.5f;
public Player Player;
private Transform mouth, leftHand, rightHand;
private Transform leftFlames, rightFlames, embers, light;
private bool partsFound;
private float nextLook;
private void LateUpdate()
{
if (Player == null) return;
if (!partsFound)
{
partsFound = true;
leftFlames = transform.Find("flames_world left");
rightFlames = transform.Find("flames_world right");
embers = transform.Find("FireEmbers");
light = transform.Find("Point light");
}
// The form can be rebuilt under the same flames; look again now and then if lost.
if ((leftHand == null || rightHand == null || mouth == null) && Time.time >= nextLook)
{
nextLook = Time.time + 0.5f;
leftHand = FindBone(Player, "LeftHand");
rightHand = FindBone(Player, "RightHand");
mouth = FenrirAttackSync.FindMouth(Player);
}
Quaternion facing = Player.transform.rotation;
transform.SetPositionAndRotation(FenrirAttackSync.MouthPoint(Player, mouth), facing);
if (leftHand == null || rightHand == null || leftFlames == null || rightFlames == null) return;
Vector3 forward = Player.transform.forward;
Vector3 left = leftHand.position + forward * AheadOfHand;
Vector3 right = rightHand.position + forward * AheadOfHand;
leftFlames.SetPositionAndRotation(left, facing);
rightFlames.SetPositionAndRotation(right, facing);
Vector3 between = (left + right) * 0.5f;
if (embers != null) embers.SetPositionAndRotation(between, facing);
if (light != null) light.position = between + forward * LightAhead;
}
private static Transform FindBone(Player player, string name)
{
foreach (Transform child in player.transform)
{
if (child.name == "Visual" || !child.gameObject.activeInHierarchy) continue;
foreach (Transform t in child.GetComponentsInChildren<Transform>())
{
if (t.name == name) return t;
}
}
return null;
}
}
/// <summary>
/// Turns the Cultist toward the camera while it breathes fire, as vanilla turns a player who
/// blocks or draws a bow: Player.AlwaysRotateCamera answers true for those, and Character then
/// turns the body to the look direction at its own turn speed. The breath is not a vanilla
/// attack, so the body stayed facing wherever the movement keys had left it.
/// </summary>
[HarmonyPatch(typeof(Player), "AlwaysRotateCamera")]
public static class Cultist_BreathFacesCamera_Patch
{
public static void Postfix(Player __instance, ref bool __result)
{
if (!__result && __instance == Player.m_localPlayer && CultistFormBehavior.LocalBreathing) __result = true;
}
}
} }

View file

@ -38,15 +38,33 @@ namespace RacesOfValheim
public static ConfigEntry<float> SpeedBonusPerState; public static ConfigEntry<float> SpeedBonusPerState;
public static ConfigEntry<float> JumpBonusPerState; public static ConfigEntry<float> JumpBonusPerState;
public static ConfigEntry<float> SunSicknessDuration; public static ConfigEntry<float> SunSicknessDuration;
public static ConfigEntry<float> SensesRadius;
// ─── Form buffs (applied while transformed) ─────────────────────────── // ─── Form buffs (applied while transformed) ───────────────────────────
public static ConfigEntry<float> FullFormSpeedBonus; public static ConfigEntry<float> FullFormSpeedBonus;
public static ConfigEntry<float> FullFormJumpBonus; public static ConfigEntry<float> FullFormJumpBonus;
public static ConfigEntry<float> FullFormFallDamageReduction; public static ConfigEntry<float> FullFormFallDamageReduction;
public static ConfigEntry<float> WolfFormSpeedBonus; public static ConfigEntry<float> WolfFormSpeedBonus;
public static ConfigEntry<float> UlvFormSpeedBonus;
public static ConfigEntry<float> FenringDamageReduction;
public static ConfigEntry<float> CultistExtraDamageTaken;
public static ConfigEntry<float> WolfFormFallDamageReduction; public static ConfigEntry<float> WolfFormFallDamageReduction;
public static ConfigEntry<float> FormStaminaRegenMultiplier; public static ConfigEntry<float> FormStaminaRegenMultiplier;
public static ConfigEntry<float> FormStaminaDrainReduction; public static ConfigEntry<float> FormStaminaDrainReduction;
public static ConfigEntry<float> FormAdrenalineMultiplier;
// ─── Form attack stamina (base cost, before the Unarmed skill discount) ─
public static ConfigEntry<float> FenringLightClawStamina;
public static ConfigEntry<float> FenringHeavyClawStamina;
public static ConfigEntry<float> FenringJumpAttackStamina;
public static ConfigEntry<float> CultistClawStamina;
public static ConfigEntry<float> CultistDoubleClawStamina;
public static ConfigEntry<float> WolfAttack1Stamina;
public static ConfigEntry<float> WolfAttack2Stamina;
public static ConfigEntry<float> WolfAttack3Stamina;
public static ConfigEntry<float> UlvBiteStamina;
public static ConfigEntry<float> UlvHeavyBiteStamina;
public static ConfigEntry<float> UlvJumpAttackStamina;
// ─── Fenring form attacks ───────────────────────────────────────────── // ─── Fenring form attacks ─────────────────────────────────────────────
public static ConfigEntry<float> FenringHeavyClawDamage; public static ConfigEntry<float> FenringHeavyClawDamage;
@ -82,9 +100,6 @@ namespace RacesOfValheim
public static ConfigEntry<float> UlvAttackRadius; public static ConfigEntry<float> UlvAttackRadius;
public static ConfigEntry<float> UlvPushForce; public static ConfigEntry<float> UlvPushForce;
// ─── Debug ─────────────────────────────────────────────────────────────
public static ConfigEntry<bool> DebugFormHits;
// ─── Appearance (per player, never synced) ────────────────────────────── // ─── Appearance (per player, never synced) ──────────────────────────────
public static ConfigEntry<bool> ReadyMessage; public static ConfigEntry<bool> ReadyMessage;
public static ConfigEntry<bool> EyeGlow; public static ConfigEntry<bool> EyeGlow;
@ -117,16 +132,30 @@ namespace RacesOfValheim
SunSicknessDuration = config.Bind(combat, "Sun Sickness Duration", 60f, SunSicknessDuration = config.Bind(combat, "Sun Sickness Duration", 60f,
new ConfigDescription("Seconds of forced human form after being reverted by sunrise.", new AcceptableValueRange<float>(0f, 300f))); new ConfigDescription("Seconds of forced human form after being reverted by sunrise.", new AcceptableValueRange<float>(0f, 300f)));
const string senses = "Fenrir - Superhuman Senses";
SensesRadius = config.Bind(senses, "Detection Radius", 100f,
new ConfigDescription("Meters within which nearby creatures glow green while you are in any form. The light itself follows the Aswid's Marker Light settings.", new AcceptableValueRange<float>(10f, 300f)));
const string buffs = "Fenrir - Form Buffs"; const string buffs = "Fenrir - Form Buffs";
BindNote(config, buffs, "Note: these values need a relog to take effect."); BindNote(config, buffs, "Note: these values need a relog to take effect.");
FullFormSpeedBonus = config.Bind(buffs, "Full Form Speed Bonus", 1.0f, // Each form has a job once all three are unlocked (Lexsonn's suggestion): the Ulv
new ConfigDescription("Speed multiplier bonus while in Fenring or Cultist form.", new AcceptableValueRange<float>(0f, 3f))); // travels, the Fenring holds the line, the Cultist burns. The speed keys were renamed
// from "Full Form Speed Bonus" and "Wolf Form Speed Bonus" so a saved .cfg cannot keep
// the old order, where the Fenring outran the Ulv.
FullFormSpeedBonus = config.Bind(buffs, "Fenring And Cultist Speed Bonus", 0.5f,
new ConfigDescription("Speed multiplier bonus while in Fenring or Cultist form. 0.5 = 50% faster.", new AcceptableValueRange<float>(0f, 3f)));
FullFormJumpBonus = config.Bind(buffs, "Full Form Jump Bonus", 1.0f, FullFormJumpBonus = config.Bind(buffs, "Full Form Jump Bonus", 1.0f,
new ConfigDescription("Jump multiplier bonus while in Fenring or Cultist form.", new AcceptableValueRange<float>(0f, 3f))); new ConfigDescription("Jump multiplier bonus while in Fenring or Cultist form.", new AcceptableValueRange<float>(0f, 3f)));
FullFormFallDamageReduction = config.Bind(buffs, "Full Form Fall Damage Reduction", 1.0f, FullFormFallDamageReduction = config.Bind(buffs, "Full Form Fall Damage Reduction", 1.0f,
new ConfigDescription("Fall damage reduction while in Fenring or Cultist form (1 = immune).", new AcceptableValueRange<float>(0f, 1f))); new ConfigDescription("Fall damage reduction while in Fenring or Cultist form (1 = immune).", new AcceptableValueRange<float>(0f, 1f)));
WolfFormSpeedBonus = config.Bind(buffs, "Wolf Form Speed Bonus", 0.5f, WolfFormSpeedBonus = config.Bind(buffs, "Wolf Speed Bonus", 0.5f,
new ConfigDescription("Speed multiplier bonus while in Wolf or Ulv form.", new AcceptableValueRange<float>(0f, 3f))); new ConfigDescription("Speed multiplier bonus while in Wolf form, the G form before Moder.", new AcceptableValueRange<float>(0f, 3f)));
UlvFormSpeedBonus = config.Bind(buffs, "Ulv Speed Bonus", 1.0f,
new ConfigDescription("Speed multiplier bonus while in Ulv form. The fastest form by default: the one to travel in.", new AcceptableValueRange<float>(0f, 3f)));
FenringDamageReduction = config.Bind(buffs, "Fenring Damage Reduction", 0.3f,
new ConfigDescription("Share of every hit the Fenring shrugs off. 0.3 = 30% less damage taken.", new AcceptableValueRange<float>(0f, 0.9f)));
CultistExtraDamageTaken = config.Bind(buffs, "Cultist Extra Damage Taken", 0.25f,
new ConfigDescription("How much harder hits land on the Cultist. 0.25 = 25% more damage taken.", new AcceptableValueRange<float>(0f, 2f)));
WolfFormFallDamageReduction = config.Bind(buffs, "Wolf Form Fall Damage Reduction", 0.5f, WolfFormFallDamageReduction = config.Bind(buffs, "Wolf Form Fall Damage Reduction", 0.5f,
new ConfigDescription("Fall damage reduction while in Wolf or Ulv form.", new AcceptableValueRange<float>(0f, 1f))); new ConfigDescription("Fall damage reduction while in Wolf or Ulv form.", new AcceptableValueRange<float>(0f, 1f)));
FormStaminaRegenMultiplier = config.Bind(buffs, "Stamina Regen Multiplier", 1.3f, FormStaminaRegenMultiplier = config.Bind(buffs, "Stamina Regen Multiplier", 1.3f,
@ -154,7 +183,7 @@ namespace RacesOfValheim
CultistClawDamage = config.Bind(cultist, "Claw Damage", 85f, CultistClawDamage = config.Bind(cultist, "Claw Damage", 85f,
new ConfigDescription("Base damage of the single claw (Left Mouse), before the Unarmed skill bonus.", new AcceptableValueRange<float>(0f, 500f))); new ConfigDescription("Base damage of the single claw (Left Mouse), before the Unarmed skill bonus.", new AcceptableValueRange<float>(0f, 500f)));
CultistDoubleClawDamage = config.Bind(cultist, "Double Claw Damage", 140f, CultistDoubleClawDamage = config.Bind(cultist, "Double Claw Damage", 140f,
new ConfigDescription("Base damage of the double claw (Middle Mouse), before the Unarmed skill bonus.", new AcceptableValueRange<float>(0f, 500f))); new ConfigDescription("Base damage of the double claw (Middle Mouse), before the Unarmed skill bonus. Each of its two swipes deals 60% of it.", new AcceptableValueRange<float>(0f, 500f)));
CultistAttackRadius = config.Bind(cultist, "Claw Attack Radius", 2.5f, CultistAttackRadius = config.Bind(cultist, "Claw Attack Radius", 2.5f,
new ConfigDescription("Hit-sweep radius for both claw attacks.", new AcceptableValueRange<float>(1f, 10f))); new ConfigDescription("Hit-sweep radius for both claw attacks.", new AcceptableValueRange<float>(1f, 10f)));
CultistPushForce = config.Bind(cultist, "Claw Push Force", 30f, CultistPushForce = config.Bind(cultist, "Claw Push Force", 30f,
@ -194,6 +223,35 @@ namespace RacesOfValheim
UlvPushForce = config.Bind(ulv, "Push Force", 25f, UlvPushForce = config.Bind(ulv, "Push Force", 25f,
new ConfigDescription("Knockback applied on a hit.", new AcceptableValueRange<float>(0f, 100f))); new ConfigDescription("Knockback applied on a hit.", new AcceptableValueRange<float>(0f, 100f)));
// Form attack stamina, beside each form's damage. Lower than a weapon's on purpose: the
// forms pay less per swing and fill the adrenaline bar faster instead (Form Adrenaline
// Multiplier). For scale, vanilla fists cost 4, Bjorn claws 6, Fenris claws 10.
const string staminaNote = " Base stamina, cut by up to a third with the Unarmed skill as a weapon's is. 0 makes it free.";
FormAdrenalineMultiplier = config.Bind(buffs, "Form Adrenaline Multiplier", 1.5f,
new ConfigDescription("Adrenaline per form hit, times the bare-handed amount, in any Fenrir form.", new AcceptableValueRange<float>(0f, 5f)));
FenringLightClawStamina = config.Bind(fenring, "Light Claw Stamina", 6f,
new ConfigDescription("Stamina for the light claw (Left Mouse)." + staminaNote, new AcceptableValueRange<float>(0f, 50f)));
FenringHeavyClawStamina = config.Bind(fenring, "Heavy Claw Stamina", 10f,
new ConfigDescription("Stamina for the heavy claw (Right Mouse)." + staminaNote, new AcceptableValueRange<float>(0f, 50f)));
FenringJumpAttackStamina = config.Bind(fenring, "Jump Attack Stamina", 16f,
new ConfigDescription("Stamina for the leaping attack (Middle Mouse)." + staminaNote, new AcceptableValueRange<float>(0f, 50f)));
CultistClawStamina = config.Bind(cultist, "Claw Stamina", 6f,
new ConfigDescription("Stamina for the single claw (Left Mouse)." + staminaNote, new AcceptableValueRange<float>(0f, 50f)));
CultistDoubleClawStamina = config.Bind(cultist, "Double Claw Stamina", 12f,
new ConfigDescription("Stamina for the double claw (Middle Mouse)." + staminaNote, new AcceptableValueRange<float>(0f, 50f)));
WolfAttack1Stamina = config.Bind(wolf, "Attack 1 Stamina", 4f,
new ConfigDescription("Stamina for the Left Mouse attack." + staminaNote, new AcceptableValueRange<float>(0f, 50f)));
WolfAttack2Stamina = config.Bind(wolf, "Attack 2 Stamina", 6f,
new ConfigDescription("Stamina for the Right Mouse attack." + staminaNote, new AcceptableValueRange<float>(0f, 50f)));
WolfAttack3Stamina = config.Bind(wolf, "Attack 3 Stamina", 10f,
new ConfigDescription("Stamina for the Middle Mouse attack." + staminaNote, new AcceptableValueRange<float>(0f, 50f)));
UlvBiteStamina = config.Bind(ulv, "Bite Stamina", 5f,
new ConfigDescription("Stamina for the Left Mouse bite." + staminaNote, new AcceptableValueRange<float>(0f, 50f)));
UlvHeavyBiteStamina = config.Bind(ulv, "Heavy Bite Stamina", 8f,
new ConfigDescription("Stamina for the Right Mouse bite." + staminaNote, new AcceptableValueRange<float>(0f, 50f)));
UlvJumpAttackStamina = config.Bind(ulv, "Jump Attack Stamina", 14f,
new ConfigDescription("Stamina for the leaping Middle Mouse attack." + staminaNote, new AcceptableValueRange<float>(0f, 50f)));
// The whole section stays local - see ConfigSync.LocalSections. // The whole section stays local - see ConfigSync.LocalSections.
const string appearance = "Fenrir - Appearance"; const string appearance = "Fenrir - Appearance";
ReadyMessage = config.Bind(appearance, "Ready Message", true, ReadyMessage = config.Bind(appearance, "Ready Message", true,
@ -207,10 +265,6 @@ namespace RacesOfValheim
// Tried at 1.2 in game: the orange was too strong. 0.9 checked and kept. // 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, EyeReadyStrength = config.Bind(appearance, "Eye Ready Strength", 0.9f,
new ConfigDescription("Glow at night while a form is ready.", new AcceptableValueRange<float>(0f, 3f))); new ConfigDescription("Glow at night while a form is ready.", new AcceptableValueRange<float>(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."));
} }
/// <summary> /// <summary>

View file

@ -18,6 +18,16 @@ namespace RacesOfValheim
/// form's own routines, and on every revert.</summary> /// form's own routines, and on every revert.</summary>
public static bool LocalAttacking { get; set; } public static bool LocalAttacking { get; set; }
/// <summary>
/// How many hit events the local form's clips have fired: the creature's own "Hit" event,
/// which CharacterAnimEvent hands to the player's OnAttackTrigger, and BlockPlayerAttackTriggerPatch
/// counts here instead of letting it through. A swing waits for this to move, so its damage
/// lands on the clip's own blow (TrolTrueFormModel.AttackEvents, the same idea).
/// </summary>
public static int AttackEvents { get; private set; }
public static void NotifyAttackTrigger() => AttackEvents++;
public static bool LocalInForm(Character character) public static bool LocalInForm(Character character)
{ {
if (character == null || character != Player.m_localPlayer) return false; if (character == null || character != Player.m_localPlayer) return false;
@ -332,7 +342,7 @@ namespace RacesOfValheim
/// </summary> /// </summary>
public static void LogMiss(string form, Collider hit, string reason) public static void LogMiss(string form, Collider hit, string reason)
{ {
if (!FenrirConfig.DebugFormHits.Value) return; if (!DebugConfig.LogFormHits.Value) return;
Jotunn.Logger.LogInfo($"[FenrirForm] {form} swing skipped '{hit.name}' (layer {LayerMask.LayerToName(hit.gameObject.layer)}): {reason}."); Jotunn.Logger.LogInfo($"[FenrirForm] {form} swing skipped '{hit.name}' (layer {LayerMask.LayerToName(hit.gameObject.layer)}): {reason}.");
} }
@ -353,19 +363,87 @@ namespace RacesOfValheim
ItemDrop unarmed = player.m_unarmedWeapon; ItemDrop unarmed = player.m_unarmedWeapon;
float perHit = unarmed != null ? unarmed.m_itemData.m_shared.m_attack.m_attackAdrenaline : 1f; float perHit = unarmed != null ? unarmed.m_itemData.m_shared.m_attack.m_attackAdrenaline : 1f;
// The Fenrir forms trade cheaper swings for a faster bar; the other races' forms do not.
if (FenrirForms.LocalInForm(player)) perHit *= FenrirConfig.FormAdrenalineMultiplier.Value;
player.AddAdrenaline(perHit * character.m_enemyAdrenalineMultiplier * scale); player.AddAdrenaline(perHit * character.m_enemyAdrenalineMultiplier * scale);
} }
/// <summary>
/// The skill experience vanilla gives for a weapon hit, which a hand-built hit never got.
/// Vanilla raises the skill inside Attack (once per swing that landed on a creature) and
/// inside Projectile.OnHit; Character.Damage never does, so a form that calls Damage
/// directly left its skill at whatever level the player brought in. Call it once per
/// swing or tick, after the loop, never once per target. amount lets a damage-over-time
/// tick pay a fraction of a swing.
/// </summary>
public static void RaiseSkill(Skills.SkillType skill, float amount = 1f)
{
Player player = Player.m_localPlayer;
if (player == null || amount <= 0f) return;
player.RaiseSkill(skill, amount);
}
/// <summary>
/// Charges a form attack's stamina the way vanilla charges a weapon's (Attack.GetAttackStamina):
/// the equipment modifier, status effects (meads, race passives), then up to a third off with
/// the attack's skill. Without enough, the attack does not start and the stamina bar flashes,
/// as it does for a weapon. A cost of 0 is free and always goes through.
/// A staggered player cannot attack at all, and an attack that may start is marked for
/// FormStagger, so a stagger before its hit cancels it.
/// </summary>
/// <returns>True if the attack may start; the stamina is already spent.</returns>
public static bool TrySpendStamina(Player player, float baseCost, Skills.SkillType skill)
{
if (player != null && player.IsStaggering()) return false;
FormStagger.MarkAttack();
if (player == null || baseCost <= 0f) return true;
float cost = baseCost * (1f + player.GetEquipmentAttackStaminaModifier());
player.GetSEMan().ModifyAttackStaminaUsage(cost, ref cost);
cost -= cost * 0.33f * player.GetSkillFactor(skill);
if (cost <= 0f) return true;
if (!player.HaveStamina(cost + 0.1f))
{
if (player == Player.m_localPlayer && Hud.instance != null) Hud.instance.StaminaBarEmptyFlash();
return false;
}
player.UseStamina(cost);
return true;
}
private static readonly System.Collections.Generic.Dictionary<string, ItemDrop.ItemData.SharedData> weapons =
new System.Collections.Generic.Dictionary<string, ItemDrop.ItemData.SharedData>();
/// <summary>
/// A creature's own attack item (dragon_bite, SeekerBrute_ram...), read once and cached,
/// null if the game has none by that name. A hand-built swing skips Attack, and Attack is
/// where vanilla plays the item's m_triggerEffect and m_hitEffect, so a form that wants the
/// creature's real swing and impact sounds plays them from here.
/// </summary>
public static ItemDrop.ItemData.SharedData CreatureWeapon(string prefabName)
{
if (string.IsNullOrEmpty(prefabName)) return null;
if (weapons.TryGetValue(prefabName, out ItemDrop.ItemData.SharedData cached)) return cached;
GameObject prefab = Jotunn.Managers.PrefabManager.Cache.GetPrefab<GameObject>(prefabName);
ItemDrop.ItemData.SharedData shared = prefab != null ? prefab.GetComponent<ItemDrop>()?.m_itemData?.m_shared : null;
if (shared == null) Jotunn.Logger.LogWarning($"[FormMelee] No attack item '{prefabName}'; that swing stays silent.");
weapons[prefabName] = shared;
return shared;
}
public static void LogHit(string form, IDestructible target, float damage) public static void LogHit(string form, IDestructible target, float damage)
{ {
if (!FenrirConfig.DebugFormHits.Value) return; if (!DebugConfig.LogFormHits.Value) return;
string name = target is MonoBehaviour behaviour && behaviour != null ? behaviour.name : target.ToString(); string name = target is MonoBehaviour behaviour && behaviour != null ? behaviour.name : target.ToString();
Jotunn.Logger.LogInfo($"[FenrirForm] {form} swing hit '{name}' for {damage:0}."); Jotunn.Logger.LogInfo($"[FenrirForm] {form} swing hit '{name}' for {damage:0}.");
} }
public static void LogSwing(string form, int candidates) public static void LogSwing(string form, int candidates)
{ {
if (!FenrirConfig.DebugFormHits.Value) return; if (!DebugConfig.LogFormHits.Value) return;
Jotunn.Logger.LogInfo($"[FenrirForm] {form} swing: {candidates} collider(s) in reach."); Jotunn.Logger.LogInfo($"[FenrirForm] {form} swing: {candidates} collider(s) in reach.");
} }
} }

View file

@ -56,7 +56,9 @@ namespace RacesOfValheim
{ {
public static bool Prefix(Humanoid __instance) public static bool Prefix(Humanoid __instance)
{ {
return !FenrirForms.LocalInForm(__instance); if (!FenrirForms.LocalInForm(__instance)) return true;
FenrirForms.NotifyAttackTrigger();
return false;
} }
} }

View file

@ -76,7 +76,7 @@ namespace RacesOfValheim {
cultistCdSE.m_icon = fenringTrophyIcon; cultistCdSE.m_icon = fenringTrophyIcon;
ItemManager.Instance.AddStatusEffect(new CustomStatusEffect(cultistCdSE, fixReference: false)); ItemManager.Instance.AddStatusEffect(new CustomStatusEffect(cultistCdSE, fixReference: false));
formBuffSE = ScriptableObject.CreateInstance<SE_Stats>(); formBuffSE = ScriptableObject.CreateInstance<SE_FenrirFormBuff>();
formBuffSE.name = "SE_FenrirForm"; formBuffSE.name = "SE_FenrirForm";
formBuffSE.m_name = "$rov_se_fenrir_form_name"; formBuffSE.m_name = "$rov_se_fenrir_form_name";
formBuffSE.m_speedModifier = FenrirConfig.FullFormSpeedBonus.Value; formBuffSE.m_speedModifier = FenrirConfig.FullFormSpeedBonus.Value;
@ -87,7 +87,7 @@ namespace RacesOfValheim {
formBuffSE.m_icon = fenringTrophyIcon; formBuffSE.m_icon = fenringTrophyIcon;
ItemManager.Instance.AddStatusEffect(new CustomStatusEffect(formBuffSE, fixReference: false)); ItemManager.Instance.AddStatusEffect(new CustomStatusEffect(formBuffSE, fixReference: false));
cultistFormBuffSE = ScriptableObject.CreateInstance<SE_Stats>(); cultistFormBuffSE = ScriptableObject.CreateInstance<SE_FenrirFormBuff>();
cultistFormBuffSE.name = "SE_CultistForm"; cultistFormBuffSE.name = "SE_CultistForm";
cultistFormBuffSE.m_name = "$rov_se_fenrir_cultistform_name"; cultistFormBuffSE.m_name = "$rov_se_fenrir_cultistform_name";
cultistFormBuffSE.m_speedModifier = FenrirConfig.FullFormSpeedBonus.Value; cultistFormBuffSE.m_speedModifier = FenrirConfig.FullFormSpeedBonus.Value;
@ -98,7 +98,7 @@ namespace RacesOfValheim {
cultistFormBuffSE.m_icon = fenringTrophyIcon; cultistFormBuffSE.m_icon = fenringTrophyIcon;
ItemManager.Instance.AddStatusEffect(new CustomStatusEffect(cultistFormBuffSE, fixReference: false)); ItemManager.Instance.AddStatusEffect(new CustomStatusEffect(cultistFormBuffSE, fixReference: false));
wolfFormBuffSE = ScriptableObject.CreateInstance<SE_Stats>(); wolfFormBuffSE = ScriptableObject.CreateInstance<SE_FenrirFormBuff>();
wolfFormBuffSE.name = "SE_WolfForm"; wolfFormBuffSE.name = "SE_WolfForm";
wolfFormBuffSE.m_name = "$rov_se_fenrir_wolfform_name"; wolfFormBuffSE.m_name = "$rov_se_fenrir_wolfform_name";
wolfFormBuffSE.m_speedModifier = FenrirConfig.WolfFormSpeedBonus.Value; wolfFormBuffSE.m_speedModifier = FenrirConfig.WolfFormSpeedBonus.Value;
@ -109,6 +109,16 @@ namespace RacesOfValheim {
ItemManager.Instance.AddStatusEffect(new CustomStatusEffect(wolfFormBuffSE, fixReference: false)); ItemManager.Instance.AddStatusEffect(new CustomStatusEffect(wolfFormBuffSE, fixReference: false));
} }
// Set on the live copy each time a form is taken, not on the registered template: the Wolf
// and the Ulv share SE_WolfForm but not a speed, and a changed value applies at the next
// transform instead of after a relog.
private static void SetFormBuff(StatusEffect se, float speedBonus, float damageTakenFactor)
{
if (!(se is SE_FenrirFormBuff buff)) return;
buff.m_speedModifier = speedBonus;
buff.m_damageTakenFactor = damageTakenFactor;
}
private void Update() private void Update()
{ {
if (Player.m_localPlayer == null || EnvMan.instance == null) return; if (Player.m_localPlayer == null || EnvMan.instance == null) return;
@ -164,6 +174,10 @@ namespace RacesOfValheim {
} }
} }
// The hunter's senses, shared with the Aswid: every form has them, the human does not.
if (isTransformed) HunterSenses.Tick(FenrirConfig.SensesRadius.Value);
else HunterSenses.Clear();
if (!RaceInput.Allowed) return; if (!RaceInput.Allowed) return;
int state = BossProgressionManager.GetCurrentProgressionState(); int state = BossProgressionManager.GetCurrentProgressionState();
@ -412,6 +426,7 @@ namespace RacesOfValheim {
private IEnumerator RevertToHumanRoutine() private IEnumerator RevertToHumanRoutine()
{ {
isTransformingSequence = true; isTransformingSequence = true;
HunterSenses.Clear();
if (currentTransformation != null) if (currentTransformation != null)
{ {
@ -545,6 +560,7 @@ namespace RacesOfValheim {
Player.m_localPlayer.GetSEMan().AddStatusEffect("SE_WolfForm".GetStableHashCode(), true); Player.m_localPlayer.GetSEMan().AddStatusEffect("SE_WolfForm".GetStableHashCode(), true);
var se = Player.m_localPlayer.GetSEMan().GetStatusEffect("SE_WolfForm".GetStableHashCode()); var se = Player.m_localPlayer.GetSEMan().GetStatusEffect("SE_WolfForm".GetStableHashCode());
if (se != null) se.m_ttl = ttl; if (se != null) se.m_ttl = ttl;
SetFormBuff(se, FenrirConfig.UlvFormSpeedBonus.Value, 1f);
Player.m_localPlayer.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_fenrir_are_ulv")); Player.m_localPlayer.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_fenrir_are_ulv"));
} }
else if (prefabName == "Wolf") else if (prefabName == "Wolf")
@ -553,6 +569,7 @@ namespace RacesOfValheim {
Player.m_localPlayer.GetSEMan().AddStatusEffect("SE_WolfForm".GetStableHashCode(), true); Player.m_localPlayer.GetSEMan().AddStatusEffect("SE_WolfForm".GetStableHashCode(), true);
var se = Player.m_localPlayer.GetSEMan().GetStatusEffect("SE_WolfForm".GetStableHashCode()); var se = Player.m_localPlayer.GetSEMan().GetStatusEffect("SE_WolfForm".GetStableHashCode());
if (se != null) se.m_ttl = ttl; if (se != null) se.m_ttl = ttl;
SetFormBuff(se, FenrirConfig.WolfFormSpeedBonus.Value, 1f);
Player.m_localPlayer.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_fenrir_are_wolf")); Player.m_localPlayer.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_fenrir_are_wolf"));
} }
else if (prefabName == "Fenring_Cultist") else if (prefabName == "Fenring_Cultist")
@ -561,6 +578,7 @@ namespace RacesOfValheim {
Player.m_localPlayer.GetSEMan().AddStatusEffect("SE_CultistForm".GetStableHashCode(), true); Player.m_localPlayer.GetSEMan().AddStatusEffect("SE_CultistForm".GetStableHashCode(), true);
var se = Player.m_localPlayer.GetSEMan().GetStatusEffect("SE_CultistForm".GetStableHashCode()); var se = Player.m_localPlayer.GetSEMan().GetStatusEffect("SE_CultistForm".GetStableHashCode());
if (se != null) se.m_ttl = ttl; if (se != null) se.m_ttl = ttl;
SetFormBuff(se, FenrirConfig.FullFormSpeedBonus.Value, 1f + FenrirConfig.CultistExtraDamageTaken.Value);
Player.m_localPlayer.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_fenrir_are_cultist")); Player.m_localPlayer.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_fenrir_are_cultist"));
} }
else else
@ -569,6 +587,7 @@ namespace RacesOfValheim {
Player.m_localPlayer.GetSEMan().AddStatusEffect("SE_FenrirForm".GetStableHashCode(), true); Player.m_localPlayer.GetSEMan().AddStatusEffect("SE_FenrirForm".GetStableHashCode(), true);
var se = Player.m_localPlayer.GetSEMan().GetStatusEffect("SE_FenrirForm".GetStableHashCode()); var se = Player.m_localPlayer.GetSEMan().GetStatusEffect("SE_FenrirForm".GetStableHashCode());
if (se != null) se.m_ttl = ttl; if (se != null) se.m_ttl = ttl;
SetFormBuff(se, FenrirConfig.FullFormSpeedBonus.Value, 1f - FenrirConfig.FenringDamageReduction.Value);
Player.m_localPlayer.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_fenrir_are_fenring")); Player.m_localPlayer.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_fenrir_are_fenring"));
} }

View file

@ -22,6 +22,23 @@ namespace RacesOfValheim
} }
} }
/// <summary>
/// A form's buff, plus a scale on the hits it takes: the Fenring holds the line on less, the
/// Cultist pays for its fire with more. SEMan.OnDamaged runs in Character.RPC_Damage on the
/// owner's machine, ahead of armor and the health loss, so the scale reaches every hit,
/// whoever's machine the attacker is on.
/// </summary>
public class SE_FenrirFormBuff : SE_Stats
{
public float m_damageTakenFactor = 1f;
public override void OnDamaged(HitData hit, Character attacker)
{
base.OnDamaged(hit, attacker);
if (!Mathf.Approximately(m_damageTakenFactor, 1f)) hit.ApplyModifier(m_damageTakenFactor);
}
}
public class SE_FenrirCurse : SE_Stats public class SE_FenrirCurse : SE_Stats
{ {
public override void Setup(Character character) public override void Setup(Character character)

View file

@ -0,0 +1,167 @@
using System.Collections.Generic;
using HarmonyLib;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// The lights a player wears - the Dvergr circlet's headlamp, a torch in hand - follow the form
/// the player has taken.
///
/// A form hides the human body and leaves it standing where it was: PlayerVisualHider turns its
/// renderers off, the Muspell shrinks the Visual to nothing. Either way the gear stays on the
/// body's bones, and a Light is not a renderer, so the headlamp kept shining from the hidden
/// human's head: at a person's height inside a troll's chest, from the feet of a Muspell. A
/// tester saw it stuck where the head had been before the transformation.
///
/// While the body is hidden, every Light under it is put at the form's head bone, a little in
/// front of it. A form with no bone called "head" gets the top front of its own model instead,
/// and with no form model at all the light sits centre-forward at a person's head height. The
/// lights go back to their own places the moment the body shows again.
///
/// Run for every player, not only the local one: the headlamp lights the world for onlookers too.
/// </summary>
public class FormLightFollow : MonoBehaviour
{
// Lights and the form's head are looked up again this often: VisEquipment rebuilds gear,
// and a form can be built a frame after the body is hidden.
private const float RescanInterval = 0.25f;
// RaceEyeHeight's reading of a Visual this small: hidden, not small.
private const float HiddenScale = 0.05f;
// Ahead of the head bone, so the lamp does not light the skull from inside.
private const float AheadOfHead = 0.3f;
// No form model at all: centre-forward, where a person's headlamp would be.
private static readonly Vector3 FallbackOffset = new Vector3(0f, 1.6f, 0.4f);
private static readonly AccessTools.FieldRef<Character, GameObject> VisualRef =
AccessTools.FieldRefAccess<Character, GameObject>("m_visual");
// Each light moved, with the local position it goes back to.
private readonly Dictionary<Light, Vector3> moved = new Dictionary<Light, Vector3>();
private readonly List<Light> dead = new List<Light>();
private float nextScan;
private Transform head;
private Vector3 anchorOffset = FallbackOffset; // player-local, used when there is no head
public static void Tick(Player player)
{
GameObject visual = VisualRef(player);
if (visual == null) return;
bool hidden = PlayerVisualHider.IsHidden(visual.transform) || visual.transform.localScale.y < HiddenScale;
FormLightFollow follow = visual.GetComponent<FormLightFollow>();
if (!hidden)
{
if (follow != null && follow.moved.Count > 0) follow.Restore();
return;
}
if (follow == null) follow = visual.AddComponent<FormLightFollow>();
follow.Follow(player);
}
private void Follow(Player player)
{
if (Time.time >= nextScan)
{
nextScan = Time.time + RescanInterval;
Scan(player);
}
Transform body = player.transform;
Vector3 anchor = head != null
? head.position + body.forward * AheadOfHead
: body.TransformPoint(anchorOffset);
foreach (Light light in moved.Keys)
{
if (light != null) light.transform.position = anchor;
}
}
private void Scan(Player player)
{
dead.Clear();
foreach (Light light in moved.Keys)
{
if (light == null) dead.Add(light);
}
foreach (Light light in dead) moved.Remove(light);
foreach (Light light in GetComponentsInChildren<Light>(true))
{
if (!moved.ContainsKey(light)) moved.Add(light, light.transform.localPosition);
}
if (moved.Count == 0) return;
if (head == null || !head.gameObject.activeInHierarchy) FindForm(player);
}
/// <summary>
/// The form's model is a child of the player beside the Visual (every form builds it that
/// way). Its head bone, if it has one; otherwise the top front of its renderers.
/// </summary>
private void FindForm(Player player)
{
head = null;
anchorOffset = FallbackOffset;
Transform body = player.transform;
foreach (Transform child in body)
{
if (child == transform || !child.gameObject.activeInHierarchy) continue;
if (child.GetComponentInChildren<Animator>() == null) continue;
head = FindHead(child);
if (head != null) return;
Bounds bounds = default;
bool any = false;
foreach (Renderer r in child.GetComponentsInChildren<Renderer>())
{
if (!(r is SkinnedMeshRenderer) && !(r is MeshRenderer)) continue;
if (any) bounds.Encapsulate(r.bounds); else { bounds = r.bounds; any = true; }
}
if (!any) continue;
Vector3 local = body.InverseTransformPoint(bounds.center);
Vector3 size = body.InverseTransformVector(bounds.extents);
anchorOffset = new Vector3(local.x, local.y + Mathf.Abs(size.y) * 0.6f, local.z + Mathf.Abs(size.z) * 0.6f);
return;
}
}
private static Transform FindHead(Transform root)
{
foreach (Transform t in root.GetComponentsInChildren<Transform>())
{
if (string.Equals(t.name, "head", System.StringComparison.OrdinalIgnoreCase)) return t;
}
return null;
}
private void Restore()
{
foreach (KeyValuePair<Light, Vector3> entry in moved)
{
if (entry.Key != null) entry.Key.transform.localPosition = entry.Value;
}
moved.Clear();
head = null;
}
/// <summary>LateUpdate, so the form's Animator has already posed the head this frame.</summary>
[HarmonyPatch(typeof(Player), "LateUpdate")]
public static class Player_LateUpdate_FormLightFollow_Patch
{
public static void Postfix(Player __instance)
{
Tick(__instance);
}
}
}
}

View file

@ -0,0 +1,95 @@
using System.Collections.Generic;
using HarmonyLib;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// A staggered player in a form plays the form's own stagger.
///
/// Vanilla staggers a character with SetTrigger("stagger") on its own Animator (Character.RPC_Stagger),
/// and that Animator belongs to the hidden human. The form's Animator never heard of it, so the
/// True Form troll stood idle while the player could not move. A tester saw it.
///
/// Every creature worn as a form has the vanilla stagger ready to play (read offline with
/// scripts/dump_controller.py, bundle c4210710): a "stagger" trigger and an AnyState -> Stagger
/// transition in troll_animator, fenring_animator, fenring_cultist_animator, wolf_animator,
/// ulv_animator, SeekerBrute_animator (the Sverm Ravager) and bat_animator (the Aswid bat).
/// gd_king_animator (the Muspell) and hatchling_animator (the Skadi drake) have none, and are
/// left alone by the parameter check.
///
/// The cue is Character.IsStaggering(), which reads the player's Animator state. The player's
/// triggers are replicated, so this holds for onlookers' copies of the form too, with nothing
/// published of its own. Fired once, as the stagger starts.
///
/// A stagger also cancels the local form's attack, as it cancels a weapon's in vanilla. The
/// form's swing waits for its clip's hit event and lands on a timeout if none comes, so a
/// stagger that cut the clip short still dealt the blow 1.5 s later. MarkAttack is called as an
/// attack starts, and AttackInterrupted tells the hit whether a stagger began since.
/// </summary>
internal static class FormStagger
{
private const string Trigger = "stagger";
private static readonly AccessTools.FieldRef<Character, Animator> AnimatorRef =
AccessTools.FieldRefAccess<Character, Animator>("m_animator");
private static readonly HashSet<int> staggering = new HashSet<int>();
private static readonly List<Animator> animators = new List<Animator>();
// Staggers of the local player so far, and the count when the current attack started.
private static int localStaggers;
private static int attackMark;
public static void MarkAttack() => attackMark = localStaggers;
/// <summary>True if the local player has been staggered since the last MarkAttack.</summary>
public static bool AttackInterrupted => localStaggers != attackMark;
public static void Tick(Player player)
{
int id = player.GetInstanceID();
if (!player.IsStaggering())
{
staggering.Remove(id);
return;
}
if (!staggering.Add(id)) return;
if (player == Player.m_localPlayer) localStaggers++;
Animator own = AnimatorRef(player);
RuntimeAnimatorController ownController = own != null ? own.runtimeAnimatorController : null;
player.GetComponentsInChildren(false, animators);
foreach (Animator anim in animators)
{
// The human's own Animator staggers already, and so does anything driven by a copy of
// its controller (a VRM model).
if (anim == own || anim.runtimeAnimatorController == null) continue;
if (anim.runtimeAnimatorController == ownController) continue;
if (!anim.isActiveAndEnabled || !HasTrigger(anim)) continue;
anim.SetTrigger(Trigger);
}
animators.Clear();
}
private static bool HasTrigger(Animator anim)
{
foreach (AnimatorControllerParameter p in anim.parameters)
{
if (p.type == AnimatorControllerParameterType.Trigger && p.name == Trigger) return true;
}
return false;
}
[HarmonyPatch(typeof(Player), "LateUpdate")]
public static class Player_LateUpdate_FormStagger_Patch
{
public static void Postfix(Player __instance)
{
FormStagger.Tick(__instance);
}
}
}
}

View file

@ -0,0 +1,92 @@
using System;
using System.Collections.Generic;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// The hunter's senses the Aswid and the Fenrir share: every untamed creature within a radius
/// gets a green light, seen only by the local player. The Aswid has it as a passive from Moder,
/// the Fenrir in any of its four forms.
///
/// The lights are local GameObjects parented to the creature, so nothing goes on the network.
/// The light's range and strength are the Aswid's settings; each race brings its own radius.
/// </summary>
public static class HunterSenses
{
private static readonly Dictionary<Character, GameObject> lights = new Dictionary<Character, GameObject>();
private static float timer;
/// <summary>
/// Called every frame while the senses are on. Sweeps once per refresh interval;
/// onSensed runs for each creature in range (the Aswid marks them with its status effect).
/// </summary>
public static void Tick(float radius, Action<Character> onSensed = null)
{
Player player = Player.m_localPlayer;
if (player == null) return;
timer -= Time.deltaTime;
if (timer > 0f) return;
timer = AswidConfig.SensesRefreshInterval.Value;
Vector3 myPos = player.transform.position;
HashSet<Character> inRange = new HashSet<Character>();
foreach (Character c in Character.GetAllCharacters())
{
if (c == null || c == player || c.IsDead() || c.IsTamed()) continue;
if (Vector3.Distance(c.transform.position, myPos) > radius) continue;
try
{
inRange.Add(c);
onSensed?.Invoke(c);
if (!lights.ContainsKey(c))
{
GameObject lightObj = new GameObject("AswidSensesLight");
lightObj.transform.SetParent(c.transform);
lightObj.transform.position = c.GetCenterPoint();
Light pLight = lightObj.AddComponent<Light>();
pLight.type = LightType.Point;
pLight.color = Color.green;
pLight.range = AswidConfig.SensesLightRange.Value;
pLight.intensity = AswidConfig.SensesLightIntensity.Value;
pLight.shadows = LightShadows.None;
lights[c] = lightObj;
}
}
catch (Exception ex)
{
Jotunn.Logger.LogError($"[Senses] Error processing mob {c.name}: {ex}");
}
}
List<Character> keysToRemove = new List<Character>();
foreach (var kvp in lights)
{
if (kvp.Key == null || kvp.Key.IsDead() || !inRange.Contains(kvp.Key))
{
if (kvp.Value != null) UnityEngine.Object.Destroy(kvp.Value);
keysToRemove.Add(kvp.Key);
}
}
foreach (var k in keysToRemove) lights.Remove(k);
}
/// <summary>Puts every light out, for when the senses end (a form reverts, a tier is lost).</summary>
public static void Clear()
{
if (lights.Count == 0) return;
foreach (var kvp in lights)
{
if (kvp.Value != null) UnityEngine.Object.Destroy(kvp.Value);
}
lights.Clear();
timer = 0f;
}
}
}

View file

@ -36,10 +36,13 @@ namespace RacesOfValheim
/// <paramref name="localPosition"/> is where the model's BOTTOM CENTRE goes. /// <paramref name="localPosition"/> is where the model's BOTTOM CENTRE goes.
/// <paramref name="targetSize"/> is how big its largest dimension should end up, in metres, /// <paramref name="targetSize"/> is how big its largest dimension should end up, in metres,
/// measured AFTER <paramref name="localRotation"/> has been applied. /// measured AFTER <paramref name="localRotation"/> has been applied.
/// <paramref name="activeOnly"/> drops every child the source keeps switched off before measuring.
/// A build piece carries its snow cover, its fire, its worn and broken meshes that way, and they
/// count towards the size: the cauldron's hidden tripod legs are two metres long.
/// </summary> /// </summary>
public static GameObject Attach(Transform parent, string holderName, string sourcePrefab, public static GameObject Attach(Transform parent, string holderName, string sourcePrefab,
Vector3 localPosition, Quaternion localRotation, float targetSize, Vector3 localPosition, Quaternion localRotation, float targetSize,
string label) string label, bool activeOnly = false)
{ {
GameObject source = Jotunn.Managers.PrefabManager.Cache.GetPrefab<GameObject>(sourcePrefab); GameObject source = Jotunn.Managers.PrefabManager.Cache.GetPrefab<GameObject>(sourcePrefab);
if (source == null) if (source == null)
@ -52,7 +55,7 @@ namespace RacesOfValheim
return empty; return empty;
} }
return Attach(parent, holderName, source, localPosition, localRotation, targetSize, label); return Attach(parent, holderName, source, localPosition, localRotation, targetSize, label, activeOnly);
} }
/// <summary> /// <summary>
@ -66,7 +69,7 @@ namespace RacesOfValheim
/// </summary> /// </summary>
public static GameObject Attach(Transform parent, string holderName, GameObject source, public static GameObject Attach(Transform parent, string holderName, GameObject source,
Vector3 localPosition, Quaternion localRotation, float targetSize, Vector3 localPosition, Quaternion localRotation, float targetSize,
string label) string label, bool activeOnly = false)
{ {
GameObject holder = new GameObject(holderName); GameObject holder = new GameObject(holderName);
holder.transform.SetParent(parent, false); holder.transform.SetParent(parent, false);
@ -110,6 +113,16 @@ namespace RacesOfValheim
if (nview != null) Object.DestroyImmediate(nview); if (nview != null) Object.DestroyImmediate(nview);
} }
if (activeOnly)
{
foreach (Transform child in copy.GetComponentsInChildren<Transform>(true))
{
// Null once an inactive parent above it has already gone.
if (child == null || child == copy.transform || child.gameObject.activeSelf) continue;
Object.DestroyImmediate(child.gameObject);
}
}
FitAndGround(copy.transform, holder.transform, targetSize, sourcePrefab, label); FitAndGround(copy.transform, holder.transform, targetSize, sourcePrefab, label);
holder.SetActive(true); holder.SetActive(true);

View file

@ -1,7 +1,7 @@
{ {
"name": "RacesOfValheim", "name": "RacesOfValheim",
"description": "A Valheim mod that adds eleven custom playable races (Alfar, Aswid, Draugh, Dvergar, Fenrir, Furling, Skadi, Skeleton, Sverm, Trenta, Trol) each with unique abilities, traits, race stations and a deep boss-driven progression system.", "description": "A Valheim mod that adds eleven custom playable races (Alfar, 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.6.1", "version_number": "1.6.11",
"website_url": "", "website_url": "",
"dependencies": [ "dependencies": [
"denikson-BepInExPack_Valheim-5.4.2333", "denikson-BepInExPack_Valheim-5.4.2333",

197
JotunnModStub/PieceLook.cs Normal file
View file

@ -0,0 +1,197 @@
using System.Collections.Generic;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// Recolouring a cloned vanilla piece without touching the original.
///
/// A clone made by CreateClonedPrefab shares its MATERIALS with the vanilla prefab, so writing a
/// colour onto renderer.sharedMaterial would repaint every Ward or cartography table in the world.
/// Each material is copied once and the copy is written; renderers that shared one material before
/// share the one copy after, so the LOD, worn and broken meshes stay matched.
/// </summary>
public static class PieceLook
{
/// <summary>
/// Multiplies the base colour of every mesh under <paramref name="root"/>, inactive ones included
/// (a piece's worn and broken meshes are switched off until it takes damage). Particles are left
/// alone: that is what <see cref="Rehue"/> is for.
/// </summary>
public static void Tint(Transform root, Color tint)
{
if (root == null) return;
var copies = new Dictionary<Material, Material>();
foreach (Renderer renderer in root.GetComponentsInChildren<Renderer>(true))
{
if (renderer == null || renderer is ParticleSystemRenderer) continue;
Material[] materials = renderer.sharedMaterials;
for (int i = 0; i < materials.Length; i++)
{
Material copy = CopyOf(materials[i], copies);
if (copy == null) continue;
if (copy.HasProperty("_Color")) copy.SetColor("_Color", copy.GetColor("_Color") * tint);
materials[i] = copy;
}
renderer.sharedMaterials = materials;
}
}
/// <summary>
/// Swaps the hue of everything under <paramref name="root"/> that GLOWS - lights, particles and
/// any material with emission - for <paramref name="glow"/>, keeping each one's brightness.
///
/// Brightness is kept rather than overwritten because these values are not 0 to 1: the Ward's
/// sparks are authored at a colour of 2.0, and painting them a flat 1.0 blue would dim them by
/// half. A material whose emission is black does not glow and is skipped, so the Ward's stone
/// stays stone.
/// </summary>
public static void Rehue(Transform root, Color glow)
{
if (root == null) return;
foreach (Light light in root.GetComponentsInChildren<Light>(true))
{
if (light != null) light.color = glow;
}
foreach (ParticleSystem ps in root.GetComponentsInChildren<ParticleSystem>(true))
{
if (ps == null) continue;
ParticleSystem.MainModule main = ps.main;
main.startColor = new ParticleSystem.MinMaxGradient(glow);
}
var copies = new Dictionary<Material, Material>();
foreach (Renderer renderer in root.GetComponentsInChildren<Renderer>(true))
{
if (renderer == null) continue;
bool particles = renderer is ParticleSystemRenderer;
Material[] materials = renderer.sharedMaterials;
bool changed = false;
for (int i = 0; i < materials.Length; i++)
{
Material source = materials[i];
if (source == null) continue;
bool emits = source.HasProperty("_EmissionColor") && Brightness(source.GetColor("_EmissionColor")) > 0.01f;
if (!emits && !particles) continue;
Material copy = CopyOf(source, copies);
if (emits) Recolour(copy, "_EmissionColor", glow);
if (particles)
{
Recolour(copy, "_Color", glow);
Recolour(copy, "_TintColor", glow);
}
materials[i] = copy;
changed = true;
}
if (changed) renderer.sharedMaterials = materials;
}
}
/// <summary>
/// Swaps textures by the name of the texture they replace: every material under
/// <paramref name="root"/> that uses "Cartographer_d" gets <paramref name="replacements"/>'s
/// "Cartographer_d" instead, whichever slot it sits in. Materials are copied as in Tint.
/// </summary>
public static void Retexture(Transform root, IDictionary<string, Texture> replacements)
{
if (root == null) return;
var copies = new Dictionary<Material, Material>();
foreach (Renderer renderer in root.GetComponentsInChildren<Renderer>(true))
{
if (renderer == null || renderer is ParticleSystemRenderer) continue;
Material[] materials = renderer.sharedMaterials;
bool changed = false;
for (int i = 0; i < materials.Length; i++)
{
Material source = materials[i];
if (source == null) continue;
foreach (string property in source.GetTexturePropertyNames())
{
Texture current = source.GetTexture(property);
if (current == null || !replacements.TryGetValue(current.name, out Texture replacement)) continue;
Material copy = CopyOf(source, copies);
copy.SetTexture(property, replacement);
materials[i] = copy;
changed = true;
}
}
if (changed) renderer.sharedMaterials = materials;
}
}
/// <summary>
/// ImageConversion.LoadImage, found at run time. Its module is built against netstandard 2.1 and
/// this project targets net48, so referencing it at compile time fails the build (CS1705); the
/// game has the module loaded either way.
/// </summary>
private static readonly System.Reflection.MethodInfo LoadImage =
System.Type.GetType("UnityEngine.ImageConversion, UnityEngine.ImageConversionModule")
?.GetMethod("LoadImage", new[] { typeof(Texture2D), typeof(byte[]), typeof(bool) });
/// <summary>
/// A PNG embedded in the DLL (see the csproj's EmbeddedResource), or null with a warning.
/// <paramref name="linear"/> for anything that is data rather than colour - a normal map read
/// as sRGB comes out bent.
/// </summary>
public static Texture2D LoadTexture(string resource, bool linear = false)
{
using (System.IO.Stream stream = typeof(PieceLook).Assembly.GetManifestResourceStream(resource))
{
if (stream == null)
{
Jotunn.Logger.LogWarning($"No embedded texture '{resource}'.");
return null;
}
byte[] bytes = new byte[stream.Length];
int read = 0;
while (read < bytes.Length) read += stream.Read(bytes, read, bytes.Length - read);
Texture2D texture = new Texture2D(2, 2, TextureFormat.RGBA32, true, linear)
{
name = System.IO.Path.GetFileNameWithoutExtension(resource),
anisoLevel = 4,
};
if (LoadImage == null || !(bool)LoadImage.Invoke(null, new object[] { texture, bytes, true }))
{
Jotunn.Logger.LogWarning($"Embedded texture '{resource}' would not decode.");
return null;
}
return texture;
}
}
private static void Recolour(Material material, string property, Color glow)
{
if (!material.HasProperty(property)) return;
Color old = material.GetColor(property);
Color hue = glow * Brightness(old);
hue.a = old.a;
material.SetColor(property, hue);
}
private static float Brightness(Color colour) => Mathf.Max(colour.r, Mathf.Max(colour.g, colour.b));
private static Material CopyOf(Material source, Dictionary<Material, Material> copies)
{
if (source == null) return null;
if (!copies.TryGetValue(source, out Material copy))
{
copy = new Material(source) { name = source.name + "_rov" };
copies[source] = copy;
}
return copy;
}
}
}

View file

@ -516,6 +516,9 @@ namespace RacesOfValheim
if (state >= 2) if (state >= 2)
{ {
sb.AppendLine(ModText.Get("rov_compendium_aswid_bat_form_g_key_night")); sb.AppendLine(ModText.Get("rov_compendium_aswid_bat_form_g_key_night"));
if (AswidConfig.UsesFreeBatFlight())
sb.AppendLine(ModText.Get("rov_compendium_aswid_bat_free_flight"));
else
sb.AppendLine(ModText.Get("rov_compendium_aswid_bat_flight", sb.AppendLine(ModText.Get("rov_compendium_aswid_bat_flight",
AswidConfig.BatPoweredStaminaPerSecond.Value.ToString("0.#"), AswidConfig.BatPoweredStaminaPerSecond.Value.ToString("0.#"),
AswidConfig.BatSprintStaminaPerSecond.Value.ToString("0.#"))); AswidConfig.BatSprintStaminaPerSecond.Value.ToString("0.#")));
@ -586,7 +589,10 @@ namespace RacesOfValheim
sb.AppendLine(ModText.Get("rov_compendium_fenrir_cursed_claws_s_wolf_s", (RaceClawsConfig.DurationSeconds.Value).ToString("0"), (SvermClaws.GetDamagePercent(state) * 100f).ToString("0"))); sb.AppendLine(ModText.Get("rov_compendium_fenrir_cursed_claws_s_wolf_s", (RaceClawsConfig.DurationSeconds.Value).ToString("0"), (SvermClaws.GetDamagePercent(state) * 100f).ToString("0")));
if (state >= 3) if (state >= 3)
{
sb.AppendLine(ModText.Get("rov_compendium_fenrir_wolf_form_g_key_night")); sb.AppendLine(ModText.Get("rov_compendium_fenrir_wolf_form_g_key_night"));
sb.AppendLine(ModText.Get("rov_compendium_fenrir_senses_in_form", Mathf.RoundToInt(FenrirConfig.SensesRadius.Value)));
}
if (state >= 4) if (state >= 4)
{ {
@ -719,7 +725,18 @@ namespace RacesOfValheim
sb.AppendLine((state <= BossProgressionManager.MinState ? ModText.Get("rov_compendium_skeleton_stand_at_first_eight_standings") : ModText.Get("rov_compendium_skeleton_stand_at_eight_standings_earned", state, BossProgressionManager.GetBossTokenForState(state)))); sb.AppendLine((state <= BossProgressionManager.MinState ? ModText.Get("rov_compendium_skeleton_stand_at_first_eight_standings") : ModText.Get("rov_compendium_skeleton_stand_at_eight_standings_earned", state, BossProgressionManager.GetBossTokenForState(state))));
sb.AppendLine(ModText.Get("rov_compendium_skeleton_undead_diet")); sb.AppendLine(ModText.Get("rov_compendium_skeleton_undead_diet"));
bool eats = SkeletonConfig.EatsMortalFood.Value, tires = SkeletonConfig.FeelsFatigue.Value;
if (!eats && !tires)
{
sb.AppendLine(ModText.Get("rov_compendium_skeleton_no_hunger_moves_no_meal", (health).ToString("0"))); sb.AppendLine(ModText.Get("rov_compendium_skeleton_no_hunger_moves_no_meal", (health).ToString("0")));
}
else
{
// A player who picked one of the "Mortal Habits" reads what they actually have.
string diet = eats ? ModText.Get("rov_compendium_skeleton_diet_mortal") : ModText.Get("rov_compendium_skeleton_diet_bones", (health).ToString("0"));
string effort = tires ? ModText.Get("rov_compendium_skeleton_effort_mortal") : ModText.Get("rov_compendium_skeleton_effort_none");
sb.AppendLine(diet + " " + effort + "\n");
}
sb.AppendLine(ModText.Get("rov_compendium_skeleton_bones_blades")); sb.AppendLine(ModText.Get("rov_compendium_skeleton_bones_blades"));
sb.AppendLine(ModText.Get("rov_compendium_skeleton_blades_points_find_little_cut")); sb.AppendLine(ModText.Get("rov_compendium_skeleton_blades_points_find_little_cut"));
@ -857,8 +874,8 @@ namespace RacesOfValheim
int foodDuration = Mathf.RoundToInt(TrentaConfig.FoodDurationMultiplier); int foodDuration = Mathf.RoundToInt(TrentaConfig.FoodDurationMultiplier);
int purpleRainRadius = Mathf.RoundToInt(TrentaConfig.PurpleRainRadius); int purpleRainRadius = Mathf.RoundToInt(TrentaConfig.PurpleRainRadius);
int purpleRainHeal = Mathf.RoundToInt(TrentaConfig.PurpleRainHealAmount); int purpleRainHeal = Mathf.RoundToInt(TrentaConfig.PurpleRainHealFor(Player.m_localPlayer));
int purpleRainPoison = Mathf.RoundToInt(TrentaConfig.PurpleRainPoisonDamage); int purpleRainPoison = Mathf.RoundToInt(TrentaConfig.PurpleRainPoisonFor(Player.m_localPlayer));
int purpleRainCooldown = Mathf.RoundToInt(TrentaConfigManagement.PurpleRainCooldown.Value); int purpleRainCooldown = Mathf.RoundToInt(TrentaConfigManagement.PurpleRainCooldown.Value);
int purpleRainMuspellCooldown = Mathf.RoundToInt(TrentaConfigManagement.MuspellPurpleRainCooldown.Value); int purpleRainMuspellCooldown = Mathf.RoundToInt(TrentaConfigManagement.MuspellPurpleRainCooldown.Value);

View file

@ -25,11 +25,13 @@ namespace RacesOfValheim
/// which means everything downstream - acquiring, chasing, retaliating, giving up - is vanilla /// which means everything downstream - acquiring, chasing, retaliating, giving up - is vanilla
/// behaviour rather than anything reimplemented here. /// behaviour rather than anything reimplemented here.
/// ///
/// WHERE IT RUNS. On the client that owns the mob's AI, which is the only one whose UpdateTarget /// WHERE IT LIVES. On the creature's own ZDO: who it is angry at and until when, in network time.
/// matters and the only one that runs Character.ApplyDamage for it. BaseAI.OnDamaged is reached /// The AI that reads it runs on whichever machine owns the creature, and that can change in the
/// through the character's damage callback on exactly that machine, so the record is made where /// middle of a fight (the owner walks off or logs out). A grudge kept in one machine's memory
/// it will be read. Nothing is replicated and nothing needs to be: another client's copy of the /// went with it, and the new owner's copy of the creature made peace on its next UpdateTarget.
/// same mob is not the one deciding who it chases. /// On the ZDO the new owner reads the same grudge. Only the owner writes it: a hit reaches the
/// owner through Character.Damage's RPC anyway, and kin owned elsewhere are told by an RPC of
/// our own (RpcName), so no client writes a ZDO it does not own.
/// ///
/// Vanilla has its own version of this idea in BaseAI.SetAggravated, and it is not usable here: /// Vanilla has its own version of this idea in BaseAI.SetAggravated, and it is not usable here:
/// it does nothing unless the prefab sets m_aggravatable, which only the dvergr and the seekers /// it does nothing unless the prefab sets m_aggravatable, which only the dvergr and the seekers
@ -37,67 +39,96 @@ namespace RacesOfValheim
/// </summary> /// </summary>
public static class RaceGrudge public static class RaceGrudge
{ {
private struct Grudge private const string RpcName = "RacesOfValheim_Grudge";
{
public ZDOID Attacker;
public float Until;
}
// One grudge per mob, against the last thing that hit it. A creature can only chase one // One grudge per creature, against the last player that hit it. A creature can only chase
// target anyway, and if two players of the same race are both poking it, the one it wants // one target anyway, and if two players of the same race are both poking it, the one it
// is whoever hit it last. // wants is whoever hit it last.
private static readonly Dictionary<ZDOID, Grudge> grudges = new Dictionary<ZDOID, Grudge>(); private static readonly KeyValuePair<int, int> AttackerKey = ZDO.GetHashZDOID("RacesOfValheim_GrudgeAttacker");
private static float lastSweep = 0f; private static readonly int UntilKey = "RacesOfValheim_GrudgeUntil".GetStableHashCode();
private static float Duration => FactionsConfig.GrudgeSeconds; private static float Duration => FactionsConfig.GrudgeSeconds;
// Network time, the same on every machine, so an end time written by one owner means the
// same thing to the next. Milliseconds in a long: ZDO has no double.
private static long NowMs => ZNet.instance != null ? (long)(ZNet.instance.GetTimeSeconds() * 1000.0) : 0L;
private static ZDO ZdoOf(Character character)
{
if (character == null || ZDOMan.instance == null) return null;
ZDOID id = character.GetZDOID();
return id.IsNone() ? null : ZDOMan.instance.GetZDO(id);
}
/// <summary> /// <summary>
/// True while <paramref name="monster"/> is owed a hit by <paramref name="player"/>. Both /// True while <paramref name="monster"/> is owed a hit by <paramref name="player"/>. Both
/// truce postfixes ask this first and leave IsEnemy alone when it answers yes. /// truce postfixes ask this first and leave IsEnemy alone when it answers yes. Read on any
/// machine; it only matters on the owner's.
/// </summary> /// </summary>
public static bool Holds(Character monster, Character player) public static bool Holds(Character monster, Character player)
{ {
if (monster == null || player == null) return false; if (monster == null || player == null) return false;
if (Duration <= 0f) return false; if (Duration <= 0f) return false;
if (!grudges.TryGetValue(monster.GetZDOID(), out Grudge grudge)) return false; ZDO zdo = ZdoOf(monster);
if (Time.time >= grudge.Until) return false; if (zdo == null) return false;
return grudge.Attacker == player.GetZDOID(); long until = zdo.GetLong(UntilKey, 0L);
} if (until == 0L || NowMs >= until) return false;
public static void Remember(Character monster, Character attacker) return zdo.GetZDOID(AttackerKey) == player.GetZDOID();
{
if (monster == null || attacker == null) return;
if (Duration <= 0f) return;
grudges[monster.GetZDOID()] = new Grudge
{
Attacker = attacker.GetZDOID(),
Until = Time.time + Duration
};
Sweep();
} }
/// <summary> /// <summary>
/// Drops grudges nobody is owed any more. At most once per duration: a fight is a burst of /// Writes the grudge on the creature's ZDO if this machine owns it, and otherwise asks the
/// damage events and the list should not be walked on each one. /// owner to. Returns true when it was written here.
/// </summary> /// </summary>
private static void Sweep() public static bool Remember(Character monster, Character attacker)
{ {
if (Time.time - lastSweep < Duration) return; if (monster == null || attacker == null) return false;
lastSweep = Time.time; if (Duration <= 0f) return false;
List<ZDOID> expired = null; ZNetView nview = monster.GetComponent<ZNetView>();
foreach (var entry in grudges) if (nview == null || !nview.IsValid()) return false;
if (!nview.IsOwner())
{ {
if (Time.time < entry.Value.Until) continue; nview.InvokeRPC(RpcName, attacker.GetZDOID());
if (expired == null) expired = new List<ZDOID>(); return false;
expired.Add(entry.Key); }
Write(nview.GetZDO(), attacker.GetZDOID());
return true;
}
private static void Write(ZDO zdo, ZDOID attacker)
{
zdo.Set(AttackerKey, attacker);
zdo.Set(UntilKey, NowMs + (long)(Duration * 1000f));
}
/// <summary>
/// Every creature can be told about a grudge by a machine that does not own it. ZNetView's
/// InvokeRPC routes to the owner, so the handler always runs where the ZDO may be written,
/// and the owner checks it is still the owner: ownership can move while the RPC travels.
/// </summary>
[HarmonyPatch(typeof(Character), "Awake")]
public static class Character_Awake_GrudgeRpc_Patch
{
public static void Postfix(Character __instance)
{
if (__instance.IsPlayer()) return;
ZNetView nview = __instance.GetComponent<ZNetView>();
if (nview == null || !nview.IsValid()) return;
nview.Register<ZDOID>(RpcName, (sender, attacker) =>
{
if (__instance == null || !nview.IsValid() || !nview.IsOwner()) return;
if (attacker.IsNone() || Duration <= 0f) return;
Write(nview.GetZDO(), attacker);
__instance.GetBaseAI()?.Alert();
});
} }
if (expired == null) return;
foreach (ZDOID id in expired) grudges.Remove(id);
} }
/// <summary> /// <summary>
@ -121,6 +152,81 @@ namespace RacesOfValheim
if (monster == null || monster.IsPlayer()) return; if (monster == null || monster.IsPlayer()) return;
Remember(monster, attacker); Remember(monster, attacker);
if (FactionsConfig.GrudgeSpreads && attacker is Player player) SpreadToKin(monster, player);
}
}
// How deep we are inside one of vanilla's hit filters (see StrikeScope). A counter rather
// than a bool because Projectile.OnHit calls DoAOE, and the inner exit must not end the
// outer scope.
private static int strikeDepth = 0;
/// <summary>
/// True while vanilla is deciding whether <paramref name="attacker"/>'s own weapon, arrow or
/// area hit lands. Both truce postfixes stand down for that question: the truce is about
/// who a creature attacks, never about whether the player is allowed to strike it.
/// </summary>
public static bool PlayerStrikes(Character attacker)
{
return strikeDepth > 0 && attacker != null && attacker.IsPlayer();
}
/// <summary>
/// THE PLAYER COULD NOT HIT THEIR OWN FACTION AT ALL. Valheim 1.0's hit filters (Attack's
/// melee and area swings, Projectile's direct hit, its AoE and its IsValidTarget, Aoe's
/// ShouldHit) ask BaseAI.IsEnemy(attacker, target) and skip the target when it answers false
/// and the attacker is a player without PvP on - vanilla's guard for tames. Our truce
/// answers false for every allied creature, so the blow passed through it, it took no
/// damage, BaseAI.OnDamaged never ran and no grudge was ever born. That is both reports at
/// once: "it will not allow me" to attack, and kin that never fight back, group grudge on or
/// off, because nobody was ever hit. With PvP on the filter let the hit through, which is
/// why it looked fine in some tests.
///
/// The scope is open only around those six methods, so everything else that asks IsEnemy
/// with the player first keeps the truce: the green health bar on allied creatures, sneaking
/// past them, the Aswid's aura leaving kin alone.
/// </summary>
[HarmonyPatch]
public static class StrikeScope
{
public static IEnumerable<System.Reflection.MethodBase> TargetMethods()
{
yield return AccessTools.Method(typeof(Attack), "DoMeleeAttack");
yield return AccessTools.Method(typeof(Attack), "DoAreaAttack");
yield return AccessTools.Method(typeof(Projectile), "DoAOE");
yield return AccessTools.Method(typeof(Projectile), "IsValidTarget");
yield return AccessTools.Method(typeof(Projectile), "OnHit");
yield return AccessTools.Method(typeof(Aoe), "ShouldHit");
}
public static void Prefix() => strikeDepth++;
// Finalizer rather than Postfix: the count has to come down even when the method
// throws, or every IsEnemy afterwards would ignore the truce.
public static void Finalizer() => strikeDepth--;
}
/// <summary>
/// Vanilla's Dvergr camp, for every faction ("Grudge spreads to kin", off by default): hit
/// a creature that is at peace with you and its kin around it take up the same grudge.
///
/// Kin this machine owns are written here; kin owned by another player's machine are told
/// through RpcName, and their owner writes the grudge and alerts them.
/// </summary>
private static void SpreadToKin(Character monster, Player player)
{
string race = FactionHostilityPatch.GetPlayerRace(player);
if (!FactionHostilityPatch.IsAlliedMob(race, monster.gameObject.name)) return;
Vector3 center = monster.transform.position;
float radius = FactionsConfig.GrudgeSpreadMeters;
foreach (Character other in Character.GetAllCharacters())
{
if (other == null || other == monster || other.IsPlayer() || other.IsDead() || other.IsTamed()) continue;
if (Vector3.Distance(other.transform.position, center) > radius) continue;
if (!FactionHostilityPatch.IsAlliedMob(race, other.gameObject.name)) continue;
if (Remember(other, player)) other.GetBaseAI()?.Alert();
} }
} }
} }

View file

@ -22,6 +22,9 @@ namespace RacesOfValheim
if (a == null || b == null) return; if (a == null || b == null) return;
// The player's own blow lands on kin too. See RaceGrudge.StrikeScope.
if (RaceGrudge.PlayerStrikes(a)) return;
Character playerCharacter = a.IsPlayer() ? a : (b.IsPlayer() ? b : null); Character playerCharacter = a.IsPlayer() ? a : (b.IsPlayer() ? b : null);
Character monster = a.IsPlayer() ? b : (b.IsPlayer() ? a : null); Character monster = a.IsPlayer() ? b : (b.IsPlayer() ? a : null);

View file

@ -167,6 +167,19 @@ namespace RacesOfValheim
return Input.GetMouseButtonDown(mouseButton) || PadAttackDown(mouseButton); return Input.GetMouseButtonDown(mouseButton) || PadAttackDown(mouseButton);
} }
/// <summary>
/// Nothing in either hand and not building. The pad has no spare button, so a race power
/// that needs one borrows the secondary attack under this condition only: with a weapon or
/// a tool in hand that button stays the item's, as in vanilla.
/// </summary>
public static bool EmptyHanded(Player player)
{
if (player == null || player.InPlaceMode()) return false;
var hands = Traverse.Create(player);
return hands.Field<ItemDrop.ItemData>("m_rightItem").Value == null &&
hands.Field<ItemDrop.ItemData>("m_leftItem").Value == null;
}
/// <summary>Held-down counterpart of <see cref="AttackDown"/>.</summary> /// <summary>Held-down counterpart of <see cref="AttackDown"/>.</summary>
public static bool AttackHeld(int mouseButton) public static bool AttackHeld(int mouseButton)
{ {
@ -202,7 +215,7 @@ namespace RacesOfValheim
private static bool loggedOpen; private static bool loggedOpen;
private static bool loggedClosed; private static bool loggedClosed;
private static bool RadialOpen internal static bool RadialOpen
{ {
get get
{ {

View file

@ -115,15 +115,18 @@ namespace RacesOfValheim
} }
} }
/// <summary>F8 turns the reach readout on and off.</summary> /// <summary>The debug key (DebugConfig, F8 by default) turns the reach readout on and off.</summary>
[HarmonyPatch(typeof(Player), "Update")] [HarmonyPatch(typeof(Player), "Update")]
internal static class RaceMeleeReachDebugKey internal static class RaceMeleeReachDebugKey
{ {
private static void Postfix(Player __instance) private static void Postfix(Player __instance)
{ {
if (__instance != Player.m_localPlayer || !Input.GetKeyDown(KeyCode.F8)) return; if (__instance != Player.m_localPlayer || !DebugConfig.EnableDebugKey.Value) return;
if (!DebugConfig.DebugKey.Value.IsDownIgnoringHeldKeys()) return;
RaceMeleeReach.DebugOn = !RaceMeleeReach.DebugOn; RaceMeleeReach.DebugOn = !RaceMeleeReach.DebugOn;
__instance.Message(MessageHud.MessageType.TopLeft, $"[RoV reach] debug {(RaceMeleeReach.DebugOn ? "on" : "off")}"); __instance.Message(MessageHud.MessageType.TopLeft, $"[RoV reach] debug {(RaceMeleeReach.DebugOn ? "on" : "off")}");
AlfarMiner.DebugReport(__instance);
AlfarDroneAI.DebugReport(__instance);
} }
} }
} }

View file

@ -44,6 +44,8 @@ namespace RacesOfValheim
prefab.AddComponent<RaceMenuWardBehavior>(); prefab.AddComponent<RaceMenuWardBehavior>();
Restyle(prefab);
PieceConfig config = new PieceConfig PieceConfig config = new PieceConfig
{ {
Name = "$rov_piece_racemenuward_name", Name = "$rov_piece_racemenuward_name",
@ -60,6 +62,44 @@ namespace RacesOfValheim
PieceManager.Instance.AddPiece(new CustomPiece(prefab, fixReference: false, config)); PieceManager.Instance.AddPiece(new CustomPiece(prefab, fixReference: false, config));
} }
// ---------------------------------------------------------------- the look
/// <summary>Seidr blue in place of the Ward's hearth orange: every race builds this, so no race's colour.</summary>
private static readonly Color Glow = new Color(0.55f, 0.62f, 1f, 1f);
/// <summary>A colder stone, so it reads as a different thing from the vanilla Ward across a base.</summary>
private static readonly Color StoneTint = new Color(0.78f, 0.82f, 0.92f, 1f);
/// <summary>Narrower and taller than the Ward, on a plinth: a statue rather than a waystone.</summary>
private static readonly Vector3 StatueShape = new Vector3(0.9f, 1.12f, 0.9f);
private const float PlinthWidth = 1.3f;
/// <summary>
/// Odin's stone on a plinth, glowing blue. The statue, its light and its sparks are lifted by the
/// plinth's MEASURED height, so a different plinth model needs no new offset.
/// </summary>
private static void Restyle(GameObject prefab)
{
Transform statue = prefab.transform.Find("new");
if (statue == null)
{
Jotunn.Logger.LogWarning("guard_stone has no 'new' model; the Race Menu Ward keeps the vanilla look.");
return;
}
PieceLook.Tint(statue, StoneTint);
PieceLook.Rehue(prefab.transform, Glow);
statue.localScale = Vector3.Scale(statue.localScale, StatueShape);
GameObject plinth = ModelBorrow.Attach(prefab.transform, "WardPlinth", "stone_floor_2x2",
Vector3.zero, Quaternion.identity, PlinthWidth,
"RaceMenuWard", activeOnly: true);
float lift = ModelBorrow.HeightOf(plinth);
foreach (string child in new[] { "new", "WayEffect", "GuidePoint" })
{
Transform part = prefab.transform.Find(child);
if (part != null) part.localPosition += Vector3.up * lift;
}
}
// Marks a world as already having its starter ward, so it is placed exactly once rather // Marks a world as already having its starter ward, so it is placed exactly once rather
// than every time someone loads in. // than every time someone loads in.
private const string PlacedKey = "RacesOfValheim_StarterWardPlaced"; private const string PlacedKey = "RacesOfValheim_StarterWardPlaced";

View file

@ -16,7 +16,7 @@ namespace RacesOfValheim
{ {
public const string PluginGUID = "com.nandor.racesofvalheim"; public const string PluginGUID = "com.nandor.racesofvalheim";
public const string PluginName = "Races Of Valheim"; public const string PluginName = "Races Of Valheim";
public const string PluginVersion = "1.6.1"; public const string PluginVersion = "1.6.11";
private readonly Harmony harmony = new Harmony(PluginGUID); private readonly Harmony harmony = new Harmony(PluginGUID);
@ -47,6 +47,7 @@ namespace RacesOfValheim
// Not a race either: a tool any race can craft, so it sits beside the vulture rather // Not a race either: a tool any race can craft, so it sits beside the vulture rather
// than inside the alphabetical run above. // than inside the alphabetical run above.
TrolsHammerConfig.Bind(Config); TrolsHammerConfig.Bind(Config);
ShrinkHammerConfig.Bind(Config);
// Not a race either: the two Bone Servants, shared by the Skeleton and Skadi, so they // Not a race either: the two Bone Servants, shared by the Skeleton and Skadi, so they
// bind here rather than inside either race's run. // bind here rather than inside either race's run.
ButlerConfig.Bind(Config); ButlerConfig.Bind(Config);
@ -56,6 +57,8 @@ namespace RacesOfValheim
// Not a race either: the faction truce and the faction merchants, which cut across // Not a race either: the faction truce and the faction merchants, which cut across
// every race at once, so they bind last rather than inside the alphabetical run above. // every race at once, so they bind last rather than inside the alphabetical run above.
FactionsConfig.Bind(Config); FactionsConfig.Bind(Config);
// The mod-wide debug switches, at the bottom of the list on purpose.
DebugConfig.Bind(Config);
// After every Bind above: tags the gameplay entries for Jotunn's server-to-client sync. // After every Bind above: tags the gameplay entries for Jotunn's server-to-client sync.
ConfigSync.Apply(Config); ConfigSync.Apply(Config);
harmony.PatchAll(); harmony.PatchAll();
@ -75,6 +78,9 @@ namespace RacesOfValheim
PrefabManager.OnVanillaPrefabsAvailable += CreateAllModAssets; PrefabManager.OnVanillaPrefabsAvailable += CreateAllModAssets;
CommandManager.Instance.AddConsoleCommand(new ResetRaceCommand()); CommandManager.Instance.AddConsoleCommand(new ResetRaceCommand());
CommandManager.Instance.AddConsoleCommand(new CheckProgressionCommand()); CommandManager.Instance.AddConsoleCommand(new CheckProgressionCommand());
CommandManager.Instance.AddConsoleCommand(new TrolSoundCommand("rovsnd1", TrolSounds.Death));
CommandManager.Instance.AddConsoleCommand(new TrolSoundCommand("rovsnd2", TrolSounds.Building));
StartCoroutine(TrolSounds.Load());
CommandManager.Instance.AddConsoleCommand(new IncreaseProgressionCommand()); CommandManager.Instance.AddConsoleCommand(new IncreaseProgressionCommand());
CommandManager.Instance.AddConsoleCommand(new ResetProgressionCommand()); CommandManager.Instance.AddConsoleCommand(new ResetProgressionCommand());
CommandManager.Instance.AddConsoleCommand(new DumpDvergerCommand()); CommandManager.Instance.AddConsoleCommand(new DumpDvergerCommand());
@ -89,6 +95,7 @@ namespace RacesOfValheim
CommandManager.Instance.AddConsoleCommand(new AlfarEitrCommand()); CommandManager.Instance.AddConsoleCommand(new AlfarEitrCommand());
CommandManager.Instance.AddConsoleCommand(new AlfarHpCommand()); CommandManager.Instance.AddConsoleCommand(new AlfarHpCommand());
CommandManager.Instance.AddConsoleCommand(new DumpAnimCommand()); CommandManager.Instance.AddConsoleCommand(new DumpAnimCommand());
CommandManager.Instance.AddConsoleCommand(new TrolPoseCommand());
CommandManager.Instance.AddConsoleCommand(new EvilLaughCommand()); CommandManager.Instance.AddConsoleCommand(new EvilLaughCommand());
} }
@ -305,6 +312,7 @@ namespace RacesOfValheim
AlfarRace.CreateModAssets(); AlfarRace.CreateModAssets();
WarVultureItem.Register(); WarVultureItem.Register();
TrolsHammerItem.Register(); TrolsHammerItem.Register();
ShrinkHammerItem.Register();
BoneServant.Register(); BoneServant.Register();
} }
// --- RACE SELECTION UI --- // --- RACE SELECTION UI ---

View file

@ -53,6 +53,13 @@
<Reference Include="System.Xml" /> <Reference Include="System.Xml" />
</ItemGroup> </ItemGroup>
<!-- Textures painted offline (scripts/paint_cook_cloth.py), carried inside the DLL so a mod
manager has no extra folder to flatten. Loaded by name: PieceLook.LoadTexture("CookCloth_d.png"). -->
<ItemGroup>
<EmbeddedResource Include="Assets\**\*.png" LogicalName="%(Filename)%(Extension)" />
<EmbeddedResource Include="Audio\*.ogg" LogicalName="%(Filename)%(Extension)" />
</ItemGroup>
<ItemGroup> <ItemGroup>
<None Include="app.config" /> <None Include="app.config" />
<None Include="packages.config" /> <None Include="packages.config" />

View file

@ -0,0 +1,211 @@
using BepInEx.Configuration;
using HarmonyLib;
using TMPro;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// What both sizing hammers share: which size the hammer in hand builds at, Alt + scroll to
/// change it, the size floating over the ghost, and the "Alt: Size" row in the bottom bar.
///
/// Trol's Hammer builds 1 to 3 times the vanilla size, the Shrink Hammer a quarter to 1. Each
/// keeps its size in its own config entry, and the wheel writes that entry, so Configuration
/// Manager and the wheel never disagree. The entries are not synced: each player picks their own.
/// Alt is free in build mode: vanilla's own placing modifier ("AltPlace") is Left Shift.
/// </summary>
public static class BuildScale
{
public const float Step = 0.05f;
/// <summary>The config entry behind the hammer in hand, or null for any other tool.</summary>
public static ConfigEntry<float> EntryFor(ItemDrop.ItemData item)
{
if (TrolsHammerItem.IsTrolsHammer(item)) return TrolsHammerConfig.ScaleFactor;
if (ShrinkHammerItem.IsShrinkHammer(item)) return ShrinkHammerConfig.ScaleFactor;
return null;
}
/// <summary>The multiplier a placement with this item in hand gets: 1 for any other tool.</summary>
public static float For(ItemDrop.ItemData item)
{
if (TrolsHammerItem.IsTrolsHammer(item)) return TrolsHammerConfig.ActiveFactor();
if (ShrinkHammerItem.IsShrinkHammer(item)) return ShrinkHammerConfig.ActiveFactor();
return 1f;
}
public static bool AltHeld() => Input.GetKey(KeyCode.LeftAlt) || Input.GetKey(KeyCode.RightAlt);
/// <summary>Moves the entry by whole steps, kept on the 0.05 grid and inside its range.</summary>
public static void Nudge(ConfigEntry<float> entry, int steps)
{
AcceptableValueRange<float> range = entry.Description.AcceptableValues as AcceptableValueRange<float>;
float min = range != null ? range.MinValue : 0.25f, max = range != null ? range.MaxValue : 3f;
float value = Mathf.Round((entry.Value + steps * Step) / Step) * Step;
entry.Value = Mathf.Clamp(value, min, max);
}
// --- the size over the ghost ---
private static GameObject s_labelled;
private static float s_shown;
/// <summary>
/// The size in Valheim's own floating NPC text, with one of the two hammers in hand:
/// - over the ghost, while the hammer's size differs from its default (1.2 for Trol's
/// Hammer, 1 for the Shrink Hammer);
/// - with the repair tool selected, over the piece aimed at, always: the size it was built
/// at, 1 for a piece no sizing hammer built.
/// The text has no timeout, so it is set again only when its piece or the size changes:
/// setting it replays its fade-in.
/// </summary>
public static void UpdateLabel(Player player, GameObject ghost)
{
if (Chat.instance == null) return;
ConfigEntry<float> entry = player != null && player.InPlaceMode() ? EntryFor(player.RightItem) : null;
if (entry == null)
{
ClearLabel();
return;
}
Piece tool = player.GetSelectedPiece();
if (tool != null && tool.m_repairPiece)
{
Piece aimed = player.GetHoveringPiece();
if (aimed != null) Show(aimed.gameObject, BuiltSize(aimed));
else ClearLabel();
return;
}
float value = For(player.RightItem);
if (ghost != null && ghost.activeInHierarchy && !Mathf.Approximately(value, (float)entry.DefaultValue))
Show(ghost, value);
else
ClearLabel();
}
/// <summary>The size a placed piece was built at, from its ZDO; 1 when no sizing hammer built it.</summary>
private static float BuiltSize(Piece piece)
{
ZDO zdo = piece.GetComponent<ZNetView>()?.GetZDO();
float saved = zdo != null ? zdo.GetFloat(TrolsHammerScaling.ScaleKey, 0f) : 0f;
return saved > 0f ? saved : 1f;
}
private static void Show(GameObject target, float value)
{
if (target == s_labelled && Mathf.Approximately(value, s_shown)) return;
ClearLabel();
Chat.instance.SetNpcText(target, Vector3.up * (TopOf(target) + 0.3f), 30f, 0f, "",
ModText.Get("rov_msg_build_scale", value.ToString("0.00")), false);
s_labelled = target;
s_shown = value;
}
private static void ClearLabel()
{
if (s_labelled != null && Chat.instance != null) Chat.instance.ClearNpcText(s_labelled);
s_labelled = null;
}
/// <summary>How far above its pivot the ghost reaches, from its renderers.</summary>
private static float TopOf(GameObject ghost)
{
float top = 0.5f;
foreach (Renderer renderer in ghost.GetComponentsInChildren<Renderer>())
top = Mathf.Max(top, renderer.bounds.max.y - ghost.transform.position.y);
return top;
}
}
/// <summary>
/// Alt + scroll in build mode. Vanilla turns the piece with the same wheel in the same method,
/// whatever key is held, so the prefix reads the wheel for the size and the postfix puts the
/// rotation back as it was.
/// </summary>
[HarmonyPatch(typeof(Player), "UpdatePlacement")]
public static class BuildScaleScrollPatch
{
private static float s_scroll;
private static void Prefix(Player __instance, bool takeInput, int ___m_placeRotation, out int __state)
{
__state = ___m_placeRotation;
if (!takeInput || __instance != Player.m_localPlayer || !__instance.InPlaceMode()) return;
if (!BuildScale.AltHeld()) return;
ConfigEntry<float> entry = BuildScale.EntryFor(__instance.RightItem);
if (entry == null) return;
s_scroll += ZInput.GetMouseScrollWheel();
if (s_scroll > __instance.m_scrollAmountThreshold) { s_scroll = 0f; BuildScale.Nudge(entry, 1); }
if (s_scroll < -__instance.m_scrollAmountThreshold) { s_scroll = 0f; BuildScale.Nudge(entry, -1); }
}
private static void Postfix(Player __instance, int __state, ref int ___m_placeRotation,
ref float ___m_scrollCurrAmount, GameObject ___m_placementGhost)
{
if (__instance != Player.m_localPlayer) return;
if (BuildScale.AltHeld() && BuildScale.EntryFor(__instance.RightItem) != null)
{
___m_placeRotation = __state;
___m_scrollCurrAmount = 0f;
}
BuildScale.UpdateLabel(__instance, ___m_placementGhost);
}
}
/// <summary>
/// The "Alt: Size" row in the build hints, next to vanilla's "Rotate": a copy of that row (the
/// wheel icon and its text), shown only while one of the two hammers is in hand. Added beside the
/// vanilla rows rather than through Jotunn's key hints, which replace the whole bar for an item.
/// </summary>
[HarmonyPatch(typeof(KeyHints), "UpdateHints")]
public static class BuildScaleKeyHintPatch
{
private static GameObject s_row;
private static bool s_failed;
private static void Postfix(KeyHints __instance)
{
if (s_row == null && !s_failed) s_row = MakeRow(__instance);
if (s_row == null) return;
Player player = Player.m_localPlayer;
bool show = player != null && BuildScale.EntryFor(player.RightItem) != null;
if (s_row.activeSelf != show) s_row.SetActive(show);
}
private static GameObject MakeRow(KeyHints hints)
{
Transform rotate = hints.m_buildHints != null ? FindDeep(hints.m_buildHints.transform, "rotate") : null;
TMP_Text source = rotate != null ? rotate.Find("Text")?.GetComponent<TMP_Text>() : null;
if (source == null)
{
s_failed = true;
Jotunn.Logger.LogWarning("[BuildScale] No rotate row in the build hints; the Alt: Size hint is not shown.");
return null;
}
GameObject row = Object.Instantiate(rotate.gameObject, rotate.parent, false);
row.name = "RoV_scale";
row.transform.SetSiblingIndex(rotate.GetSiblingIndex() + 1);
row.transform.Find("Text").GetComponent<TMP_Text>().text = ModText.Get("rov_hint_build_scale");
return row;
}
private static Transform FindDeep(Transform parent, string name)
{
foreach (Transform child in parent)
{
if (child.name == name) return child;
Transform found = FindDeep(child, name);
if (found != null) return found;
}
return null;
}
}
}

View file

@ -0,0 +1,33 @@
using BepInEx.Configuration;
namespace RacesOfValheim
{
/// <summary>
/// The Shrink Hammer's one number: the size it builds at, from a quarter of the vanilla piece up
/// to the vanilla size. Bigger than vanilla is Trol's Hammer's job. Alt + scroll with the hammer
/// in hand writes this same entry (BuildScale), so the slider in Configuration Manager and the
/// wheel always agree, and the size survives a restart.
/// </summary>
public static class ShrinkHammerConfig
{
public static ConfigEntry<float> ScaleFactor;
public static void Bind(ConfigFile config)
{
ScaleFactor = config.Bind("Shrink Hammer", "Scale factor", 1f,
new ConfigDescription("The size of the pieces the Shrink Hammer builds, against the " +
"vanilla piece: 1 is vanilla size, 0.25 a quarter. Hold Alt and " +
"scroll in build mode to change it in steps of 0.05. Cost and " +
"drop never change. A ship keeps its physics at any size.",
new AcceptableValueRange<float>(0.25f, 1f)));
}
/// <summary>The multiplier a new placement should use; 1 for a value typed into the .cfg
/// file that would make a piece too small to see, hit or remove.</summary>
public static float ActiveFactor()
{
if (ScaleFactor == null) return 1f;
return ScaleFactor.Value > 0.01f ? ScaleFactor.Value : 1f;
}
}
}

View file

@ -0,0 +1,77 @@
using Jotunn.Configs;
using Jotunn.Entities;
using Jotunn.Managers;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// The Shrink Hammer: the builder's hammer for small work, down to a quarter of the vanilla size.
/// Any race can craft it. Built the same way as <see cref="TrolsHammerItem"/>: a clone of the
/// vanilla Hammer that keeps the vanilla piece table, so every piece, including those other mods
/// add, is in its menu at the same cost. The size lives on the placement (TrolsHammerPatches,
/// BuildScale), never on the piece prefabs.
/// </summary>
public static class ShrinkHammerItem
{
public const string PrefabName = "ShrinkHammer";
public const string DisplayName = "$rov_item_shrinkhammer_name";
private const string SourcePrefab = "Hammer";
private const string Label = "ShrinkHammer";
public static void Register()
{
GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(PrefabName, SourcePrefab);
ItemDrop drop = prefab != null ? prefab.GetComponent<ItemDrop>() : null;
if (drop == null || drop.m_itemData == null || drop.m_itemData.m_shared == null)
{
Jotunn.Logger.LogWarning($"[{Label}] Could not clone {SourcePrefab}; {DisplayName} not registered.");
return;
}
ItemDrop.ItemData.SharedData shared = drop.m_itemData.m_shared;
shared.m_name = DisplayName;
shared.m_description = "$rov_item_shrinkhammer_desc";
Sprite icon = HammerIcon.Load("ShrinkHammer_icon.png");
if (icon != null) shared.m_icons = new[] { icon };
ItemManager.Instance.AddItem(new CustomItem(prefab, fixReference: false));
ItemManager.Instance.AddRecipe(new CustomRecipe(new RecipeConfig
{
Item = PrefabName,
Amount = 1,
CraftingStation = CraftingStations.Workbench,
MinStationLevel = 1,
Requirements = new[]
{
new RequirementConfig("FineWood", 2, 0, true),
new RequirementConfig("Resin", 2, 0, true),
},
}));
Jotunn.Logger.LogInfo($"[{Label}] {DisplayName} registered on the vanilla hammer's piece table.");
}
/// <summary>Whether an item in hand is this hammer; the display name is the fallback for an
/// ItemData built before ObjectDB finished, as in TrolsHammerItem.</summary>
public static bool IsShrinkHammer(ItemDrop.ItemData item)
{
if (item == null) return false;
if (item.m_dropPrefab != null) return item.m_dropPrefab.name == PrefabName;
return item.m_shared != null && item.m_shared.m_name == DisplayName;
}
}
/// <summary>The two hammers' own icons, painted offline (scripts/paint_hammer_icons.py) and
/// embedded in the DLL.</summary>
internal static class HammerIcon
{
public static Sprite Load(string resource)
{
Texture2D texture = PieceLook.LoadTexture(resource);
if (texture == null) return null;
return Sprite.Create(texture, new Rect(0f, 0f, texture.width, texture.height), new Vector2(0.5f, 0.5f));
}
}
}

View file

@ -45,21 +45,37 @@ namespace RacesOfValheim
// level for a short window past this before letting it start sinking. // level for a short window past this before letting it start sinking.
public float LastPoweredTime { get; set; } public float LastPoweredTime { get; set; }
// The drake's numbers for DirectedFlightPatch. Base flight stays free on purpose - the // This form's numbers for DirectedFlightPatch. The Drake's base flight defaults to free on
// drake arrives at the Elder, long before the player has the stamina pool to pay for // purpose - it arrives at the Elder, long before the player has the stamina pool to pay
// simply staying airborne - so only the sprint costs anything. // for simply staying airborne - so only its sprint costs anything. The Moder pays for
public float TurnSpeed => SkadiConfig.FlightTurnSpeed.Value; // every beat. The Fader never flies, so it falls back on the Drake's set unread.
public float GlideSpeed => SkadiConfig.FlightGlideSpeed.Value; private SkadiConfig.FormFlight Flight =>
public float BoostSpeed => SkadiConfig.FlightBoostSpeed.Value; formRules != null && formRules.Form == SkadiProgression.FormType.Moder ? SkadiConfig.ModerFlight : SkadiConfig.DrakeFlight;
public float SprintSpeed => SkadiConfig.FlightSprintSpeed.Value;
public float ReverseSpeed => SkadiConfig.FlightReverseSpeed.Value; public float TurnSpeed => Flight.TurnSpeed.Value;
public float GlideSpeed => Flight.GlideSpeed.Value;
public float BoostSpeed => Flight.BoostSpeed.Value;
public float SprintSpeed => Flight.SprintSpeed.Value;
public float ReverseSpeed => Flight.ReverseSpeed.Value;
// Climbing out of water is deliberately slower than a powered climb in open air - the // Climbing out of water is deliberately slower than a powered climb in open air - the
// wings are dragging themselves free, not racing. // wings are dragging themselves free, not racing.
public float LiftoffSpeed => SkadiConfig.FlightLiftoffSpeed.Value; public float LiftoffSpeed => Flight.LiftoffSpeed.Value;
public float HoverSeconds => SkadiConfig.FlightHoverSeconds.Value; public float HoverSeconds => Flight.HoverSeconds.Value;
public float PoweredStaminaPerSecond => 0f; public float PoweredStaminaPerSecond => Flight.PoweredStaminaPerSecond.Value * EncumberedCostFactor();
public float SprintStaminaPerSecond => SkadiConfig.FlightSprintStaminaPerSecond.Value; public float SprintStaminaPerSecond => Flight.SprintStaminaPerSecond.Value * EncumberedCostFactor();
public bool CanPower => true; public bool CanPower => !(IsEncumbered() && TooHeavyToFly);
private bool TooHeavyToFly => Flight.Encumbered.Value == AswidConfig.EncumberedMode.Blocked;
private static bool IsEncumbered()
{
return Player.m_localPlayer != null && Player.m_localPlayer.IsEncumbered();
}
private float EncumberedCostFactor()
{
return IsEncumbered() ? 1f + Flight.EncumberedExtraCost.Value : 1f;
}
private SkadiProgression.FormRules formRules; private SkadiProgression.FormRules formRules;
@ -171,7 +187,11 @@ namespace RacesOfValheim
(SkadiConfig.FlightToggleKey.Value.IsDownIgnoringHeldKeys() || RaceInput.PadAttackDown(1)) && (SkadiConfig.FlightToggleKey.Value.IsDownIgnoringHeldKeys() || RaceInput.PadAttackDown(1)) &&
formRules != null && formRules.Form != SkadiProgression.FormType.SkeletonDragon) formRules != null && formRules.Form != SkadiProgression.FormType.SkeletonDragon)
{ {
if (!isFlying && !isLanding) if (!isFlying && !isLanding && IsEncumbered() && TooHeavyToFly)
{
Player.m_localPlayer.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_skadi_too_heavy_to_fly"));
}
else if (!isFlying && !isLanding)
{ {
isFlying = true; isFlying = true;
LastPoweredTime = Time.time; LastPoweredTime = Time.time;
@ -291,6 +311,29 @@ namespace RacesOfValheim
return true; return true;
} }
/// <summary>
/// How many hit events the form's clips have sent: the dragon's own "Hit" event, which
/// CharacterAnimEvent hands to the player's OnAttackTrigger and SkadiBlockAttackTriggerPatch
/// counts here instead of letting it through. FenrirForms.AttackEvents, the same idea.
/// </summary>
public static int AttackEvents { get; private set; }
public static void NotifyAttackTrigger() => AttackEvents++;
// Longest a melee waits for its Hit event before landing anyway, from the trigger. The
// slowest blow is the Moder's claw at 2.0 s of 3.75 s; a clip that never sends one must
// not leave the swing hitting nothing.
private const float HitEventTimeout = 3f;
/// <summary>
/// Waits for the clip's own blow. A fixed 0.5 s used to land every melee early, read off the
/// game's clips: Moder bite 0.60 s and claws 2.0 s, Fader bite 1.27 s, claws 1.24 s, spin 1.30 s.
/// </summary>
private IEnumerator WaitForHit(int baseline, float started)
{
while (AttackEvents == baseline && Time.time - started < HitEventTimeout) yield return null;
}
private IEnumerator PerformAttackCoroutine(int button) private IEnumerator PerformAttackCoroutine(int button)
{ {
lastAttackTime = Time.time; lastAttackTime = Time.time;
@ -389,13 +432,18 @@ namespace RacesOfValheim
breathingUntil = Time.time + projDelay + projCount * 0.05f + 0.5f; breathingUntil = Time.time + projDelay + projCount * 0.05f + 0.5f;
} }
int hitBaseline = AttackEvents;
float triggeredAt = Time.time;
SetAttackTrigger(attackTrigger); SetAttackTrigger(attackTrigger);
yield return new WaitForSeconds(projDelay);
if (isMelee) if (isMelee)
{ {
ExecuteMeleeDamage(MODER_MELEE_DAMAGE, MELEE_RADIUS); yield return WaitForHit(hitBaseline, triggeredAt);
ExecuteMeleeDamage(MODER_MELEE_DAMAGE, MELEE_RADIUS, MeleeWeapon(attackTrigger));
}
else
{
yield return new WaitForSeconds(projDelay);
} }
if (!isMelee && projName != null) if (!isMelee && projName != null)
@ -495,13 +543,18 @@ namespace RacesOfValheim
breathingUntil = Time.time + projDelay + projCount * 0.05f + 0.5f; breathingUntil = Time.time + projDelay + projCount * 0.05f + 0.5f;
} }
int hitBaseline = AttackEvents;
float triggeredAt = Time.time;
SetAttackTrigger(attackTrigger); SetAttackTrigger(attackTrigger);
yield return new WaitForSeconds(projDelay);
if (isMelee) if (isMelee)
{ {
ExecuteMeleeDamage(meleeDamage, meleeRadius); yield return WaitForHit(hitBaseline, triggeredAt);
ExecuteMeleeDamage(meleeDamage, meleeRadius, MeleeWeapon(attackTrigger));
}
else
{
yield return new WaitForSeconds(projDelay);
} }
if (!isMelee && projName != null) if (!isMelee && projName != null)
@ -563,7 +616,28 @@ namespace RacesOfValheim
// The dragon forms never go through Humanoid.StartAttack - SkadiAttackPatch blocks it, and // The dragon forms never go through Humanoid.StartAttack - SkadiAttackPatch blocks it, and
// they carry no weapon - so the bite, claw and spin animations landed no damage at all and // they carry no weapon - so the bite, claw and spin animations landed no damage at all and
// simply burned eitr. Sweep for targets the way FenrirBehaviors does for its claws. // simply burned eitr. Sweep for targets the way FenrirBehaviors does for its claws.
private void ExecuteMeleeDamage(float baseDamage, float radius) private string FormLabel => formRules != null ? formRules.Form.ToString() : "Skadi form";
/// <summary>
/// The real creature's attack item behind each melee trigger, for its impact sound. The
/// Fader's spin has no item of its own in the game's manifest, so it borrows the claw's.
/// </summary>
private string MeleeWeapon(string trigger)
{
bool fader = formRules != null && formRules.Form == SkadiProgression.FormType.SkeletonDragon;
switch (trigger)
{
case "attack_bite": return fader ? "Fader_Bite" : "dragon_bite";
case "attack_claw_left": return "dragon_claw_left";
case "attack_claw_right": return "dragon_claw_right";
case "attack_ClawL": return "Fader_Claw_Left";
case "attack_ClawR": return "Fader_Claw_Right";
case "attack_Spin": return "Fader_Claw_Left";
default: return null;
}
}
private void ExecuteMeleeDamage(float baseDamage, float radius, string weapon)
{ {
if (Player.m_localPlayer == null) return; if (Player.m_localPlayer == null) return;
@ -578,7 +652,10 @@ namespace RacesOfValheim
int layerMask = LayerMask.GetMask("Default", "static_solid", "Default_small", "piece", "piece_nonsolid", "terrain", "character", "character_net", "character_ghost", "hitbox", "character_noenv", "vehicle"); int layerMask = LayerMask.GetMask("Default", "static_solid", "Default_small", "piece", "piece_nonsolid", "terrain", "character", "character_net", "character_ghost", "hitbox", "character_noenv", "vehicle");
Collider[] hits = Physics.OverlapSphere(attackPoint, radius, layerMask); Collider[] hits = Physics.OverlapSphere(attackPoint, radius, layerMask);
FormMelee.LogSwing(FormLabel, hits.Length);
ItemDrop.ItemData.SharedData shared = FormMelee.CreatureWeapon(weapon);
System.Collections.Generic.HashSet<GameObject> hitObjects = new System.Collections.Generic.HashSet<GameObject>(); System.Collections.Generic.HashSet<GameObject> hitObjects = new System.Collections.Generic.HashSet<GameObject>();
bool hitCreature = false;
foreach (Collider hit in hits) foreach (Collider hit in hits)
{ {
@ -592,18 +669,29 @@ namespace RacesOfValheim
if (characterTarget != null && characterTarget == Player.m_localPlayer) continue; if (characterTarget != null && characterTarget == Player.m_localPlayer) continue;
GameObject targetObj = (target as MonoBehaviour)?.gameObject; GameObject targetObj = (target as MonoBehaviour)?.gameObject;
if (targetObj != null) // Marked only once it is hit, further down: marking it here let the first collider
{ // found (a limb outside the arc) rule out a body squarely in the swing.
if (hitObjects.Contains(targetObj)) continue; if (targetObj != null && hitObjects.Contains(targetObj)) continue;
hitObjects.Add(targetObj);
}
Vector3 targetCenter = hit.bounds.center; Vector3 targetCenter = hit.bounds.center;
Vector3 dirToTarget = (targetCenter - playerPos).normalized; Vector3 dirToTarget = (targetCenter - playerPos).normalized;
if (!fullCircle && Vector3.Angle(forward, dirToTarget) >= 70f) continue; float angle = Vector3.Angle(forward, dirToTarget);
if (!fullCircle && angle >= 70f)
{
FormMelee.LogMiss(FormLabel, hit, $"outside the swing arc ({angle:0} deg)");
continue;
}
// FormMelee.CanReach, not a bare Linecast. The Linecast tested the piece layer and
// counted the target's own collider as cover, so anything living on that layer
// could never be hit: the T.W.I.G. training dummy is a Humanoid whose only collider
// is on "piece". Wildlife sits on "character" and was never affected.
Vector3 eyePos = playerPos + Vector3.up * 1.5f; Vector3 eyePos = playerPos + Vector3.up * 1.5f;
if (Physics.Linecast(eyePos, targetCenter, out RaycastHit rayHit, LayerMask.GetMask("Default", "static_solid", "terrain", "piece"))) continue; if (!FormMelee.CanReach(eyePos, attackPoint, hit, target, out string cover))
{
FormMelee.LogMiss(FormLabel, hit, "no clear line, blocked by '" + cover + "'");
continue;
}
HitData hitData = new HitData(); HitData hitData = new HitData();
// Frost-flavoured maul; SkadiDamagePatch tops this up with the per-tier frost bonus. // Frost-flavoured maul; SkadiDamagePatch tops this up with the per-tier frost bonus.
@ -619,8 +707,15 @@ namespace RacesOfValheim
hitData.m_toolTier = 0; hitData.m_toolTier = 0;
hitData.SetAttacker(Player.m_localPlayer); hitData.SetAttacker(Player.m_localPlayer);
if (targetObj != null) hitObjects.Add(targetObj);
FormMelee.LogHit(FormLabel, target, totalDamage);
target.Damage(hitData); target.Damage(hitData);
FormMelee.GrantAdrenaline(target);
shared?.m_hitEffect.Create(targetCenter, Quaternion.identity);
if (characterTarget != null) hitCreature = true;
} }
if (hitCreature) FormMelee.RaiseSkill(Skills.SkillType.Unarmed);
} }
private void OnDestroy() private void OnDestroy()

View file

@ -69,15 +69,38 @@ namespace RacesOfValheim
public static ConfigEntry<float> FaderSpinDamage; public static ConfigEntry<float> FaderSpinDamage;
public static ConfigEntry<float> FaderSpinRadius; public static ConfigEntry<float> FaderSpinRadius;
// ─── Directed flight (Drake/Moder) ──────────────────────────────────── // ─── Dragon forms: flight and timing, one set per form ───────────────────
public static ConfigEntry<float> FlightTurnSpeed; // One section for all three, as Dissolution asked for the bat's knobs on each form: the
public static ConfigEntry<float> FlightGlideSpeed; // keys carry the form's name and an Order, so Configuration Manager lists Drake, then
public static ConfigEntry<float> FlightBoostSpeed; // Moder, then Fader instead of mixing them alphabetically.
public static ConfigEntry<float> FlightSprintSpeed; public class FormFlight
public static ConfigEntry<float> FlightReverseSpeed; {
public static ConfigEntry<float> FlightLiftoffSpeed; public ConfigEntry<float> TurnSpeed;
public static ConfigEntry<float> FlightHoverSeconds; public ConfigEntry<float> GlideSpeed;
public static ConfigEntry<float> FlightSprintStaminaPerSecond; public ConfigEntry<float> BoostSpeed;
public ConfigEntry<float> SprintSpeed;
public ConfigEntry<float> ReverseSpeed;
public ConfigEntry<float> LiftoffSpeed;
public ConfigEntry<float> HoverSeconds;
public ConfigEntry<float> PoweredStaminaPerSecond;
public ConfigEntry<float> SprintStaminaPerSecond;
public ConfigEntry<AswidConfig.EncumberedMode> Encumbered;
public ConfigEntry<float> EncumberedExtraCost;
}
public class FormTiming
{
// -1 keeps the boss-tier table in SkadiProgression, so an untouched .cfg plays as before.
public ConfigEntry<float> MaxDuration;
public ConfigEntry<float> DurationPerState;
public ConfigEntry<float> Cooldown;
}
public static FormFlight DrakeFlight;
public static FormFlight ModerFlight;
public static FormTiming DrakeTiming;
public static FormTiming ModerTiming;
public static FormTiming FaderTiming;
public static void Bind(ConfigFile config) public static void Bind(ConfigFile config)
{ {
@ -164,23 +187,69 @@ namespace RacesOfValheim
FaderSpinRadius = config.Bind(attacks, "Fader Spin Radius", 5f, FaderSpinRadius = config.Bind(attacks, "Fader Spin Radius", 5f,
new ConfigDescription("Hit-sweep radius for the Skeleton Dragon's spin attack.", new AcceptableValueRange<float>(1f, 15f))); new ConfigDescription("Hit-sweep radius for the Skeleton Dragon's spin attack.", new AcceptableValueRange<float>(1f, 15f)));
const string flight = "Skadi - Directed Flight"; // Was "Skadi - Directed Flight", one set of numbers for both flying forms. The Drake is
FlightTurnSpeed = config.Bind(flight, "Turn Speed", 120f, // the scout: quick, nimble, free to fly, grounded by a heavy pack. The Moder is the
new ConfigDescription("Degrees per second the dragon form turns to face its heading.", new AcceptableValueRange<float>(10f, 360f))); // freighter: slow to turn and paying for every beat, but it lifts what the Drake cannot.
FlightGlideSpeed = config.Bind(flight, "Glide Speed", 5f, const string forms = "Skadi - Dragon Forms";
new ConfigDescription("Speed while gliding unpowered (no W/S held).", new AcceptableValueRange<float>(0f, 30f))); int order = 1000;
FlightBoostSpeed = config.Bind(flight, "Boost Speed", 12f, DrakeFlight = BindFlight(config, forms, "Drake", ref order,
new ConfigDescription("Speed while holding W without sprinting.", new AcceptableValueRange<float>(0f, 50f))); turn: 180f, glide: 6f, boost: 14f, sprint: 26f, reverse: 8f, liftoff: 9f, hover: 3f,
FlightSprintSpeed = config.Bind(flight, "Sprint Speed", 22f, powered: 0f, sprintCost: 10f, encumbered: AswidConfig.EncumberedMode.Blocked, extraCost: 0.25f);
new ConfigDescription("Speed while holding W and Shift, stamina permitting.", new AcceptableValueRange<float>(0f, 60f))); DrakeTiming = BindTiming(config, forms, "Drake", ref order);
FlightReverseSpeed = config.Bind(flight, "Reverse Speed", 7f, ModerFlight = BindFlight(config, forms, "Moder", ref order,
new ConfigDescription("Speed while beating backwards (S).", new AcceptableValueRange<float>(0f, 30f))); turn: 80f, glide: 5f, boost: 10f, sprint: 18f, reverse: 6f, liftoff: 9f, hover: 8f,
FlightLiftoffSpeed = config.Bind(flight, "Liftoff Speed", 9f, powered: 3f, sprintCost: 15f, encumbered: AswidConfig.EncumberedMode.Allowed, extraCost: 0.25f);
new ConfigDescription("Climb speed while clawing out of water.", new AcceptableValueRange<float>(0f, 30f))); ModerTiming = BindTiming(config, forms, "Moder", ref order);
FlightHoverSeconds = config.Bind(flight, "Hover Seconds", 5f, FaderTiming = BindTiming(config, forms, "Fader", ref order);
new ConfigDescription("How long level flight holds altitude after the last powered input before it starts to sink.", new AcceptableValueRange<float>(0f, 30f))); }
FlightSprintStaminaPerSecond = config.Bind(flight, "Sprint Stamina Per Second", 15f,
new ConfigDescription("Stamina drained per second while the sprint speed is actually granted.", new AcceptableValueRange<float>(0f, 60f))); private static FormFlight BindFlight(ConfigFile config, string section, string form, ref int order,
float turn, float glide, float boost, float sprint, float reverse, float liftoff, float hover,
float powered, float sprintCost, AswidConfig.EncumberedMode encumbered, float extraCost)
{
return new FormFlight
{
TurnSpeed = config.Bind(section, $"{form} Turn Speed", turn,
OrderedDesc($"Degrees per second the {form} turns towards where you aim.", new AcceptableValueRange<float>(10f, 360f), order--)),
GlideSpeed = config.Bind(section, $"{form} Glide Speed", glide,
OrderedDesc($"{form} speed while gliding with no key held, in m/s.", new AcceptableValueRange<float>(0f, 30f), order--)),
BoostSpeed = config.Bind(section, $"{form} Boost Speed", boost,
OrderedDesc($"{form} speed while holding W, in m/s. Costs the flight stamina below.", new AcceptableValueRange<float>(0f, 50f), order--)),
SprintSpeed = config.Bind(section, $"{form} Sprint Speed", sprint,
OrderedDesc($"{form} speed while holding W and Shift, in m/s. Costs the sprint stamina on top.", new AcceptableValueRange<float>(0f, 60f), order--)),
ReverseSpeed = config.Bind(section, $"{form} Reverse Speed", reverse,
OrderedDesc($"{form} speed while holding S, in m/s. Costs the flight stamina.", new AcceptableValueRange<float>(0f, 30f), order--)),
LiftoffSpeed = config.Bind(section, $"{form} Liftoff Speed", liftoff,
OrderedDesc($"{form} climb speed out of water, in m/s. Always free, so a form that touches the sea can still leave it.", new AcceptableValueRange<float>(0f, 30f), order--)),
HoverSeconds = config.Bind(section, $"{form} Hover Seconds", hover,
OrderedDesc($"How long the {form} holds its height after the last powered beat before it starts to sink.", new AcceptableValueRange<float>(0f, 30f), order--)),
PoweredStaminaPerSecond = config.Bind(section, $"{form} Flight Stamina Per Second", powered,
OrderedDesc($"Stamina per second while the {form} holds W or S. Out of stamina, it can only glide. 0 makes flight free.", new AcceptableValueRange<float>(0f, 60f), order--)),
SprintStaminaPerSecond = config.Bind(section, $"{form} Sprint Stamina Per Second", sprintCost,
OrderedDesc($"Extra stamina per second while the {form} sprints, on top of the flight cost.", new AcceptableValueRange<float>(0f, 60f), order--)),
Encumbered = config.Bind(section, $"{form} While Encumbered", encumbered,
OrderedDesc($"Allowed: the {form} flies while you carry too much, at the extra stamina cost below. Blocked: it cannot take off while you are encumbered, and one that becomes encumbered in the air can only glide down. It still walks.", null, order--)),
EncumberedExtraCost = config.Bind(section, $"{form} Encumbered Extra Stamina Cost", extraCost,
OrderedDesc($"With 'Allowed' above: how much more the {form}'s flight and sprint cost while encumbered. 0.25 = 25% more.", new AcceptableValueRange<float>(0f, 1f), order--)),
};
}
private static FormTiming BindTiming(ConfigFile config, string section, string form, ref int order)
{
return new FormTiming
{
MaxDuration = config.Bind(section, $"{form} Max Duration", -1f,
OrderedDesc($"Seconds the {form} form lasts before you turn back on your own. -1 follows the boss tiers (see the Compendium), 0 means no limit.", new AcceptableValueRange<float>(-1f, 3600f), order--)),
DurationPerState = config.Bind(section, $"{form} Duration Per State", 0f,
OrderedDesc($"Seconds added to the {form}'s max duration per progression state. Only counts when Max Duration is above 0.", new AcceptableValueRange<float>(0f, 600f), order--)),
Cooldown = config.Bind(section, $"{form} Cooldown", -1f,
OrderedDesc($"Seconds after leaving the {form} form before you can take it again. -1 follows the boss tiers, 0 means none.", new AcceptableValueRange<float>(-1f, 3600f), order--)),
};
}
private static ConfigDescription OrderedDesc(string description, AcceptableValueBase range, int order)
{
return new ConfigDescription(description, range, new ConfigurationManagerAttributes { Order = order });
} }
private static ConfigDescription KeyDesc(string description, int order) private static ConfigDescription KeyDesc(string description, int order)

View file

@ -408,7 +408,11 @@ namespace RacesOfValheim
public static bool Prefix(Humanoid __instance) public static bool Prefix(Humanoid __instance)
{ {
if (__instance != Player.m_localPlayer) return true; if (__instance != Player.m_localPlayer) return true;
return __instance.GetComponentInChildren<DrakeFormBehavior>() == null; if (__instance.GetComponentInChildren<DrakeFormBehavior>() == null) return true;
// The dragon's own clip calling its blow: the hit cue for the form's melee.
DrakeFormBehavior.NotifyAttackTrigger();
return false;
} }
} }
} }

View file

@ -85,7 +85,9 @@ namespace RacesOfValheim
rules.Form = FormType.Drake; rules.Form = FormType.Drake;
rules.CanAttackInForm = false; rules.CanAttackInForm = false;
} }
return rules.Form != FormType.None ? rules : null; if (rules.Form == FormType.None) return null;
ApplyTiming(rules, SkadiConfig.DrakeTiming, state);
return rules;
} }
public static FormRules GetHKeyRules(int state) public static FormRules GetHKeyRules(int state)
@ -112,7 +114,9 @@ namespace RacesOfValheim
rules.CooldownMinutes = 10f; rules.CooldownMinutes = 10f;
rules.CanAttackInForm = true; rules.CanAttackInForm = true;
} }
return rules.Form != FormType.None ? rules : null; if (rules.Form == FormType.None) return null;
ApplyTiming(rules, SkadiConfig.ModerTiming, state);
return rules;
} }
public static FormRules GetJKeyRules(int state) public static FormRules GetJKeyRules(int state)
@ -125,7 +129,27 @@ namespace RacesOfValheim
rules.CooldownMinutes = 0f; rules.CooldownMinutes = 0f;
rules.CanAttackInForm = true; rules.CanAttackInForm = true;
} }
return rules.Form != FormType.None ? rules : null; if (rules.Form == FormType.None) return null;
ApplyTiming(rules, SkadiConfig.FaderTiming, state);
return rules;
}
/// <summary>
/// The config's timing on top of the tier table above: -1 leaves the table's value, 0 or
/// more replaces it. Per-state seconds only stretch a limit that exists, as on the bat.
/// </summary>
private static void ApplyTiming(FormRules rules, SkadiConfig.FormTiming timing, int state)
{
if (timing == null) return;
float max = timing.MaxDuration.Value;
if (max >= 0f)
rules.DurationMinutes = max > 0f ? (max + timing.DurationPerState.Value * state) / 60f : 0f;
else if (rules.DurationMinutes > 0f)
rules.DurationMinutes += timing.DurationPerState.Value * state / 60f;
float cooldown = timing.Cooldown.Value;
if (cooldown >= 0f) rules.CooldownMinutes = cooldown / 60f;
} }
} }
} }

View file

@ -79,11 +79,11 @@ namespace RacesOfValheim
// drake one used for the passive blessing. // drake one used for the passive blessing.
Sprite dragonIcon = GetItemIcon("TrophyDragonQueen") ?? GetItemIcon("TrophyHatchling"); Sprite dragonIcon = GetItemIcon("TrophyDragonQueen") ?? GetItemIcon("TrophyHatchling");
skadiCdSE = ScriptableObject.CreateInstance<SE_FormCooldown>(); // One cooldown per form, so a Drake cooldown set in the config never holds the Moder
skadiCdSE.name = "SE_SkadiCooldown"; // back, nor the other way round. The Moder keeps the original name.
skadiCdSE.m_name = "$rov_se_skadi_formcd_name"; skadiCdSE = RegisterFormCooldown(SkadiProgression.FormType.Moder, "$rov_se_skadi_formcd_name", dragonIcon);
skadiCdSE.m_icon = dragonIcon; RegisterFormCooldown(SkadiProgression.FormType.Drake, "$rov_se_skadi_drakecd_name", GetItemIcon("TrophyHatchling") ?? dragonIcon);
ItemManager.Instance.AddStatusEffect(new CustomStatusEffect(skadiCdSE, fixReference: false)); RegisterFormCooldown(SkadiProgression.FormType.SkeletonDragon, "$rov_se_skadi_fadercd_name", GetItemIcon("TrophyFader") ?? dragonIcon);
skadiFormSE = ScriptableObject.CreateInstance<SE_SkadiForm>(); skadiFormSE = ScriptableObject.CreateInstance<SE_SkadiForm>();
skadiFormSE.name = "SE_SkadiForm"; skadiFormSE.name = "SE_SkadiForm";
@ -124,6 +124,26 @@ namespace RacesOfValheim
if (se != null) se.m_ttl = seconds; if (se != null) se.m_ttl = seconds;
} }
private static SE_FormCooldown RegisterFormCooldown(SkadiProgression.FormType form, string displayName, Sprite icon)
{
SE_FormCooldown cd = ScriptableObject.CreateInstance<SE_FormCooldown>();
cd.name = CooldownSEName(form);
cd.m_name = displayName;
cd.m_icon = icon;
ItemManager.Instance.AddStatusEffect(new CustomStatusEffect(cd, fixReference: false));
return cd;
}
private static string CooldownSEName(SkadiProgression.FormType form)
{
switch (form)
{
case SkadiProgression.FormType.Drake: return "SE_SkadiCooldown_Drake";
case SkadiProgression.FormType.SkeletonDragon: return "SE_SkadiCooldown_Fader";
default: return "SE_SkadiCooldown";
}
}
private static Sprite GetItemIcon(string prefabName) private static Sprite GetItemIcon(string prefabName)
{ {
GameObject trophy = PrefabManager.Cache.GetPrefab<ItemDrop>(prefabName)?.gameObject; GameObject trophy = PrefabManager.Cache.GetPrefab<ItemDrop>(prefabName)?.gameObject;
@ -465,13 +485,7 @@ namespace RacesOfValheim
/// mode and with nothing in either hand. Shared with SkadiAttackPatch, which swallows the /// mode and with nothing in either hand. Shared with SkadiAttackPatch, which swallows the
/// unarmed kick under exactly the same condition. /// unarmed kick under exactly the same condition.
/// </summary> /// </summary>
public static bool PadCastsColdSpell(Player player) public static bool PadCastsColdSpell(Player player) => RaceInput.EmptyHanded(player);
{
if (player == null || player.InPlaceMode()) return false;
var hands = HarmonyLib.Traverse.Create(player);
return hands.Field<ItemDrop.ItemData>("m_rightItem").Value == null &&
hands.Field<ItemDrop.ItemData>("m_leftItem").Value == null;
}
private IEnumerator ColdSpellKickCoroutine(SkadiProgression.FormRules rules) private IEnumerator ColdSpellKickCoroutine(SkadiProgression.FormRules rules)
{ {
@ -693,7 +707,7 @@ namespace RacesOfValheim
if (rules.CooldownMinutes > 0) if (rules.CooldownMinutes > 0)
{ {
var cdSE = Player.m_localPlayer.GetSEMan().GetStatusEffect("SE_SkadiCooldown".GetStableHashCode()); var cdSE = Player.m_localPlayer.GetSEMan().GetStatusEffect(CooldownSEName(rules.Form).GetStableHashCode());
if (cdSE != null) if (cdSE != null)
{ {
float m_time = HarmonyLib.Traverse.Create(cdSE).Field<float>("m_time").Value; float m_time = HarmonyLib.Traverse.Create(cdSE).Field<float>("m_time").Value;
@ -989,8 +1003,9 @@ namespace RacesOfValheim
if (activeRules != null && activeRules.CooldownMinutes > 0) if (activeRules != null && activeRules.CooldownMinutes > 0)
{ {
Player.m_localPlayer.GetSEMan().AddStatusEffect("SE_SkadiCooldown".GetStableHashCode(), true); int cdHash = CooldownSEName(activeRules.Form).GetStableHashCode();
var cdSE = Player.m_localPlayer.GetSEMan().GetStatusEffect("SE_SkadiCooldown".GetStableHashCode()); Player.m_localPlayer.GetSEMan().AddStatusEffect(cdHash, true);
var cdSE = Player.m_localPlayer.GetSEMan().GetStatusEffect(cdHash);
if (cdSE != null) cdSE.m_ttl = activeRules.CooldownMinutes * 60f; if (cdSE != null) cdSE.m_ttl = activeRules.CooldownMinutes * 60f;
} }
activeRules = null; activeRules = null;

View file

@ -47,6 +47,11 @@ namespace RacesOfValheim
public static ConfigEntry<bool> HeadFireVFXEnabled; public static ConfigEntry<bool> HeadFireVFXEnabled;
public static ConfigEntry<bool> BodyModelEnabled; public static ConfigEntry<bool> BodyModelEnabled;
public static ConfigEntry<bool> RaiseDeadIcon; public static ConfigEntry<bool> RaiseDeadIcon;
public static ConfigEntry<bool> ShowHelmet;
// ─── Mortal Habits (per player) ────────────────────────────────────────
public static ConfigEntry<bool> EatsMortalFood;
public static ConfigEntry<bool> FeelsFatigue;
public static void Bind(ConfigFile config) public static void Bind(ConfigFile config)
{ {
@ -86,6 +91,17 @@ 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.")); 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, 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.")); new ConfigDescription("Shows the Raise the Dead status icon while your Summon on Kill is on."));
ShowHelmet = config.Bind(visuals, "Show Helmet", false,
new ConfigDescription("Off: your helmet stays hidden over the skull. On: the helmet you wear shows. Helmets and hoods are moved and enlarged to fit the skull. Your own choice: other players see you the way you picked. A viking body (Body Model Enabled off) always shows its helmet."));
// For groups who want the Skeleton but miss Valheim's food or stamina. Both only take
// away an advantage (permanent best-tier food, infinite stamina), so each player picks
// for themselves and the server does not sync them.
const string habits = "Skeleton - Mortal Habits";
EatsMortalFood = config.Bind(habits, "Eats Mortal Food", false,
new ConfigDescription("Off: you never eat, and your Maximum Health comes from your standing (the bosses you have defeated). On: you eat like the living, your health and stamina come from your meals, and the standing's health bonus is gone. Your other Skeleton powers stay. Your own choice, not synced by the server."));
FeelsFatigue = config.Bind(habits, "Feels Fatigue", false,
new ConfigDescription("Off: you have no stamina and never tire. On: you spend stamina like the living. Without Eats Mortal Food your stamina grows with your standing, from the same meals your health is measured by. Your own choice, not synced by the server."));
} }
} }
} }

View file

@ -44,16 +44,26 @@ namespace RacesOfValheim
/// GetTotalFoodValue has exactly one caller, Player.UpdateFood, which passes the result /// GetTotalFoodValue has exactly one caller, Player.UpdateFood, which passes the result
/// straight to SetMaxHealth - so this is the single point where the number is decided, and /// straight to SetMaxHealth - so this is the single point where the number is decided, and
/// it now comes from the progression table rather than from three scaled sausages. /// it now comes from the progression table rather than from three scaled sausages.
///
/// A Skeleton with "Eats Mortal Food" is left to vanilla: its real meals decide both
/// numbers, and the tier's health, which stands in for those meals, does not stack on top.
/// One with "Feels Fatigue" who does not eat gets the stand-in meals' stamina, which the
/// fake foods themselves never deliver.
/// </summary> /// </summary>
[HarmonyPatch(typeof(Player), "GetTotalFoodValue")] [HarmonyPatch(typeof(Player), "GetTotalFoodValue")]
public static class Player_GetTotalFoodValue_SkeletonHealth_Patch public static class Player_GetTotalFoodValue_SkeletonHealth_Patch
{ {
public static void Postfix(Player __instance, ref float hp) public static void Postfix(Player __instance, ref float hp, ref float stamina)
{ {
if (__instance != Player.m_localPlayer || !SkeletonRace.IsSkeleton()) return; if (__instance != Player.m_localPlayer || !SkeletonRace.IsSkeleton()) return;
if (SkeletonConfig.EatsMortalFood.Value) return;
int state = BossProgressionManager.GetCurrentProgressionState(); int state = BossProgressionManager.GetCurrentProgressionState();
hp = __instance.m_baseHP + SkeletonProgression.GetMaxHealthBonus(state); hp = __instance.m_baseHP + SkeletonProgression.GetMaxHealthBonus(state);
if (SkeletonConfig.FeelsFatigue.Value)
{
stamina = __instance.m_baseStamina + SkeletonRace.GetStandInStamina(state);
}
} }
} }
@ -63,7 +73,7 @@ namespace RacesOfValheim
public static bool Prefix(Player __instance) public static bool Prefix(Player __instance)
{ {
// The Aswid used to be on this list. It spends stamina now, see Aswid_UseStamina_Patch. // The Aswid used to be on this list. It spends stamina now, see Aswid_UseStamina_Patch.
if ((SkeletonRace.IsSkeleton() || DraughRace.IsDraugh()) && __instance == Player.m_localPlayer) if (((SkeletonRace.IsSkeleton() && !SkeletonConfig.FeelsFatigue.Value) || DraughRace.IsDraugh()) && __instance == Player.m_localPlayer)
{ {
// Infinite stamina: skip the original UseStamina method // Infinite stamina: skip the original UseStamina method
return false; return false;
@ -79,7 +89,7 @@ namespace RacesOfValheim
{ {
if (__instance == Player.m_localPlayer) if (__instance == Player.m_localPlayer)
{ {
if (SkeletonRace.IsSkeleton() && item.m_shared.m_itemType == ItemDrop.ItemData.ItemType.Consumable && (item.m_shared.m_food > 0 || item.m_shared.m_foodStamina > 0 || item.m_shared.m_foodEitr > 0)) if (SkeletonRace.IsSkeleton() && !SkeletonConfig.EatsMortalFood.Value && item.m_shared.m_itemType == ItemDrop.ItemData.ItemType.Consumable && (item.m_shared.m_food > 0 || item.m_shared.m_foodStamina > 0 || item.m_shared.m_foodEitr > 0))
{ {
__instance.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_skeleton_skeletons_do_not_need_eat")); __instance.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_skeleton_skeletons_do_not_need_eat"));
__result = false; __result = false;
@ -194,7 +204,7 @@ namespace RacesOfValheim
{ {
try try
{ {
if (player == Player.m_localPlayer && SkeletonRace.IsSkeleton()) if (player == Player.m_localPlayer && SkeletonRace.IsSkeleton() && !SkeletonConfig.EatsMortalFood.Value)
{ {
if (__instance.m_foodBarRoot != null && __instance.m_foodBarRoot.gameObject.activeSelf) if (__instance.m_foodBarRoot != null && __instance.m_foodBarRoot.gameObject.activeSelf)
{ {
@ -233,7 +243,7 @@ namespace RacesOfValheim
} }
catch (System.Exception e) catch (System.Exception e)
{ {
if (player == Player.m_localPlayer && SkeletonRace.IsSkeleton()) return false; if (player == Player.m_localPlayer && SkeletonRace.IsSkeleton() && !SkeletonConfig.EatsMortalFood.Value) return false;
return true; return true;
} }
} }
@ -351,7 +361,7 @@ namespace RacesOfValheim
HideItemInstances(__instance, "m_hairItemInstance"); HideItemInstances(__instance, "m_hairItemInstance");
HideItemInstances(__instance, "m_beardItemInstance"); HideItemInstances(__instance, "m_beardItemInstance");
SetHelmetVisible(__instance, false); SkeletonVisuals.FitHelmet(p, __instance, SkeletonVisuals.ShowsHelmet(p));
// Poses the mandible, once per frame, after the animation. Attached from // Poses the mandible, once per frame, after the animation. Attached from
// here rather than from SkeletonRace because this postfix is the one path // here rather than from SkeletonRace because this postfix is the one path
@ -396,7 +406,7 @@ namespace RacesOfValheim
ShowItemInstances(__instance, "m_hairItemInstance"); ShowItemInstances(__instance, "m_hairItemInstance");
ShowItemInstances(__instance, "m_beardItemInstance"); ShowItemInstances(__instance, "m_beardItemInstance");
SetHelmetVisible(__instance, true); SkeletonVisuals.UnfitHelmet(__instance);
// Parented to rig bones, not to the body container that was just switched // Parented to rig bones, not to the body container that was just switched
// off above - so without this a human keeps the skeleton's lit sockets. // off above - so without this a human keeps the skeleton's lit sockets.
@ -405,26 +415,6 @@ namespace RacesOfValheim
} }
} }
/// <summary>
/// A helmet on a skull looks like a helmet floating in a skull, so the race hides it.
///
/// SkeletonRace does this every frame in a world, but it only ever runs for the local
/// player - which is why the helmet came back on the main-menu preview once the body
/// swap started working there. Doing it here covers the menu, remote players and the
/// first frame after a race change, all of which reach this postfix and none of which
/// reach SkeletonRace.
///
/// Delegates to SkeletonVisuals.SetEquipmentPieceHidden, which scales the wrapper to
/// zero and disables its renderers - scale alone leaves a skinned piece (bound to the
/// player's own bones rather than its own transform) still drawing, which is what a
/// helmet with a skinned cloth or chain part looked like.
/// </summary>
private static void SetHelmetVisible(VisEquipment visEq, bool visible)
{
GameObject helmet = Traverse.Create(visEq).Field<GameObject>("m_helmetItemInstance").Value;
SkeletonVisuals.SetEquipmentPieceHidden(helmet, !visible);
}
private static void HideItemInstances(VisEquipment visEq, string fieldName) private static void HideItemInstances(VisEquipment visEq, string fieldName)
{ {
SetItemInstanceActive(visEq, fieldName, false); SetItemInstanceActive(visEq, fieldName, false);
@ -882,6 +872,10 @@ namespace RacesOfValheim
if (name == "skeleton" || if (name == "skeleton" ||
name == "skeleton_noarcher" || name == "skeleton_noarcher" ||
name == "skeleton_poison" || name == "skeleton_poison" ||
name == "skeleton_meadows" || name == "skeleton_meadows_noarcher" ||
name == "skeleton_swamps" || name == "skeleton_swamps_noarcher" ||
name == "skeleton_mountains" || name == "skeleton_mountains_noarcher" ||
name == "skeleton_deepnorth" ||
name == "skeleton_friendly" || name == "skeleton_friendly" ||
name.StartsWith("draugr") || name.StartsWith("draugr") ||
name == "ghost" || name == "ghost" ||

View file

@ -125,6 +125,22 @@ namespace RacesOfValheim
Player.m_localPlayer.m_customData["Race"] == "Skeleton"; Player.m_localPlayer.m_customData["Race"] == "Skeleton";
} }
/// <summary>
/// Stamina from the tier's stand-in meals, for a Skeleton who feels fatigue but does not
/// eat. The fake foods cannot supply it: they are kept at m_time 0, so UpdateFood scales
/// their stamina to nothing on every tick.
/// </summary>
public static float GetStandInStamina(int state)
{
var foods = GetBestRealFoods(state);
float stamina = 0f;
if (foods != null)
{
foreach (var f in foods) stamina += f.m_shared.m_foodStamina;
}
return stamina;
}
private static readonly int StatsEffectHash = "SE_SkeletonStats".GetStableHashCode(); private static readonly int StatsEffectHash = "SE_SkeletonStats".GetStableHashCode();
private float lastAuraTime = 0f; private float lastAuraTime = 0f;
@ -137,7 +153,7 @@ namespace RacesOfValheim
private static List<ItemDrop.ItemData>[] cachedRealFoods = new List<ItemDrop.ItemData>[9]; private static List<ItemDrop.ItemData>[] cachedRealFoods = new List<ItemDrop.ItemData>[9];
private List<ItemDrop.ItemData> GetBestRealFoods(int state) private static List<ItemDrop.ItemData> GetBestRealFoods(int state)
{ {
if (state < 1) state = 1; if (state < 1) state = 1;
if (state > 8) state = 8; if (state > 8) state = 8;
@ -236,97 +252,6 @@ namespace RacesOfValheim
return bestCombo; return bestCombo;
} }
private void DumpTransformHierarchy(Transform t, string indent)
{
if (t == null) return;
Jotunn.Logger.LogInfo(indent + t.name + " (Active: " + t.gameObject.activeSelf + ")");
for(int i = 0; i < t.childCount; i++)
{
DumpTransformHierarchy(t.GetChild(i), indent + " ");
}
}
/// <summary>
/// F8 debug: fires a ray from the camera and logs whatever it hits. Cosmetic pieces
/// (hair, beard, helmet) carry no collider, so this mostly confirms terrain/creature hits
/// - LogHeadCosmeticsState below is what actually answers "what is that floating chunk."
/// Kept anyway because it is the general-purpose "what am I looking at" tool for any other
/// bone or prefab placement question that comes up later.
/// </summary>
private void LogRaycastHit()
{
Camera cam = Camera.main;
if (cam == null)
{
Jotunn.Logger.LogInfo("[F8] No camera found for raycast.");
return;
}
Ray ray = new Ray(cam.transform.position, cam.transform.forward);
if (Physics.Raycast(ray, out RaycastHit hit, 50f))
{
Jotunn.Logger.LogInfo("--- F8 RAYCAST HIT ---");
Jotunn.Logger.LogInfo($"Collider: '{hit.collider.gameObject.name}' at {hit.point:F2}, distance={hit.distance:F2}");
Jotunn.Logger.LogInfo($"Full path: {GetFullPath(hit.collider.transform)}");
Renderer renderer = hit.collider.GetComponentInParent<Renderer>();
if (renderer != null)
{
Jotunn.Logger.LogInfo($"Nearest renderer: '{renderer.gameObject.name}' ({renderer.GetType().Name}), enabled={renderer.enabled}, scale={renderer.transform.lossyScale:F3}");
}
Jotunn.Logger.LogInfo("----------------------");
}
else
{
Jotunn.Logger.LogInfo("[F8] Raycast hit nothing within 50m (cosmetic pieces usually have no collider anyway).");
}
}
private static string GetFullPath(Transform t)
{
string path = t.name;
for (Transform parent = t.parent; parent != null; parent = parent.parent)
{
path = parent.name + "/" + path;
}
return path;
}
/// <summary>
/// F8 debug: dumps the exact state of the three item slots this race hides (hair, beard,
/// helmet) - active flag, renderer enabled flag and scale for every renderer underneath.
/// This is the direct answer to "what is still visible and why": a chunk that survives
/// hiding will show up here as active=true, or as a renderer with enabled=true even while
/// its wrapper is scaled to zero (the skinned-mesh case scale alone cannot hide).
/// </summary>
private void LogHeadCosmeticsState()
{
if (Player.m_localPlayer == null) return;
VisEquipment vis = Player.m_localPlayer.GetComponent<VisEquipment>();
if (vis == null) return;
Jotunn.Logger.LogInfo("--- F8 SKELETON HEAD COSMETICS ---");
DumpItemInstanceField(vis, "m_hairItemInstance");
DumpItemInstanceField(vis, "m_beardItemInstance");
DumpItemInstanceField(vis, "m_helmetItemInstance");
Jotunn.Logger.LogInfo("----------------------------------");
}
private static void DumpItemInstanceField(VisEquipment vis, string fieldName)
{
GameObject go = HarmonyLib.Traverse.Create(vis).Field<GameObject>(fieldName).Value;
if (go == null)
{
Jotunn.Logger.LogInfo($"[F8] {fieldName}: null (nothing equipped/instantiated).");
return;
}
Jotunn.Logger.LogInfo($"[F8] {fieldName}: '{go.name}' active={go.activeSelf} scale={go.transform.localScale:F3}");
foreach (Renderer r in go.GetComponentsInChildren<Renderer>(true))
{
Jotunn.Logger.LogInfo($"[F8] renderer '{r.gameObject.name}' ({r.GetType().Name}) enabled={r.enabled}");
}
}
private void Update() private void Update()
{ {
if (Player.m_localPlayer == null) return; if (Player.m_localPlayer == null) return;
@ -396,10 +321,11 @@ namespace RacesOfValheim
{ {
// Hide Helmets (Valheim uses singular GameObject for helmet). Only over a skull: // 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. // a viking body wears its helmet, and the VisEquipment postfix puts it back.
// "Show Helmet" keeps it on the skull too, and is published for other clients.
SkeletonVisuals.PublishShowHelmet(Player.m_localPlayer);
if (SkeletonConfig.BodyModelEnabled.Value) if (SkeletonConfig.BodyModelEnabled.Value)
{ {
var helmetObj = HarmonyLib.Traverse.Create(currentVis).Field<GameObject>("m_helmetItemInstance").Value; SkeletonVisuals.FitHelmet(Player.m_localPlayer, currentVis, SkeletonConfig.ShowHelmet.Value);
SkeletonVisuals.SetEquipmentPieceHidden(helmetObj, true);
} }
// Scale Body Armor (Chest, Legs, Shoulder) by 5% // Scale Body Armor (Chest, Legs, Shoulder) by 5%
@ -453,7 +379,14 @@ namespace RacesOfValheim
var foods = Player.m_localPlayer.GetFoods(); var foods = Player.m_localPlayer.GetFoods();
bool needsFood = false; bool needsFood = false;
if (foods.Count != 3) if (SkeletonConfig.EatsMortalFood.Value)
{
// Real meals instead. The stand-in foods are the ones held at m_time 0 or below;
// dropped here at once rather than left for UpdateFood, which would announce each
// one as "food done".
foods.RemoveAll(f => f.m_time <= 0f);
}
else if (foods.Count != 3)
{ {
needsFood = true; needsFood = true;
} }

View file

@ -59,6 +59,41 @@ namespace RacesOfValheim
public static bool ShowsSkeletonBody(Player player) => public static bool ShowsSkeletonBody(Player player) =>
SkeletonConfig.BodyModelEnabled.Value && IsSkeletonPlayer(player); SkeletonConfig.BodyModelEnabled.Value && IsSkeletonPlayer(player);
// The owner's "Show Helmet" choice, so every other client draws this skeleton's helmet the
// way its owner picked rather than the way the onlooker's own setting says.
public const string ShowHelmetZdoKey = "RacesOfValheim_SkeletonShowHelmet";
/// <summary>
/// Whether this skeleton wears its helmet visibly over the skull. The local player and the
/// menu preview (which has no ZDO and is always this client's own character) go by this
/// client's setting; anyone else by what their owner published.
/// </summary>
public static bool ShowsHelmet(Player player)
{
if (player == null) return false;
ZNetView nview = player.GetComponent<ZNetView>();
if (player == Player.m_localPlayer || nview == null || !nview.IsValid())
{
return SkeletonConfig.ShowHelmet.Value;
}
return nview.GetZDO().GetBool(ShowHelmetZdoKey, false);
}
/// <summary>Writes the local player's choice to its ZDO when it differs. Owner only.</summary>
public static void PublishShowHelmet(Player player)
{
ZNetView nview = player != null ? player.GetComponent<ZNetView>() : null;
if (nview == null || !nview.IsValid() || !nview.IsOwner()) return;
bool show = SkeletonConfig.ShowHelmet.Value;
if (nview.GetZDO().GetBool(ShowHelmetZdoKey, false) != show)
{
nview.GetZDO().Set(ShowHelmetZdoKey, show);
}
}
/// <summary> /// <summary>
/// Fully hides (or restores) one equipped item instance - a helmet, typically. /// Fully hides (or restores) one equipped item instance - a helmet, typically.
/// ///
@ -71,11 +106,11 @@ namespace RacesOfValheim
/// is reasserted the same way (Valheim's own visual refresh re-enables the instance and /// is reasserted the same way (Valheim's own visual refresh re-enables the instance and
/// resets its scale, so both must be redone every time visuals rebuild). /// resets its scale, so both must be redone every time visuals rebuild).
/// </summary> /// </summary>
public static void SetEquipmentPieceHidden(GameObject instance, bool hidden) public static void SetEquipmentPieceHidden(GameObject instance, bool hidden, float shownSize = 1f)
{ {
if (instance == null) return; if (instance == null) return;
Vector3 wantedScale = hidden ? Vector3.zero : Vector3.one; Vector3 wantedScale = hidden ? Vector3.zero : Vector3.one * shownSize;
if (instance.transform.localScale != wantedScale) if (instance.transform.localScale != wantedScale)
{ {
instance.transform.localScale = wantedScale; instance.transform.localScale = wantedScale;
@ -90,6 +125,218 @@ namespace RacesOfValheim
} }
} }
/// <summary>
/// Where VisEquipment.AttachItem put the helmet: zero, or the prefab's own "equipoffset".
/// Kept on the instance so the fit is always a delta on it, and so taking the fit off
/// puts the helmet back exactly. A re-equip makes a new instance without one.
/// </summary>
private class HelmetBasePose : MonoBehaviour
{
public Vector3 Position;
// Skinned parts whose Head bone was swapped for the fit bone, with the bone list
// AttachItem gave them, so a viking body gets its own head back.
public readonly List<SkinnedMeshRenderer> Fitted = new List<SkinnedMeshRenderer>();
public readonly List<Transform[]> OriginalBones = new List<Transform[]>();
}
private const string FitBoneName = "SkeletonHelmetFitBone";
// The helmet on a skull: metres up and forward, and size. Dialled in on screen with
// Configuration Manager sliders (playtest, 2026-10-29) on the bronze, drake and flametal
// helmets, then written down here; the sliders are gone. One set fits all three bodies.
private const float HelmetFitUp = 0.068f;
private const float HelmetFitForward = -0.053f;
private const float HelmetFitSize = 1.298f;
// The same for the fit bone of skinned helmets (the 16 vanilla prefabs with an
// "attach_skin" child: hoods, but also Padded, Carapace, Sweatband and others). Tuned on
// the Fenring hood, then checked on nearly all the rest (2026-10-29). It scales from the
// Head bone's pivot rather than the helmet joint's, hence the different numbers.
private const float HoodFitUp = 0.041f;
private const float HoodFitForward = -0.071f;
private const float HoodFitSize = 1.246f;
// Which of the helmet joint's own axes are the skull's up and forward. Every player wears
// the same rig, so this is found once and kept. Re-picking it every frame made the
// offset jump sideways whenever the head turned far enough for another axis to win.
private static bool fitAxesFound;
private static Vector3 fitUpAxis, fitForwardAxis;
/// <summary>
/// Picks the axes only while the head faces straight ahead, so a turned head on the
/// first frame cannot lock in the wrong ones. False until then.
/// </summary>
private static bool FindFitAxes(Transform joint, Player player)
{
Vector3 up = ClosestLocalAxis(joint, player.transform.up);
Vector3 forward = ClosestLocalAxis(joint, player.transform.forward);
if (Vector3.Dot(joint.TransformDirection(up), player.transform.up) < 0.8f ||
Vector3.Dot(joint.TransformDirection(forward), player.transform.forward) < 0.8f)
{
return false;
}
fitUpAxis = up;
fitForwardAxis = forward;
fitAxesFound = true;
Jotunn.Logger.LogInfo($"[Skeleton] Helmet fit on '{joint.name}': up = local {up}, forward = local {forward}, joint scale {joint.lossyScale}.");
return true;
}
/// <summary>
/// The helmet on a skull: hidden, or shown and moved to fit the skull, which is bigger
/// and sits higher and further back than the viking head the helmet hangs for. Hidden
/// unless the owner turned on "Show Helmet" (ShowsHelmet).
///
/// Called from the VisEquipment postfix as well as SkeletonRace and ZdoVisualSync:
/// SkeletonRace only ever runs for the local player, which is why the helmet once came
/// back on the main-menu preview. The postfix covers the menu, remote players and the
/// first frame after a race change.
///
/// Up and forward are the player's, carried over to whichever of the helmet joint's own
/// axes points closest to them. The joint turns with the head, so the helmet keeps its
/// place on the skull when the player looks up or down.
///
/// A hood ("attach_skin") is skinned to the player's own bones, so moving its transform
/// does nothing. Its parts weighted to the Head bone get a fit bone instead: a child of
/// the real Head carrying the same kind of move and size. The parts weighted to the neck
/// and shoulders stay put, so the hood stretches between the two like it would over a
/// bigger head. Rigid helmets with a skinned chain or cloth piece get the same treatment
/// for that piece.
/// </summary>
public static void FitHelmet(Player player, VisEquipment vis, bool show)
{
GameObject helmet = vis != null ? HarmonyLib.Traverse.Create(vis).Field<GameObject>("m_helmetItemInstance").Value : null;
if (helmet == null) return;
if (!show)
{
SetEquipmentPieceHidden(helmet, true);
return;
}
// Always the helmet joint, never the instance's parent: a hood hangs off the body
// container, whose axes are not the head's.
Transform joint = HarmonyLib.Traverse.Create(vis).Field<Transform>("m_helmet").Value;
bool rigid = joint != null && helmet.transform.parent == joint;
SetEquipmentPieceHidden(helmet, false, rigid ? HelmetFitSize : 1f);
HelmetBasePose pose = helmet.GetComponent<HelmetBasePose>();
if (pose == null)
{
pose = helmet.AddComponent<HelmetBasePose>();
pose.Position = helmet.transform.localPosition;
}
if (joint == null) return;
if (!fitAxesFound && !FindFitAxes(joint, player)) return;
if (rigid)
{
Vector3 worldOffset = FitOffset(joint, HelmetFitUp, HelmetFitForward);
Vector3 wanted = pose.Position + joint.InverseTransformVector(worldOffset);
if (helmet.transform.localPosition != wanted)
{
helmet.transform.localPosition = wanted;
}
}
FitSkinnedParts(player, helmet, pose, joint);
}
private static Vector3 FitOffset(Transform joint, float up, float forward) =>
joint.TransformDirection(fitUpAxis) * up + joint.TransformDirection(fitForwardAxis) * forward;
private static readonly HashSet<string> loggedCloth = new HashSet<string>();
/// <summary>
/// Points every skinned part of the helmet that uses the Head bone at this player's fit
/// bone, and keeps the fit bone posed. The bone list is the part's own copy (Unity
/// copies on get and on set), so the body and the other armour keep the real Head.
/// </summary>
private static void FitSkinnedParts(Player player, GameObject helmet, HelmetBasePose pose, Transform joint)
{
Animator anim = player.GetComponentInChildren<Animator>();
Transform head = anim != null ? anim.GetBoneTransform(HumanBodyBones.Head) : null;
if (head == null) return;
Transform fitBone = null;
foreach (SkinnedMeshRenderer smr in helmet.GetComponentsInChildren<SkinnedMeshRenderer>(true))
{
if (pose.Fitted.Contains(smr)) continue;
Transform[] bones = smr.bones;
int index = System.Array.IndexOf(bones, head);
if (index < 0) continue;
if (fitBone == null) fitBone = GetFitBone(head);
pose.Fitted.Add(smr);
pose.OriginalBones.Add((Transform[])bones.Clone());
bones[index] = fitBone;
smr.bones = bones;
if (smr.GetComponent<Cloth>() != null && loggedCloth.Add(helmet.name))
{
Jotunn.Logger.LogInfo($"[Skeleton] Helmet '{helmet.name}': skinned part '{smr.name}' carries Cloth; its Head bone was swapped for the fit bone.");
}
}
if (pose.Fitted.Count == 0) return;
if (fitBone == null) fitBone = GetFitBone(head);
Vector3 wantedPos = head.InverseTransformVector(FitOffset(joint, HoodFitUp, HoodFitForward));
Vector3 wantedScale = Vector3.one * HoodFitSize;
if (fitBone.localPosition != wantedPos) fitBone.localPosition = wantedPos;
if (fitBone.localScale != wantedScale) fitBone.localScale = wantedScale;
}
/// <summary>This head's fit bone, made the first time a skinned helmet part needs it.</summary>
private static Transform GetFitBone(Transform head)
{
Transform fitBone = head.Find(FitBoneName);
if (fitBone != null) return fitBone;
fitBone = new GameObject(FitBoneName).transform;
fitBone.SetParent(head, false);
fitBone.localRotation = Quaternion.identity;
return fitBone;
}
/// <summary>Shows the helmet where vanilla put it, undoing any fit. For a viking body.</summary>
public static void UnfitHelmet(VisEquipment vis)
{
GameObject helmet = vis != null ? HarmonyLib.Traverse.Create(vis).Field<GameObject>("m_helmetItemInstance").Value : null;
if (helmet == null) return;
SetEquipmentPieceHidden(helmet, false);
HelmetBasePose pose = helmet.GetComponent<HelmetBasePose>();
if (pose == null) return;
if (helmet.transform.localPosition != pose.Position)
{
helmet.transform.localPosition = pose.Position;
}
for (int i = 0; i < pose.Fitted.Count; i++)
{
if (pose.Fitted[i] != null) pose.Fitted[i].bones = pose.OriginalBones[i];
}
pose.Fitted.Clear();
pose.OriginalBones.Clear();
}
private static Vector3 ClosestLocalAxis(Transform joint, Vector3 worldDir)
{
Vector3 local = joint.InverseTransformDirection(worldDir);
Vector3 abs = new Vector3(Mathf.Abs(local.x), Mathf.Abs(local.y), Mathf.Abs(local.z));
if (abs.x >= abs.y && abs.x >= abs.z) return new Vector3(Mathf.Sign(local.x), 0f, 0f);
if (abs.y >= abs.z) return new Vector3(0f, Mathf.Sign(local.y), 0f);
return new Vector3(0f, 0f, Mathf.Sign(local.z));
}
/// <summary> /// <summary>
/// The tier a given player's body should be built for. The ZDO carries it so remote /// The tier a given player's body should be built for. The ZDO carries it so remote
/// players render at their own standing; without one - the menu preview - fall back to /// players render at their own standing; without one - the menu preview - fall back to

View file

@ -46,6 +46,7 @@ namespace RacesOfValheim
public static ConfigEntry<float> RavagerYawDegrees; public static ConfigEntry<float> RavagerYawDegrees;
public static ConfigEntry<float> RavagerAttackOffsetValue; public static ConfigEntry<float> RavagerAttackOffsetValue;
public static ConfigEntry<bool> RavagerSlamCraterValue; public static ConfigEntry<bool> RavagerSlamCraterValue;
public static ConfigEntry<float> RavagerDamageShareValue;
// ─── Colony caps ───────────────────────────────────────────────────── // ─── Colony caps ─────────────────────────────────────────────────────
// Every ceiling on how many things the colony can have alive at once, in one section, so // Every ceiling on how many things the colony can have alive at once, in one section, so
@ -231,6 +232,11 @@ namespace RacesOfValheim
"The middle-click slam digs into the ground where it lands, like a pickaxe blow. " + "The middle-click slam digs into the ground where it lands, like a pickaxe blow. " +
"Never inside a ward you have no access to."); "Never inside a ward you have no access to.");
RavagerDamageShareValue = config.Bind(ravager, "Ravager Attack Damage", 1f,
new ConfigDescription("Share of a real Seeker Brute's damage each Ravager attack deals. " +
"Your Unarmed skill then scales it the way it scales a weapon: about 40% at level 0, " +
"about 92% at level 100.", new AcceptableValueRange<float>(0.1f, 2f)));
EmberGlowStrength = config.Bind(ember, "Glow Strength", SvermConfig.EmberGlowStrength, EmberGlowStrength = config.Bind(ember, "Glow Strength", SvermConfig.EmberGlowStrength,
"How hot the chitin burns at Fader. This multiplies an HDR colour and it is applied " + "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 " + "to the chest, the legs and the helmet at once, so it goes a very long way. Settled " +
@ -364,6 +370,7 @@ namespace RacesOfValheim
public static float RavagerYaw => RavagerYawDegrees?.Value ?? 0f; public static float RavagerYaw => RavagerYawDegrees?.Value ?? 0f;
public static float RavagerAttackOffset => RavagerAttackOffsetValue?.Value ?? 1.5f; public static float RavagerAttackOffset => RavagerAttackOffsetValue?.Value ?? 1.5f;
public static bool RavagerSlamCrater => RavagerSlamCraterValue?.Value ?? true; public static bool RavagerSlamCrater => RavagerSlamCraterValue?.Value ?? true;
public static float RavagerDamageShare => RavagerDamageShareValue?.Value ?? 1f;
public static bool Spines => SpinesEnabled?.Value ?? false; public static bool Spines => SpinesEnabled?.Value ?? false;
public static float SizeSmall => SpineSizeSmall?.Value ?? SvermConfig.SpineSizeSmall; public static float SizeSmall => SpineSizeSmall?.Value ?? SvermConfig.SpineSizeSmall;

View file

@ -24,6 +24,29 @@ namespace RacesOfValheim
{ {
public string Trigger; public string Trigger;
public HitData.DamageTypes Damage; public HitData.DamageTypes Damage;
/// <summary>The Brute weapon itself, for its swing (m_triggerEffect) and impact
/// (m_hitEffect) sounds. Vanilla plays both inside Attack, which this form never runs,
/// so without them every hit landed silent. Null if the weapon was missing.</summary>
public ItemDrop.ItemData.SharedData Shared;
/// <summary>The weapon's own push (m_attackForce), tool tier and swing arc, the way
/// TrolTrueFormModel.Profile carries the troll's.</summary>
public float PushForce;
public int ToolTier;
public float Angle;
}
/// <summary>
/// One blow's damage: the Brute's, times Ravager Attack Damage, times the Unarmed skill
/// factor the way a weapon's skill scales it (0.25-0.55 at level 0, 0.85-1 at 100).
/// TrolTrueFormModel.DamageFor does the same with Clubs for the troll.
/// </summary>
public static HitData.DamageTypes DamageFor(Player player, Profile profile)
{
HitData.DamageTypes damage = profile.Damage.Clone();
damage.Modify(SvermConfigManagement.RavagerDamageShare * player.GetRandomSkillFactor(Skills.SkillType.Unarmed));
return damage;
} }
private static Profile bite; private static Profile bite;
@ -72,6 +95,10 @@ namespace RacesOfValheim
{ {
Trigger = shared.m_attack != null ? (shared.m_attack.m_attackAnimation ?? "") : "", Trigger = shared.m_attack != null ? (shared.m_attack.m_attackAnimation ?? "") : "",
Damage = shared.m_damages, Damage = shared.m_damages,
Shared = shared,
PushForce = shared.m_attackForce,
ToolTier = shared.m_toolTier,
Angle = shared.m_attack != null ? shared.m_attack.m_attackAngle : 90f,
}; };
Jotunn.Logger.LogInfo($"[Sverm] Ravager Strain reads '{profile.Trigger}' off '{sourcePrefabName}' - " + Jotunn.Logger.LogInfo($"[Sverm] Ravager Strain reads '{profile.Trigger}' off '{sourcePrefabName}' - " +

View file

@ -744,7 +744,7 @@ namespace RacesOfValheim
wasGrounded = grounded; wasGrounded = grounded;
if (!RaceInput.Allowed || !grounded) return; if (!RaceInput.Allowed || !grounded || player.IsStaggering()) return;
// Right click rams, left click bites, middle click slams. All three read the device // Right click rams, left click bites, middle click slams. All three read the device
// directly (mouse, or its gamepad counterpart - see RaceInput.AttackDown) rather than // directly (mouse, or its gamepad counterpart - see RaceInput.AttackDown) rather than
@ -782,6 +782,7 @@ namespace RacesOfValheim
float radius, bool slam, bool lunge) float radius, bool slam, bool lunge)
{ {
isAttacking = true; isAttacking = true;
FormStagger.MarkAttack();
bool played = StartAttackState(profile); bool played = StartAttackState(profile);
if (rootMotion != null) rootMotion.Active = lunge; if (rootMotion != null) rootMotion.Active = lunge;
@ -791,8 +792,9 @@ namespace RacesOfValheim
yield return FollowAttackState(stateName, played, 0f, () => yield return FollowAttackState(stateName, played, 0f, () =>
{ {
if (FormStagger.AttackInterrupted) return;
if (slam) Slam(profile, radius, leftY, rightY, dropSamples); if (slam) Slam(profile, radius, leftY, rightY, dropSamples);
else ExecuteDamage(profile, radius); else ExecuteDamage(profile, radius, false);
}, () => }, () =>
{ {
if (leftClaw == null || rightClaw == null) return; if (leftClaw == null || rightClaw == null) return;
@ -826,7 +828,11 @@ namespace RacesOfValheim
{ {
Player player = Player.m_localPlayer; Player player = Player.m_localPlayer;
if (player != null) if (player != null)
ApplyDamageInSphere(player.transform.position + Vector3.up, SvermConfig.RavagerTauntRadius, profile.Damage); {
// No Strike: the roar above is the taunt's sound, the weapon's would double it.
if (ApplyDamageInSphere(player.transform.position + Vector3.up, SvermConfig.RavagerTauntRadius, profile, true))
FormMelee.RaiseSkill(Skills.SkillType.Unarmed);
}
}, null); }, null);
isAttacking = false; isAttacking = false;
@ -842,6 +848,11 @@ namespace RacesOfValheim
{ {
if (hasForwardSpeed) anim.SetFloat("forward_speed", 0f); if (hasForwardSpeed) anim.SetFloat("forward_speed", 0f);
// The Brute weapon's swing sound, which vanilla plays in Attack.Start (the bite's
// snap, the ram's charge, the slam's wind-up). The taunt's weapon has none.
Player player = Player.m_localPlayer;
if (player != null) profile.Shared?.m_startEffect.Create(player.transform.position, player.transform.rotation, player.transform);
if (string.IsNullOrEmpty(profile.Trigger) || !knownTriggers.Contains(profile.Trigger)) return false; if (string.IsNullOrEmpty(profile.Trigger) || !knownTriggers.Contains(profile.Trigger)) return false;
anim.SetTrigger(profile.Trigger); anim.SetTrigger(profile.Trigger);
@ -942,14 +953,14 @@ namespace RacesOfValheim
Transform claw = StrikingClaw(leftY, rightY, samples); Transform claw = StrikingClaw(leftY, rightY, samples);
if (claw == null) if (claw == null)
{ {
ExecuteDamage(profile, radius); ExecuteDamage(profile, radius, true);
Player player = Player.m_localPlayer; Player player = Player.m_localPlayer;
if (player != null) if (player != null)
DigCrater(player.transform.position + player.transform.forward * SvermConfigManagement.RavagerAttackOffset); DigCrater(player.transform.position + player.transform.forward * SvermConfigManagement.RavagerAttackOffset);
return; return;
} }
ApplyDamageInSphere(claw.position + Vector3.up * 0.5f, radius, profile.Damage); Strike(claw.position + Vector3.up * 0.5f, radius, profile, true);
DigCrater(claw.position); DigCrater(claw.position);
} }
@ -983,14 +994,14 @@ namespace RacesOfValheim
/// FenrirBehaviors.ExecuteClawDamage, unchanged in shape: a sphere swept against the same /// FenrirBehaviors.ExecuteClawDamage, unchanged in shape: a sphere swept against the same
/// broad layer mask every melee form in this mod already uses. /// broad layer mask every melee form in this mod already uses.
/// </summary> /// </summary>
private void ExecuteDamage(SvermRavagerAttacks.Profile profile, float radius) private void ExecuteDamage(SvermRavagerAttacks.Profile profile, float radius, bool slam)
{ {
Player player = Player.m_localPlayer; Player player = Player.m_localPlayer;
if (player == null) return; if (player == null) return;
float reach = SvermConfigManagement.RavagerAttackOffset; float reach = SvermConfigManagement.RavagerAttackOffset;
Vector3 attackPoint = player.transform.position + player.transform.forward * reach + Vector3.up; Vector3 attackPoint = player.transform.position + player.transform.forward * reach + Vector3.up;
ApplyDamageInSphere(attackPoint, radius, profile.Damage); Strike(attackPoint, radius, profile, slam);
} }
private const string CraterPrefab = "digg_v3"; private const string CraterPrefab = "digg_v3";
@ -1013,26 +1024,40 @@ namespace RacesOfValheim
if (crater != null) Object.Instantiate(crater, ground.point, Quaternion.identity); if (crater != null) Object.Instantiate(crater, ground.point, Quaternion.identity);
} }
private const string FormLabel = "Ravager";
private static readonly int HitMask = LayerMask.GetMask("Default", "static_solid", "Default_small", "piece",
"piece_nonsolid", "terrain", "character", "character_net", "character_ghost",
"hitbox", "character_noenv", "vehicle");
/// <summary> /// <summary>
/// The actual sweep, shared by every attack this form has (the three forward swings and /// The actual sweep, shared by every attack this form has. TrolTrueFormHit.SphereHit in
/// the taunt's own AoE) - only the sphere's centre and radius differ between them. /// shape: a forward swing stays inside its arc (the Brute's own, widened to 75 degrees each
/// side the way the troll's is), the slam's claws and the taunt reach all around, and
/// FormMelee.CanReach keeps a blow from landing through a wall. Each target that takes the
/// blow plays the Brute weapon's own impact effect, which vanilla plays inside Attack.
/// ///
/// m_skill is Swords, deliberately NOT Unarmed: Sverm_Damage_Patch rewrites any Unarmed /// m_skill is Swords, deliberately NOT Unarmed: Sverm_Damage_Patch rewrites any Unarmed
/// hit from a Sverm into the Chitin Claws' own tier damage, and that patch fires for THIS /// hit from a Sverm into the Chitin Claws' own tier damage, and that patch fires for THIS
/// call too, since it hooks Character.Damage itself rather than caring who dealt the hit. /// call too, since it hooks Character.Damage itself rather than caring who dealt the hit.
/// Swords keeps that rewrite from overwriting the Brute's real numbers with the claws'. /// Swords keeps that rewrite from overwriting the Brute's numbers with the claws'. It is
/// the Brute weapons' own skill too. The damage still scales with Unarmed (DamageFor).
/// </summary> /// </summary>
private static void ApplyDamageInSphere(Vector3 center, float radius, HitData.DamageTypes damage) /// <returns>True if the blow landed on a creature, so the caller raises the skill.</returns>
private static bool ApplyDamageInSphere(Vector3 center, float radius, SvermRavagerAttacks.Profile profile, bool allAround)
{ {
Player player = Player.m_localPlayer; Player player = Player.m_localPlayer;
if (player == null) return; if (player == null) return false;
int layerMask = LayerMask.GetMask("Default", "static_solid", "Default_small", "piece", Vector3 pos = player.transform.position;
"piece_nonsolid", "terrain", "character", "character_net", "character_ghost", Vector3 forward = player.transform.forward;
"hitbox", "character_noenv", "vehicle"); float halfAngle = allAround ? 180f : Mathf.Max(75f, profile.Angle * 0.5f);
HitData.DamageTypes damage = SvermRavagerAttacks.DamageFor(player, profile);
Collider[] hits = Physics.OverlapSphere(center, radius, layerMask); Collider[] hits = Physics.OverlapSphere(center, radius, HitMask);
FormMelee.LogSwing(FormLabel, hits.Length);
var hitObjects = new System.Collections.Generic.HashSet<GameObject>(); var hitObjects = new System.Collections.Generic.HashSet<GameObject>();
bool hitCreature = false;
foreach (Collider hit in hits) foreach (Collider hit in hits)
{ {
@ -1040,34 +1065,65 @@ namespace RacesOfValheim
if (hit.attachedRigidbody != null && hit.attachedRigidbody.gameObject == player.gameObject) continue; if (hit.attachedRigidbody != null && hit.attachedRigidbody.gameObject == player.gameObject) continue;
IDestructible target = hit.GetComponentInParent<IDestructible>(); IDestructible target = hit.GetComponentInParent<IDestructible>();
if (target == null) continue; if (target == null || (target is Character self && self == player)) continue;
if (target is Character characterTarget && characterTarget == player) continue;
// Marked only once it is hit, further down, so a limb outside the arc does not rule
// out a body squarely in the swing.
GameObject targetObj = (target as MonoBehaviour)?.gameObject; GameObject targetObj = (target as MonoBehaviour)?.gameObject;
if (targetObj != null) if (targetObj != null && hitObjects.Contains(targetObj)) continue;
{
if (hitObjects.Contains(targetObj)) continue;
hitObjects.Add(targetObj);
}
Vector3 targetCenter = hit.bounds.center; Vector3 targetCenter = hit.bounds.center;
Vector3 dirToTarget = (targetCenter - player.transform.position).normalized; 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;
}
if (!FormMelee.CanReach(player.GetEyePoint(), center, hit, target, out string cover))
{
FormMelee.LogMiss(FormLabel, hit, "no clear line, blocked by '" + cover + "'");
continue;
}
HitData hitData = new HitData(); HitData hitData = new HitData();
hitData.m_damage = damage; hitData.m_damage = damage;
hitData.m_point = targetCenter; hitData.m_point = targetCenter;
hitData.m_dir = dirToTarget; hitData.m_dir = (targetCenter - pos).normalized;
hitData.m_pushForce = 40f; hitData.m_pushForce = profile.PushForce;
hitData.m_skill = Skills.SkillType.Swords; hitData.m_skill = Skills.SkillType.Swords;
hitData.m_dodgeable = true; hitData.m_dodgeable = true;
hitData.m_blockable = true; hitData.m_blockable = true;
hitData.m_hitType = HitData.HitType.PlayerHit; hitData.m_hitType = HitData.HitType.PlayerHit;
hitData.m_toolTier = 100; hitData.m_toolTier = (short)profile.ToolTier;
hitData.SetAttacker(player); hitData.SetAttacker(player);
if (targetObj != null) hitObjects.Add(targetObj);
FormMelee.LogHit(FormLabel, target, damage.GetTotalDamage());
target.Damage(hitData); target.Damage(hitData);
} FormMelee.GrantAdrenaline(target);
profile.Shared?.m_hitEffect.Create(targetCenter, Quaternion.identity);
if (target is Character) hitCreature = true;
}
return hitCreature;
}
/// <summary>
/// One blow of a Ravager attack: the Brute weapon's trigger effect (the slam's landing
/// thud; the bite and the ram have none), the sweep, and the Unarmed experience vanilla
/// pays inside Attack for a swing that reached a creature. The Ravager fights unarmed like
/// the rest of the Sverm, so that is the skill it trains.
/// </summary>
private static void Strike(Vector3 center, float radius, SvermRavagerAttacks.Profile profile, bool allAround)
{
Player player = Player.m_localPlayer;
if (player == null) return;
profile.Shared?.m_triggerEffect.Create(center, player.transform.rotation);
if (ApplyDamageInSphere(center, radius, profile, allAround)) FormMelee.RaiseSkill(Skills.SkillType.Unarmed);
} }
} }
} }

View file

@ -12,7 +12,7 @@
"rov_compendium_alfar_utsog": "[Elder Unlock] Utsog: $1% of the damage you deal comes back to you as eitr.\n", "rov_compendium_alfar_utsog": "[Elder Unlock] Utsog: $1% of the damage you deal comes back to you as eitr.\n",
"rov_compendium_alfar_kall": "[Bonemass Unlock] Kall ('$1' Key): Pulls every dropped item within $2 meters to you. Waits $3 seconds.\n", "rov_compendium_alfar_kall": "[Bonemass Unlock] Kall ('$1' Key): Pulls every dropped item within $2 meters to you. Waits $3 seconds.\n",
"rov_compendium_alfar_ljosstorm": "[Moder Unlock] Ljosstorm ('$1' Key): A psionic storm over a $2 meter area for $3 seconds. Waits $4 seconds.\n", "rov_compendium_alfar_ljosstorm": "[Moder Unlock] Ljosstorm ('$1' Key): A psionic storm over a $2 meter area for $3 seconds. Waits $4 seconds.\n",
"rov_compendium_alfar_geisli": "[Yagluth Unlock] Geisli ('$1' Key, hold): A laser from your right hand, up to $2 meters, for at most $3 seconds, costing eitr by the second.\n", "rov_compendium_alfar_geisli": "[Yagluth Unlock] Geisli ('$1' Key, hold): A laser from your right hand, up to $2 meters, for at most $3 seconds, costing eitr by the second. On a gamepad, hold the secondary attack with empty hands.\n",
"rov_compendium_alfar_kyrr": "[Queen Unlock] Kyrr ('$1' Key): Holds what you look at in stasis for $2 seconds ($3 for a boss).\n", "rov_compendium_alfar_kyrr": "[Queen Unlock] Kyrr ('$1' Key): Holds what you look at in stasis for $2 seconds ($3 for a boss).\n",
"rov_compendium_alfar_sameining": "[Fader Unlock] Sameining ('$1' Key): The archon. Needs $2% of your eitr and a ready Heimkall; spends all the eitr and turns it into a pool of protection. For up to $3 seconds you are larger, faster and you fly, and a psionic pulse strikes everything hostile around you, but you cannot use weapons. When it ends - time up or pool gone - you are called home at one health and the Heimkall begins its wait.\n", "rov_compendium_alfar_sameining": "[Fader Unlock] Sameining ('$1' Key): The archon. Needs $2% of your eitr and a ready Heimkall; spends all the eitr and turns it into a pool of protection. For up to $3 seconds you are larger, faster and you fly, and a psionic pulse strikes everything hostile around you, but you cannot use weapons. When it ends - time up or pool gone - you are called home at one health and the Heimkall begins its wait.\n",
"rov_compendium_alfar_more_to_come": "More powers wake as the great ones fall.\n", "rov_compendium_alfar_more_to_come": "More powers wake as the great ones fall.\n",
@ -31,6 +31,7 @@
"rov_compendium_aswid_aswid_s_curse": "The Aswid's Curse\n", "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_g_key_night": "[Eikthyr Unlock] Bat Form ('G' Key, night only): Take the shape of a bat.\n",
"rov_compendium_aswid_bat_flight": "The bat flies where you look: W beats forward for $1 stamina a second, Shift sprints for $2 more, S beats backwards, and letting go holds you still for a moment before you glide down. Out of stamina, you can only glide.\n", "rov_compendium_aswid_bat_flight": "The bat flies where you look: W beats forward for $1 stamina a second, Shift sprints for $2 more, S beats backwards, and letting go holds you still for a moment before you glide down. Out of stamina, you can only glide.\n",
"rov_compendium_aswid_bat_free_flight": "Free Flight: the bat flies fast and free, with no stamina cost and no weight limit. Jump rises, Left Ctrl sinks, Shift goes faster.\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_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_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_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",
@ -85,14 +86,15 @@
"rov_compendium_dvergar_weapon_crossbow": "Crossbow", "rov_compendium_dvergar_weapon_crossbow": "Crossbow",
"rov_compendium_dvergar_weapon_hammer": "Hammer", "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_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_j_key_night": "[Yagluth Unlock] Cultist Form ('J' Key, night only): A robed shape that claws and channels fire, and pays for it: every hit on it lands 25% harder. 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_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_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_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_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_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. It is the one that holds the line: every hit on it lands 30% lighter.\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_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_g_now_calls_ulv_form": "[Moder Unlock] 'G' now calls Ulv Form instead of Wolf, and answers by day as well as night. The Ulv is the fastest of your shapes, the one to travel in.\n",
"rov_compendium_fenrir_senses_in_form": "In any form you sense every untamed creature within $1m, marking it with a telltale glow, as the Aswid do.\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_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_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_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",
@ -140,7 +142,7 @@
"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_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_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_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_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 a few 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. Carry too much and they will not lift you at all. 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_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_title": "Skadi Secrets",
"rov_compendium_skadi_winter_incarnate_passive": "[The Queen Unlock] Winter Incarnate (Passive):", "rov_compendium_skadi_winter_incarnate_passive": "[The Queen Unlock] Winter Incarnate (Passive):",
@ -216,9 +218,9 @@
"rov_compendium_trenta_purple_rain_g_key": "[The Elder Unlock] Purple Rain ('G' Key):", "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_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_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_spray_toxic_pollen_bursts_out": "A spray of toxic pollen bursts out to $1 meters: you and every ally caught in it are 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_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_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. In the water your stamina even comes back, slowly.\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_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_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_thorns_passive": "[Moder Unlock] Thorns (Passive):",
@ -238,5 +240,9 @@
"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_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_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_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" "rov_compendium_warvulture_what_bird_has_left_bar": "What the bird has left is the bar under your own.\n",
"rov_compendium_skeleton_diet_bones": "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.",
"rov_compendium_skeleton_diet_mortal": "You kept the habits of the flesh: you eat as the living do, and your health comes from your meals, not from your standing.",
"rov_compendium_skeleton_effort_none": "Nor does effort tire you; you have no stamina to spend at all.",
"rov_compendium_skeleton_effort_mortal": "Effort tires you as it tires the living, and you spend stamina like anyone else."
} }

View file

@ -45,12 +45,14 @@
"rov_hover_trenta_ready_empty": "ready: $1 $2\n[<color=yellow><b>$KEY_Use</b></color>] Empty it", "rov_hover_trenta_ready_empty": "ready: $1 $2\n[<color=yellow><b>$KEY_Use</b></color>] Empty it",
"rov_hover_trenta_rotting_minutes_left": "rotting, $1 minutes left", "rov_hover_trenta_rotting_minutes_left": "rotting, $1 minutes left",
"rov_hover_trol_call_warbands": "\n[<color=yellow><b>$KEY_Use</b></color>] Call the warbands", "rov_hover_trol_call_warbands": "\n[<color=yellow><b>$KEY_Use</b></color>] Call the warbands",
"rov_hover_trol_grab_log": "\n[<color=yellow><b>$1</b></color>] Grab Log", "rov_hover_trol_grab_log": "\n[<color=yellow><b>$KEY_Use</b></color>] Grab Log",
"rov_hover_trol_warbands": "warbands $1/$2", "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_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_personal": "Personal",
"rov_hover_ward_race_menu_ward_progression_open": "$rov_piece_racemenuward_name\n$1 progression - $2 ($3/$4)\n[<color=yellow><b>$KEY_Use</b></color>] Open\n[<color=yellow><b>Use item</b></color>] Offer a boss relic", "rov_hover_ward_race_menu_ward_progression_open": "$rov_piece_racemenuward_name\n$1 progression - $2 ($3/$4)\n[<color=yellow><b>$KEY_Use</b></color>] Open\n[<color=yellow><b>Use item</b></color>] Offer a boss relic",
"rov_hover_ward_world": "World", "rov_hover_ward_world": "World",
"rov_hover_boneship_roster": "\nmelee $1/$2 of $3\narchers $4/$5 of $6\naboard $7", "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" "rov_hover_boneship_bone_hand": "\nbone in hand to buy a place",
"rov_hover_alfar_inngangskista": "Inngangskista (input)",
"rov_hover_alfar_eldividarkista": "Eldividarkista (fuel)"
} }

View file

@ -81,8 +81,10 @@
"rov_item_trenta_rotseed_name": "Rot Seed", "rov_item_trenta_rotseed_name": "Rot Seed",
"rov_item_trol_giantslog_desc": "A massive tree log wielded as a weapon.", "rov_item_trol_giantslog_desc": "A massive tree log wielded as a weapon.",
"rov_item_trol_giantslog_name": "Giant's Log", "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_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. Hold Alt and scroll to choose how much bigger.",
"rov_item_trolshammer_name": "Trol's Hammer", "rov_item_trolshammer_name": "Trol's Hammer",
"rov_item_shrinkhammer_name": "Shrink Hammer",
"rov_item_shrinkhammer_desc": "A fine hammer for small work. It builds everything the ordinary one builds, out of the same materials, down to a quarter of the size. Hold Alt and scroll to choose the size.",
"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_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_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_desc": "Flesh goes in, bone goes in, and what is left of both comes out red.",

View file

@ -18,6 +18,7 @@
"rov_msg_aswid_vae_victis": "Vae Victis", "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_aswid_what_horrible_night_have_curse": "what a horrible night to have a curse",
"rov_msg_aswid_bat_cooldown": "Your blood is not ready to take wing again ($1s)", "rov_msg_aswid_bat_cooldown": "Your blood is not ready to take wing again ($1s)",
"rov_msg_aswid_bat_combat_lock": "Your blood runs too hot from the fight to take wing ($1s)",
"rov_msg_aswid_bat_form_fades": "The bat form fades", "rov_msg_aswid_bat_form_fades": "The bat form fades",
"rov_msg_aswid_bat_too_heavy_to_beat": "Too heavy to beat your wings. You can only glide", "rov_msg_aswid_bat_too_heavy_to_beat": "Too heavy to beat your wings. You can only glide",
"rov_msg_aswid_too_heavy_for_bat": "You carry too much to take bat form", "rov_msg_aswid_too_heavy_for_bat": "You carry too much to take bat form",
@ -117,6 +118,7 @@
"rov_msg_skadi_are_moder": "You are Moder!", "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_cooldown": "Dragon Form is on cooldown ($1:$2).",
"rov_msg_skadi_dragon_form_fades": "Your dragon form fades.", "rov_msg_skadi_dragon_form_fades": "Your dragon form fades.",
"rov_msg_skadi_too_heavy_to_fly": "You carry too much for the Drake to take off",
"rov_msg_skadi_dumped_dragon_drake_fader_debug": "Dumped Dragon/Drake/Fader debug info to console!", "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_needs_stonecutter_cut_at": "It needs a stonecutter to be cut at.",
"rov_msg_skadi_not_enough_stamina": "Not enough stamina", "rov_msg_skadi_not_enough_stamina": "Not enough stamina",
@ -227,6 +229,7 @@
"rov_msg_alfar_nexus_built": "Made: $1", "rov_msg_alfar_nexus_built": "Made: $1",
"rov_msg_alfar_nexus_no_crystals": "The core holds no crystals yet.", "rov_msg_alfar_nexus_no_crystals": "The core holds no crystals yet.",
"rov_msg_alfar_nexus_collected": "Crystals taken: $1", "rov_msg_alfar_nexus_collected": "Crystals taken: $1",
"rov_msg_alfar_graf_cooldown": "The drones are not ready yet ($1s).",
"rov_msg_alfar_graf_materials": "The drones need $1 stone and $2 flint.", "rov_msg_alfar_graf_materials": "The drones need $1 stone and $2 flint.",
"rov_msg_thrall_refusal_alfar": "The construct does not know your light.", "rov_msg_thrall_refusal_alfar": "The construct does not know your light.",
"rov_msg_thrall_refusal_alfar_drone": "The drone takes no orders. It works." "rov_msg_thrall_refusal_alfar_drone": "The drone takes no orders. It works."
@ -237,5 +240,10 @@
"rov_msg_build_limit_alfar_chest": "This core already has one of these within reach.", "rov_msg_build_limit_alfar_chest": "This core already has one of these within reach.",
"rov_msg_build_limit_alfar_ljosgard": "This core already has its Ljosgard." "rov_msg_build_limit_alfar_ljosgard": "This core already has its Ljosgard."
, ,
"rov_msg_alfar_nexus_no_store": "The nucleus has nothing to offer right now." "rov_msg_alfar_nexus_no_store": "The nucleus has nothing to offer right now.",
"rov_msg_alfar_drone_sort_nowhere": "I have nowhere to put $1. Give me an empty chest, or one that already holds $1.",
"rov_msg_alfar_drone_sort_keep": "I leave $1 in the $2: a station here works with it.",
"rov_msg_alfar_drone_kiln_wood": "The $4 is idle. I only burn wood from the $3, and the $1 is in another chest.",
"rov_msg_build_scale": "Size $1",
"rov_hint_build_scale": "Alt: Size"
} }

View file

@ -40,7 +40,9 @@
"rov_se_skadi_dragonattackcd_tooltip": "Your dragon shape must ready itself to strike again.", "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_name": "Dragon Form",
"rov_se_skadi_form_tooltip": "Your dragon shape holds for a while longer.", "rov_se_skadi_form_tooltip": "Your dragon shape holds for a while longer.",
"rov_se_skadi_formcd_name": "Dragon Form Cooldown", "rov_se_skadi_drakecd_name": "Drake Form Cooldown",
"rov_se_skadi_fadercd_name": "Fader Form Cooldown",
"rov_se_skadi_formcd_name": "Moder Form Cooldown",
"rov_se_skadi_stats_name": "Skadi's Blessing", "rov_se_skadi_stats_name": "Skadi's Blessing",
"rov_se_skeleton_resurrectcd_name": "Resurrection Cooldown", "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_resurrectcd_tooltip": "Your skeletal body is too weak to resurrect again right now.",

View file

@ -12,7 +12,7 @@
"rov_compendium_alfar_utsog": "[Sblocco Anziano] Utsog: il $1% dei danni che infliggi ti torna come eitr.\n", "rov_compendium_alfar_utsog": "[Sblocco Anziano] Utsog: il $1% dei danni che infliggi ti torna come eitr.\n",
"rov_compendium_alfar_kall": "[Sblocco Bonemass] Kall (tasto '$1'): attira a te ogni oggetto a terra entro $2 metri. Attesa $3 secondi.\n", "rov_compendium_alfar_kall": "[Sblocco Bonemass] Kall (tasto '$1'): attira a te ogni oggetto a terra entro $2 metri. Attesa $3 secondi.\n",
"rov_compendium_alfar_ljosstorm": "[Sblocco Moder] Ljosstorm (tasto '$1'): una tempesta psionica su un'area di $2 metri per $3 secondi. Attesa $4 secondi.\n", "rov_compendium_alfar_ljosstorm": "[Sblocco Moder] Ljosstorm (tasto '$1'): una tempesta psionica su un'area di $2 metri per $3 secondi. Attesa $4 secondi.\n",
"rov_compendium_alfar_geisli": "[Sblocco Yagluth] Geisli (tasto '$1', tenuto): un laser dalla mano destra, fino a $2 metri, per al massimo $3 secondi, consumando eitr al secondo.\n", "rov_compendium_alfar_geisli": "[Sblocco Yagluth] Geisli (tasto '$1', tenuto): un laser dalla mano destra, fino a $2 metri, per al massimo $3 secondi, consumando eitr al secondo. Col controller, tieni premuto l'attacco secondario a mani vuote.\n",
"rov_compendium_alfar_kyrr": "[Sblocco Regina] Kyrr (tasto '$1'): tiene in stasi ciò che guardi per $2 secondi ($3 per un boss).\n", "rov_compendium_alfar_kyrr": "[Sblocco Regina] Kyrr (tasto '$1'): tiene in stasi ciò che guardi per $2 secondi ($3 per un boss).\n",
"rov_compendium_alfar_sameining": "[Sblocco Fader] Sameining (tasto '$1'): l'arconte. Servono il $2% dell'eitr e un Heimkall pronto; spende tutto l'eitr e lo trasforma in una riserva di protezione. Per al massimo $3 secondi sei più grande, più veloce e voli, e un impulso psionico colpisce tutto ciò che è ostile attorno a te, ma non puoi usare armi. Alla fine - tempo scaduto o riserva esaurita - vieni richiamato a casa con un punto ferita e l'attesa dell'Heimkall ricomincia.\n", "rov_compendium_alfar_sameining": "[Sblocco Fader] Sameining (tasto '$1'): l'arconte. Servono il $2% dell'eitr e un Heimkall pronto; spende tutto l'eitr e lo trasforma in una riserva di protezione. Per al massimo $3 secondi sei più grande, più veloce e voli, e un impulso psionico colpisce tutto ciò che è ostile attorno a te, ma non puoi usare armi. Alla fine - tempo scaduto o riserva esaurita - vieni richiamato a casa con un punto ferita e l'attesa dell'Heimkall ricomincia.\n",
"rov_compendium_alfar_more_to_come": "Altri poteri si risveglieranno man mano che cadono i grandi.\n", "rov_compendium_alfar_more_to_come": "Altri poteri si risveglieranno man mano che cadono i grandi.\n",
@ -31,6 +31,7 @@
"rov_compendium_aswid_aswid_s_curse": "La maledizione degli Aswid\n", "rov_compendium_aswid_aswid_s_curse": "La maledizione degli Aswid\n",
"rov_compendium_aswid_bat_form_g_key_night": "[Sblocco Eikthyr] Forma di pipistrello (tasto 'G', solo di notte): prendi la forma di un pipistrello.\n", "rov_compendium_aswid_bat_form_g_key_night": "[Sblocco Eikthyr] Forma di pipistrello (tasto 'G', solo di notte): prendi la forma di un pipistrello.\n",
"rov_compendium_aswid_bat_flight": "Il pipistrello vola dove guardi: W batte le ali in avanti per $1 stamina al secondo, Shift scatta per altri $2, S batte all'indietro, e se lasci tutto resti fermo un attimo prima di planare giù. Senza stamina puoi solo planare.\n", "rov_compendium_aswid_bat_flight": "Il pipistrello vola dove guardi: W batte le ali in avanti per $1 stamina al secondo, Shift scatta per altri $2, S batte all'indietro, e se lasci tutto resti fermo un attimo prima di planare giù. Senza stamina puoi solo planare.\n",
"rov_compendium_aswid_bat_free_flight": "Volo libero: il pipistrello vola veloce e libero, senza costo di stamina e senza limite di peso. Salto sale, Ctrl sinistro scende, Shift va più veloce.\n",
"rov_compendium_aswid_bat_form_now_answers_by": "[Sblocco Antico] La forma di pipistrello ora risponde di giorno come di notte.\n", "rov_compendium_aswid_bat_form_now_answers_by": "[Sblocco Antico] La forma di pipistrello ora risponde di giorno come di notte.\n",
"rov_compendium_aswid_benedictus_et_afflictus": "[Passiva base] Benedictus et Afflictus:", "rov_compendium_aswid_benedictus_et_afflictus": "[Passiva base] Benedictus et Afflictus:",
"rov_compendium_aswid_claws_beast_s_grows_blackened": "[Passiva base] Artigli della Bestia ([K], $1s): per un tempo limitato fai crescere artigli anneriti al posto di un'arma. I colpi a mani nude valgono il $2% del peso di un paio adulto, tutto come danno da taglio, e crescono con ogni boss che cade. Sfodera una spada e aspettano, rinfoderala e tornano, finché il tempo non scade e si ritraggono da soli, senza sprecare uno slot tra un uso e l'altro. Mentre sono fuori non possono essere lasciati cadere, scambiati o rubati, e in forma di pipistrello o di nebbia non hai mani per tenerli.\n", "rov_compendium_aswid_claws_beast_s_grows_blackened": "[Passiva base] Artigli della Bestia ([K], $1s): per un tempo limitato fai crescere artigli anneriti al posto di un'arma. I colpi a mani nude valgono il $2% del peso di un paio adulto, tutto come danno da taglio, e crescono con ogni boss che cade. Sfodera una spada e aspettano, rinfoderala e tornano, finché il tempo non scade e si ritraggono da soli, senza sprecare uno slot tra un uso e l'altro. Mentre sono fuori non possono essere lasciati cadere, scambiati o rubati, e in forma di pipistrello o di nebbia non hai mani per tenerli.\n",
@ -85,14 +86,15 @@
"rov_compendium_dvergar_weapon_crossbow": "Balestra", "rov_compendium_dvergar_weapon_crossbow": "Balestra",
"rov_compendium_dvergar_weapon_hammer": "Martello", "rov_compendium_dvergar_weapon_hammer": "Martello",
"rov_compendium_fenrir_beast_within_physical_stats_scale": "[Passiva base] La bestia dentro: le tue statistiche fisiche crescono con ogni boss sconfitto: +$1 armatura, +$2 danni, +$3% velocità, +$4% salto e -$5% danni da caduta.\n", "rov_compendium_fenrir_beast_within_physical_stats_scale": "[Passiva base] La bestia dentro: le tue statistiche fisiche crescono con ogni boss sconfitto: +$1 armatura, +$2 danni, +$3% velocità, +$4% salto e -$5% danni da caduta.\n",
"rov_compendium_fenrir_cultist_form_j_key_night": "[Sblocco Yagluth] Forma di Cultista (tasto 'J', solo di notte): una figura incappucciata che artiglia e incanala il fuoco. Dura 1 minuto, ricarica di 10 minuti.\n", "rov_compendium_fenrir_cultist_form_j_key_night": "[Sblocco Yagluth] Forma di Cultista (tasto 'J', solo di notte): una figura incappucciata che artiglia e incanala il fuoco, e lo paga: ogni colpo che subisce arriva più forte del 25%. Dura 1 minuto, ricarica di 10 minuti.\n",
"rov_compendium_fenrir_cultist_form_now_answers_by": "[Sblocco Fader] La forma di Cultista ora risponde di giorno come di notte, e puoi tenerla quanto vuoi.\n", "rov_compendium_fenrir_cultist_form_now_answers_by": "[Sblocco Fader] La forma di Cultista ora risponde di giorno come di notte, e puoi tenerla quanto vuoi.\n",
"rov_compendium_fenrir_cultist_form_s_cooldown_falls": "[Sblocco Regina] La ricarica della forma di Cultista scende a 5 minuti (sempre solo di notte, sempre 1 minuto).\n", "rov_compendium_fenrir_cultist_form_s_cooldown_falls": "[Sblocco Regina] La ricarica della forma di Cultista scende a 5 minuti (sempre solo di notte, sempre 1 minuto).\n",
"rov_compendium_fenrir_curse_pack": "La maledizione del branco\n", "rov_compendium_fenrir_curse_pack": "La maledizione del branco\n",
"rov_compendium_fenrir_cursed_claws_s_wolf_s": "[Passiva base] Artigli maledetti ([K], $1s): le mani del lupo, tenute nella forma dell'uomo per un tempo limitato al posto di un'arma. I colpi a mani nude valgono il $2% del peso di un paio adulto, tutto come danno da taglio, e crescono con ogni boss che cade. Sfodera una spada e aspettano, rinfoderala e tornano, finché il tempo non scade e si ritraggono da soli, senza sprecare uno slot tra un uso e l'altro. Mentre sono fuori non possono essere lasciati cadere, scambiati o rubati, e in forma di bestia sono le fauci a fare il lavoro.\n", "rov_compendium_fenrir_cursed_claws_s_wolf_s": "[Passiva base] Artigli maledetti ([K], $1s): le mani del lupo, tenute nella forma dell'uomo per un tempo limitato al posto di un'arma. I colpi a mani nude valgono il $2% del peso di un paio adulto, tutto come danno da taglio, e crescono con ogni boss che cade. Sfodera una spada e aspettano, rinfoderala e tornano, finché il tempo non scade e si ritraggono da soli, senza sprecare uno slot tra un uso e l'altro. Mentre sono fuori non possono essere lasciati cadere, scambiati o rubati, e in forma di bestia sono le fauci a fare il lavoro.\n",
"rov_compendium_fenrir_fenring_form_h_key_night": "[Sblocco Moder] Forma di Fenring (tasto 'H', solo di notte): ergiti come un vero Fenring, con artigli pesanti e un attacco in salto, la più forte delle quattro forme finora.\n", "rov_compendium_fenrir_fenring_form_h_key_night": "[Sblocco Moder] Forma di Fenring (tasto 'H', solo di notte): ergiti come un vero Fenring, con artigli pesanti e un attacco in salto, la più forte delle quattro forme finora. È la forma che tiene la linea: ogni colpo che subisce arriva più leggero del 30%.\n",
"rov_compendium_fenrir_fenring_form_now_answers_by": "[Sblocco Regina] La forma di Fenring ora risponde di giorno come di notte.\n", "rov_compendium_fenrir_fenring_form_now_answers_by": "[Sblocco Regina] La forma di Fenring ora risponde di giorno come di notte.\n",
"rov_compendium_fenrir_g_now_calls_ulv_form": "[Sblocco Moder] 'G' ora richiama la forma di Ulv invece del Lupo, e risponde di giorno come di notte.\n", "rov_compendium_fenrir_g_now_calls_ulv_form": "[Sblocco Moder] 'G' ora richiama la forma di Ulv invece del Lupo, e risponde di giorno come di notte. L'Ulv è la più veloce delle tue forme, quella per viaggiare.\n",
"rov_compendium_fenrir_senses_in_form": "In qualsiasi forma percepisci ogni creatura non addomesticata entro $1m, e la segni con un bagliore rivelatore, come fanno gli Aswid.\n",
"rov_compendium_fenrir_sunrise_breaks_any_night_bound": "L'alba spezza in anticipo ogni forma legata alla notte, e lascia la bestia troppo stanca per cambiare di nuovo forma per un po'.\n", "rov_compendium_fenrir_sunrise_breaks_any_night_bound": "L'alba spezza in anticipo ogni forma legata alla notte, e lascia la bestia troppo stanca per cambiare di nuovo forma per un po'.\n",
"rov_compendium_fenrir_title": "Segreti dei Fenrir", "rov_compendium_fenrir_title": "Segreti dei Fenrir",
"rov_compendium_fenrir_ulv_form_h_key_night": "[Sblocco Massa d'ossa] Forma di Ulv (tasto 'H', solo di notte): una forma di lupo più pesante, con morsi più forti, ancora legata al buio.\n", "rov_compendium_fenrir_ulv_form_h_key_night": "[Sblocco Massa d'ossa] Forma di Ulv (tasto 'H', solo di notte): una forma di lupo più pesante, con morsi più forti, ancora legata al buio.\n",
@ -140,7 +142,7 @@
"rov_compendium_skadi_one_stonecutter_holds_them_no": "Uno scalpellino ne tiene $1, e non più di $2 possono stare entro una giornata di cammino l'uno dall'altro. Distruggi lo scalpellino e ciò che ha tagliato si ferma $3 secondi dopo.\n", "rov_compendium_skadi_one_stonecutter_holds_them_no": "Uno scalpellino ne tiene $1, e non più di $2 possono stare entro una giornata di cammino l'uno dall'altro. Distruggi lo scalpellino e ciò che ha tagliato si ferma $3 secondi dopo.\n",
"rov_compendium_skadi_secrets_winter": "I segreti dell'inverno\n", "rov_compendium_skadi_secrets_winter": "I segreti dell'inverno\n",
"rov_compendium_skadi_skeleton_dragon_form_j_key": "[Sblocco Fader] Forma di drago scheletrico (tasto 'J'):", "rov_compendium_skadi_skeleton_dragon_form_j_key": "[Sblocco Fader] Forma di drago scheletrico (tasto 'J'):",
"rov_compendium_skadi_take_shape_frost_drake_right": "Prendi la forma di un drake del gelo. Il tasto destro ti solleva in volo: plani dove miri, tieni premuto W per salire e prendere velocità, aggiungi Shift per spendere stamina in uno scatto, e premi S per battere le ali all'indietro lungo la mira mentre lo sguardo resta dov'era. Lascia tutto e resti in quota per cinque secondi prima di scendere piano. L'acqua non può trattenerti: le tue ali ti tirano fuori dal mare con la stessa facilità con cui ti sollevano dalla riva. In questa forma non puoi ancora colpire.\n", "rov_compendium_skadi_take_shape_frost_drake_right": "Prendi la forma di un drake del gelo. Il tasto destro ti solleva in volo: plani dove miri, tieni premuto W per salire e prendere velocità, aggiungi Shift per spendere stamina in uno scatto, e premi S per battere le ali all'indietro lungo la mira mentre lo sguardo resta dov'era. Lascia tutto e resti in quota per qualche secondo prima di scendere piano. L'acqua non può trattenerti: le tue ali ti tirano fuori dal mare con la stessa facilità con cui ti sollevano dalla riva. Se porti troppo peso, però, non ti sollevano affatto. In questa forma non puoi ancora colpire.\n",
"rov_compendium_skadi_tear_cold_nothing_wakes_stone": "La lacrima è fredda. Niente si sveglia nella pietra finché la regina della montagna non è caduta.\n", "rov_compendium_skadi_tear_cold_nothing_wakes_stone": "La lacrima è fredda. Niente si sveglia nella pietra finché la regina della montagna non è caduta.\n",
"rov_compendium_skadi_title": "Segreti di Skadi", "rov_compendium_skadi_title": "Segreti di Skadi",
"rov_compendium_skadi_winter_incarnate_passive": "[Sblocco Regina] Inverno incarnato (passiva):", "rov_compendium_skadi_winter_incarnate_passive": "[Sblocco Regina] Inverno incarnato (passiva):",
@ -216,9 +218,9 @@
"rov_compendium_trenta_purple_rain_g_key": "[Sblocco Antico] Purple Rain (tasto 'G'):", "rov_compendium_trenta_purple_rain_g_key": "[Sblocco Antico] Purple Rain (tasto 'G'):",
"rov_compendium_trenta_sap_heartwood_conduct_lightning_turn": "Linfa e durame conducono il fulmine e respingono i morti: subisci metà dei danni da fulmine e da spirito. Ma la legna da ardere brucia e l'ascia del boscaiolo morde ancora: subisci una volta e mezza i danni da fuoco e da taglio. Carne, pesce, uova e miele non riesci a mandarli giù; ti sostiene solo ciò che cresce dalla terra, e lo fa $1 volte più a lungo che per un corpo normale.\n", "rov_compendium_trenta_sap_heartwood_conduct_lightning_turn": "Linfa e durame conducono il fulmine e respingono i morti: subisci metà dei danni da fulmine e da spirito. Ma la legna da ardere brucia e l'ascia del boscaiolo morde ancora: subisci una volta e mezza i danni da fuoco e da taglio. Carne, pesce, uova e miele non riesci a mandarli giù; ti sostiene solo ciò che cresce dalla terra, e lo fa $1 volte più a lungo che per un corpo normale.\n",
"rov_compendium_trenta_secrets_heartwood": "I segreti del durame\n", "rov_compendium_trenta_secrets_heartwood": "I segreti del durame\n",
"rov_compendium_trenta_spray_toxic_pollen_bursts_out": "Uno spruzzo di polline tossico esplode fino a $1 metri: ogni alleato colpito viene curato di $2, ogni nemico viene avvelenato per $3. Ricarica di $4 secondi, ridotta a $5 secondi da trasformato in Muspell.\n", "rov_compendium_trenta_spray_toxic_pollen_bursts_out": "Uno spruzzo di polline tossico esplode fino a $1 metri: tu e ogni alleato colpito venite curati di $2, ogni nemico viene avvelenato per $3. Ricarica di $4 secondi, ridotta a $5 secondi da trasformato in Muspell.\n",
"rov_compendium_trenta_stand_still_daylight_roof_over": "Resta fermo alla luce del giorno, con sopra la testa nient'altro che cielo, per $1 secondi di fila, e le radici attecchiscono: seguono $2 impulsi di cura, ciascuno del $3% della salute massima, insieme a un bonus Riposato di $4 minuti, più lungo per ogni boss che hai abbattuto.\n", "rov_compendium_trenta_stand_still_daylight_roof_over": "Resta fermo alla luce del giorno, con sopra la testa nient'altro che cielo, per $1 secondi di fila, e le radici attecchiscono: seguono $2 impulsi di cura, ciascuno del $3% della salute massima, insieme a un bonus Riposato di $4 minuti, più lungo per ogni boss che hai abbattuto.\n",
"rov_compendium_trenta_swamp_has_nothing_left_spoil": "La palude non ha più niente da guastare in te. Il veleno non può toccarti, l'effetto Bagnato non può colpirti, e nuotare non costa stamina.\n", "rov_compendium_trenta_swamp_has_nothing_left_spoil": "La palude non ha più niente da guastare in te. Il veleno non può toccarti, l'effetto Bagnato non può colpirti, e nuotare non costa stamina. In acqua la stamina torna persino, piano piano.\n",
"rov_compendium_trenta_swarm_hornets_has_made_its": "Uno sciame di calabroni ha fatto casa tra i tuoi rami e non se ne va più. Ogni nemico che arriva entro $1 metri viene punto per $2 danni da veleno e perforanti ogni $3 secondi, finché non si allontana o cade.\n", "rov_compendium_trenta_swarm_hornets_has_made_its": "Uno sciame di calabroni ha fatto casa tra i tuoi rami e non se ne va più. Ogni nemico che arriva entro $1 metri viene punto per $2 danni da veleno e perforanti ogni $3 secondi, finché non si allontana o cade.\n",
"rov_compendium_trenta_take_shape_young_elder_root": "Prendi la forma di un giovane Antico, radici e rovi fatti furia. Il tasto sinistro pesta il terreno per $1 danni in un anello intorno a te, il destro scaglia una punta di radice che perfora per $2, ed entrambi crescono con la tua abilità a mani nude. Purple Rain risponde ancora al tuo richiamo mentre sei trasformato, con la sua ricarica più breve.\n", "rov_compendium_trenta_take_shape_young_elder_root": "Prendi la forma di un giovane Antico, radici e rovi fatti furia. Il tasto sinistro pesta il terreno per $1 danni in un anello intorno a te, il destro scaglia una punta di radice che perfora per $2, ed entrambi crescono con la tua abilità a mani nude. Purple Rain risponde ancora al tuo richiamo mentre sei trasformato, con la sua ricarica più breve.\n",
"rov_compendium_trenta_thorns_passive": "[Sblocco Moder] Spine (passiva):", "rov_compendium_trenta_thorns_passive": "[Sblocco Moder] Spine (passiva):",
@ -238,5 +240,9 @@
"rov_compendium_warvulture_goes_where_look_goes_as": "Va dove guardi, e va finché vuoi restare in aria: $1 metri al secondo non gli costano niente. Tieni premuto il tasto di corsa e ti dà $2 per $3 secondi, non un momento di più: in un uccello c'è solo tanta fretta. Lascia andare e il vento gli torna dentro in $4 secondi, in aria. Non devi mai atterrare per questo.\n", "rov_compendium_warvulture_goes_where_look_goes_as": "Va dove guardi, e va finché vuoi restare in aria: $1 metri al secondo non gli costano niente. Tieni premuto il tasto di corsa e ti dà $2 per $3 secondi, non un momento di più: in un uccello c'è solo tanta fretta. Lascia andare e il vento gli torna dentro in $4 secondi, in aria. Non devi mai atterrare per questo.\n",
"rov_compendium_warvulture_vulture_s_head_kept_stick": "La testa di un avvoltoio infilata su un bastone, e l'uccello le risponde. Sollevala e l'avvoltoio torna sotto di te. Sollevala di nuovo e ti porta giù, sordo a te finché non arriva il terreno; una terza volta ti lascia andare dove sei.\n", "rov_compendium_warvulture_vulture_s_head_kept_stick": "La testa di un avvoltoio infilata su un bastone, e l'uccello le risponde. Sollevala e l'avvoltoio torna sotto di te. Sollevala di nuovo e ti porta giù, sordo a te finché non arriva il terreno; una terza volta ti lascia andare dove sei.\n",
"rov_compendium_warvulture_war_vulture": "\n-- L'AVVOLTOIO DA GUERRA --\n", "rov_compendium_warvulture_war_vulture": "\n-- L'AVVOLTOIO DA GUERRA --\n",
"rov_compendium_warvulture_what_bird_has_left_bar": "Ciò che resta all'uccello è la barra sotto la tua.\n" "rov_compendium_warvulture_what_bird_has_left_bar": "Ciò che resta all'uccello è la barra sotto la tua.\n",
"rov_compendium_skeleton_diet_bones": "Nessuna fame ti muove e nessun pasto può aiutarti: il cibo dei mortali non è niente per ossa secche. Al suo posto i morti si rafforzano man mano che i loro superiori cadono: al tuo grado attuale hai +$1 di salute massima.",
"rov_compendium_skeleton_diet_mortal": "Hai conservato le abitudini della carne: mangi come i vivi, e la tua salute viene dai pasti, non dal tuo grado.",
"rov_compendium_skeleton_effort_none": "Nemmeno la fatica ti stanca: non hai stamina da spendere.",
"rov_compendium_skeleton_effort_mortal": "La fatica ti stanca come stanca i vivi, e spendi stamina come chiunque altro."
} }

View file

@ -45,12 +45,14 @@
"rov_hover_trenta_ready_empty": "pronto: $1 $2\n[<color=yellow><b>$KEY_Use</b></color>] Svuotala", "rov_hover_trenta_ready_empty": "pronto: $1 $2\n[<color=yellow><b>$KEY_Use</b></color>] Svuotala",
"rov_hover_trenta_rotting_minutes_left": "sta marcendo, mancano $1 minuti", "rov_hover_trenta_rotting_minutes_left": "sta marcendo, mancano $1 minuti",
"rov_hover_trol_call_warbands": "\n[<color=yellow><b>$KEY_Use</b></color>] Chiama le bande da guerra", "rov_hover_trol_call_warbands": "\n[<color=yellow><b>$KEY_Use</b></color>] Chiama le bande da guerra",
"rov_hover_trol_grab_log": "\n[<color=yellow><b>$1</b></color>] Afferra il tronco", "rov_hover_trol_grab_log": "\n[<color=yellow><b>$KEY_Use</b></color>] Afferra il tronco",
"rov_hover_trol_warbands": "bande da guerra $1/$2", "rov_hover_trol_warbands": "bande da guerra $1/$2",
"rov_hover_trol_yagluth_drop_hand_buys_king": "\n(un bottino di Yagluth in mano compra la testa di un re, e altre due bande)", "rov_hover_trol_yagluth_drop_hand_buys_king": "\n(un bottino di Yagluth in mano compra la testa di un re, e altre due bande)",
"rov_hover_ward_personal": "Personale", "rov_hover_ward_personal": "Personale",
"rov_hover_ward_race_menu_ward_progression_open": "$rov_piece_racemenuward_name\nProgressione $1 - $2 ($3/$4)\n[<color=yellow><b>$KEY_Use</b></color>] Apri\n[<color=yellow><b>Usa oggetto</b></color>] Offri una reliquia di boss", "rov_hover_ward_race_menu_ward_progression_open": "$rov_piece_racemenuward_name\nProgressione $1 - $2 ($3/$4)\n[<color=yellow><b>$KEY_Use</b></color>] Apri\n[<color=yellow><b>Usa oggetto</b></color>] Offri una reliquia di boss",
"rov_hover_ward_world": "del mondo", "rov_hover_ward_world": "del mondo",
"rov_hover_boneship_roster": "\nmischia $1/$2 di $3\narcieri $4/$5 di $6\na bordo $7", "rov_hover_boneship_roster": "\nmischia $1/$2 di $3\narcieri $4/$5 di $6\na bordo $7",
"rov_hover_boneship_bone_hand": "\nosso in mano per comprare un posto" "rov_hover_boneship_bone_hand": "\nosso in mano per comprare un posto",
"rov_hover_alfar_inngangskista": "Inngangskista (ingresso)",
"rov_hover_alfar_eldividarkista": "Eldividarkista (combustibile)"
} }

View file

@ -81,8 +81,10 @@
"rov_item_trenta_rotseed_name": "Seme marcio", "rov_item_trenta_rotseed_name": "Seme marcio",
"rov_item_trol_giantslog_desc": "Un enorme tronco d'albero brandito come arma.", "rov_item_trol_giantslog_desc": "Un enorme tronco d'albero brandito come arma.",
"rov_item_trol_giantslog_name": "Tronco del gigante", "rov_item_trol_giantslog_name": "Tronco del gigante",
"rov_item_trolshammer_desc": "Un martello brandito da qualcosa che non ha mai dovuto chinarsi sotto una porta. Costruisce tutto ciò che costruisce quello normale, con gli stessi materiali, e lo fa semplicemente più grande.", "rov_item_trolshammer_desc": "Un martello brandito da qualcosa che non ha mai dovuto chinarsi sotto una porta. Costruisce tutto ciò che costruisce quello normale, con gli stessi materiali, e lo fa semplicemente più grande. Tieni premuto Alt e usa la rotellina per scegliere quanto.",
"rov_item_trolshammer_name": "Martello del Trol", "rov_item_trolshammer_name": "Martello del Trol",
"rov_item_shrinkhammer_name": "Martello Riduttore",
"rov_item_shrinkhammer_desc": "Un martello fine per i lavori piccoli. Costruisce tutto ciò che costruisce quello normale, con gli stessi materiali, fino a un quarto della grandezza. Tieni premuto Alt e usa la rotellina per sceglierla.",
"rov_item_warvulture_desc": "La testa di un avvoltoio, conservata. Sollevala e l'uccello torna sotto di te, e ti porterà finché vorrai restare in aria, anche se ha solo un po' di slancio prima di mettersi a planare.", "rov_item_warvulture_desc": "La testa di un avvoltoio, conservata. Sollevala e l'uccello torna sotto di te, e ti porterà finché vorrai restare in aria, anche se ha solo un po' di slancio prima di mettersi a planare.",
"rov_item_warvulture_name": "Avvoltoio da guerra", "rov_item_warvulture_name": "Avvoltoio da guerra",
"rov_piece_aswid_bloodrefinery_desc": "Entra carne, entra osso, e quel che resta di entrambi esce rosso.", "rov_piece_aswid_bloodrefinery_desc": "Entra carne, entra osso, e quel che resta di entrambi esce rosso.",

View file

@ -18,6 +18,7 @@
"rov_msg_aswid_vae_victis": "Vae Victis", "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_aswid_what_horrible_night_have_curse": "what a horrible night to have a curse",
"rov_msg_aswid_bat_cooldown": "Il tuo sangue non è pronto a spiccare il volo di nuovo ($1s)", "rov_msg_aswid_bat_cooldown": "Il tuo sangue non è pronto a spiccare il volo di nuovo ($1s)",
"rov_msg_aswid_bat_combat_lock": "Il sangue ti ribolle per lo scontro, non puoi spiccare il volo ($1s)",
"rov_msg_aswid_bat_form_fades": "La forma di pipistrello svanisce", "rov_msg_aswid_bat_form_fades": "La forma di pipistrello svanisce",
"rov_msg_aswid_bat_too_heavy_to_beat": "Troppo pesante per battere le ali. Puoi solo planare", "rov_msg_aswid_bat_too_heavy_to_beat": "Troppo pesante per battere le ali. Puoi solo planare",
"rov_msg_aswid_too_heavy_for_bat": "Porti troppo peso per prendere la forma di pipistrello", "rov_msg_aswid_too_heavy_for_bat": "Porti troppo peso per prendere la forma di pipistrello",
@ -117,6 +118,7 @@
"rov_msg_skadi_are_moder": "Sei Moder!", "rov_msg_skadi_are_moder": "Sei Moder!",
"rov_msg_skadi_dragon_form_cooldown": "La forma di drago è in ricarica ($1:$2).", "rov_msg_skadi_dragon_form_cooldown": "La forma di drago è in ricarica ($1:$2).",
"rov_msg_skadi_dragon_form_fades": "La tua forma di drago svanisce.", "rov_msg_skadi_dragon_form_fades": "La tua forma di drago svanisce.",
"rov_msg_skadi_too_heavy_to_fly": "Porti troppo peso perché il Drake possa alzarsi in volo",
"rov_msg_skadi_dumped_dragon_drake_fader_debug": "Info di debug Dragon/Drake/Fader scritte nella console!", "rov_msg_skadi_dumped_dragon_drake_fader_debug": "Info di debug Dragon/Drake/Fader scritte nella console!",
"rov_msg_skadi_needs_stonecutter_cut_at": "Ha bisogno di uno scalpellino per essere tagliato.", "rov_msg_skadi_needs_stonecutter_cut_at": "Ha bisogno di uno scalpellino per essere tagliato.",
"rov_msg_skadi_not_enough_stamina": "Stamina insufficiente", "rov_msg_skadi_not_enough_stamina": "Stamina insufficiente",
@ -227,6 +229,7 @@
"rov_msg_alfar_nexus_built": "Fatto: $1", "rov_msg_alfar_nexus_built": "Fatto: $1",
"rov_msg_alfar_nexus_no_crystals": "Il nucleo non ha ancora cristalli.", "rov_msg_alfar_nexus_no_crystals": "Il nucleo non ha ancora cristalli.",
"rov_msg_alfar_nexus_collected": "Cristalli presi: $1", "rov_msg_alfar_nexus_collected": "Cristalli presi: $1",
"rov_msg_alfar_graf_cooldown": "I droni non sono ancora pronti ($1s).",
"rov_msg_alfar_graf_materials": "I droni vogliono $1 pietra e $2 selce.", "rov_msg_alfar_graf_materials": "I droni vogliono $1 pietra e $2 selce.",
"rov_msg_thrall_refusal_alfar": "Il costrutto non conosce la tua luce.", "rov_msg_thrall_refusal_alfar": "Il costrutto non conosce la tua luce.",
"rov_msg_thrall_refusal_alfar_drone": "Il drone non prende ordini. Lavora." "rov_msg_thrall_refusal_alfar_drone": "Il drone non prende ordini. Lavora."
@ -237,5 +240,10 @@
"rov_msg_build_limit_alfar_chest": "Questo nucleo ne ha gia' una nel suo raggio.", "rov_msg_build_limit_alfar_chest": "Questo nucleo ne ha gia' una nel suo raggio.",
"rov_msg_build_limit_alfar_ljosgard": "Questo nucleo ha gia' il suo Ljosgard." "rov_msg_build_limit_alfar_ljosgard": "Questo nucleo ha gia' il suo Ljosgard."
, ,
"rov_msg_alfar_nexus_no_store": "Il nucleo non ha niente da offrire adesso." "rov_msg_alfar_nexus_no_store": "Il nucleo non ha niente da offrire adesso.",
"rov_msg_alfar_drone_sort_nowhere": "Non so dove mettere $1. Dammi una cassa vuota, o una che contenga già $1.",
"rov_msg_alfar_drone_sort_keep": "Lascio $1 nella $2: una stazione qui lo usa.",
"rov_msg_alfar_drone_kiln_wood": "$4 è fermo. Brucio solo la legna della $3, e $1 è in un'altra cassa.",
"rov_msg_build_scale": "Grandezza $1",
"rov_hint_build_scale": "Alt: Grandezza"
} }

View file

@ -40,7 +40,9 @@
"rov_se_skadi_dragonattackcd_tooltip": "La tua forma di drago deve prepararsi prima di colpire ancora.", "rov_se_skadi_dragonattackcd_tooltip": "La tua forma di drago deve prepararsi prima di colpire ancora.",
"rov_se_skadi_form_name": "Forma di drago", "rov_se_skadi_form_name": "Forma di drago",
"rov_se_skadi_form_tooltip": "La tua forma di drago resiste ancora per un po'.", "rov_se_skadi_form_tooltip": "La tua forma di drago resiste ancora per un po'.",
"rov_se_skadi_formcd_name": "Ricarica forma di drago", "rov_se_skadi_drakecd_name": "Ricarica forma di Drake",
"rov_se_skadi_fadercd_name": "Ricarica forma di Fader",
"rov_se_skadi_formcd_name": "Ricarica forma di Moder",
"rov_se_skadi_stats_name": "Benedizione di Skadi", "rov_se_skadi_stats_name": "Benedizione di Skadi",
"rov_se_skeleton_resurrectcd_name": "Ricarica resurrezione", "rov_se_skeleton_resurrectcd_name": "Ricarica resurrezione",
"rov_se_skeleton_resurrectcd_tooltip": "Il tuo corpo scheletrico è troppo debole per risorgere di nuovo adesso.", "rov_se_skeleton_resurrectcd_tooltip": "Il tuo corpo scheletrico è troppo debole per risorgere di nuovo adesso.",

View file

@ -12,7 +12,7 @@
"rov_compendium_alfar_utsog": "[Открывается со Старейшиной] Утсог: $1% нанесённого вами урона возвращается к вам в виде эйтра.\n", "rov_compendium_alfar_utsog": "[Открывается со Старейшиной] Утсог: $1% нанесённого вами урона возвращается к вам в виде эйтра.\n",
"rov_compendium_alfar_kall": "[Открывается с Боунмассом] Калль (клавиша '$1'): притягивает к вам все лежащие предметы в радиусе $2 метров. Перезарядка $3 секунд.\n", "rov_compendium_alfar_kall": "[Открывается с Боунмассом] Калль (клавиша '$1'): притягивает к вам все лежащие предметы в радиусе $2 метров. Перезарядка $3 секунд.\n",
"rov_compendium_alfar_ljosstorm": "[Открывается с Модером] Льёсстормр (клавиша '$1'): псионическая буря на площади $2 метров на $3 секунд. Перезарядка $4 секунд.\n", "rov_compendium_alfar_ljosstorm": "[Открывается с Модером] Льёсстормр (клавиша '$1'): псионическая буря на площади $2 метров на $3 секунд. Перезарядка $4 секунд.\n",
"rov_compendium_alfar_geisli": "[Открывается с Ягнутом] Гейсли (клавиша '$1', удерживать): лазер из правой руки до $2 метров, не дольше $3 секунд, эйтр тратится каждую секунду.\n", "rov_compendium_alfar_geisli": "[Открывается с Ягнутом] Гейсли (клавиша '$1', удерживать): лазер из правой руки до $2 метров, не дольше $3 секунд, эйтр тратится каждую секунду. На геймпаде удерживайте вторичную атаку с пустыми руками.\n",
"rov_compendium_alfar_kyrr": "[Открывается с Королевой] Кюрр (клавиша '$1'): удерживает того, на кого смотрите, в стазисе $2 секунд ($3 для босса).\n", "rov_compendium_alfar_kyrr": "[Открывается с Королевой] Кюрр (клавиша '$1'): удерживает того, на кого смотрите, в стазисе $2 секунд ($3 для босса).\n",
"rov_compendium_alfar_sameining": "[Открывается с Фадером] Саминг (клавиша '$1'): архонт. Нужно $2% эйтра и готовый Хеймкалль; тратит весь эйтр и превращает его в запас защиты. До $3 секунд вы больше, быстрее и летаете, а псионический импульс бьёт всех врагов вокруг, но оружием пользоваться нельзя. В конце - по времени или с исчерпанным запасом - вас возвращают домой с одной единицей здоровья, и Хеймкалль начинает ожидание.\n", "rov_compendium_alfar_sameining": "[Открывается с Фадером] Саминг (клавиша '$1'): архонт. Нужно $2% эйтра и готовый Хеймкалль; тратит весь эйтр и превращает его в запас защиты. До $3 секунд вы больше, быстрее и летаете, а псионический импульс бьёт всех врагов вокруг, но оружием пользоваться нельзя. В конце - по времени или с исчерпанным запасом - вас возвращают домой с одной единицей здоровья, и Хеймкалль начинает ожидание.\n",
"rov_compendium_alfar_more_to_come": "Новые силы пробуждаются по мере падения великих.\n", "rov_compendium_alfar_more_to_come": "Новые силы пробуждаются по мере падения великих.\n",
@ -31,6 +31,7 @@
"rov_compendium_aswid_aswid_s_curse": "Проклятие Асвида\n", "rov_compendium_aswid_aswid_s_curse": "Проклятие Асвида\n",
"rov_compendium_aswid_bat_form_g_key_night": "[Награда: Эйктюр] Облик летучей мыши (клавиша «G», только ночью): Примите облик летучей мыши.\n", "rov_compendium_aswid_bat_form_g_key_night": "[Награда: Эйктюр] Облик летучей мыши (клавиша «G», только ночью): Примите облик летучей мыши.\n",
"rov_compendium_aswid_bat_flight": "Летучая мышь летит туда, куда вы смотрите: W — полет вперед за $1 выносливости в секунду, Shift — рывок еще за $2, S — полет назад, а если отпустить клавиши, вы ненадолго зависаете, а затем планируете вниз. Без выносливости можно только планировать.\n", "rov_compendium_aswid_bat_flight": "Летучая мышь летит туда, куда вы смотрите: W — полет вперед за $1 выносливости в секунду, Shift — рывок еще за $2, S — полет назад, а если отпустить клавиши, вы ненадолго зависаете, а затем планируете вниз. Без выносливости можно только планировать.\n",
"rov_compendium_aswid_bat_free_flight": "Свободный полет: летучая мышь летает быстро и свободно, без затрат выносливости и без ограничения веса. Прыжок — вверх, левый Ctrl — вниз, Shift — быстрее.\n",
"rov_compendium_aswid_bat_form_now_answers_by": "[Награда: Древний] Облик летучей мыши теперь доступен как ночью, так и днем.\n", "rov_compendium_aswid_bat_form_now_answers_by": "[Награда: Древний] Облик летучей мыши теперь доступен как ночью, так и днем.\n",
"rov_compendium_aswid_benedictus_et_afflictus": "[Базовое пассивное] Benedictus et Afflictus:", "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",
@ -85,14 +86,15 @@
"rov_compendium_dvergar_weapon_crossbow": "Арбалет", "rov_compendium_dvergar_weapon_crossbow": "Арбалет",
"rov_compendium_dvergar_weapon_hammer": "Молот", "rov_compendium_dvergar_weapon_hammer": "Молот",
"rov_compendium_fenrir_beast_within_physical_stats_scale": "[Базовое пассивное] Зверь внутри: Ваши физические характеристики растут с каждым убитым боссом: +$1 к броне, +$2 к урону, +$3% к скорости, +$4% к прыжку и -$5% к урону от падения.\n", "rov_compendium_fenrir_beast_within_physical_stats_scale": "[Базовое пассивное] Зверь внутри: Ваши физические характеристики растут с каждым убитым боссом: +$1 к броне, +$2 к урону, +$3% к скорости, +$4% к прыжку и -$5% к урону от падения.\n",
"rov_compendium_fenrir_cultist_form_j_key_night": "[Награда: Яглут] Облик культиста (клавиша «J», только ночью): Облик в балахоне, раздирающий врагов когтями и направляющий потоки пламени. Длится 1 минуту, перезарядка: 10 минут.\n", "rov_compendium_fenrir_cultist_form_j_key_night": "[Награда: Яглут] Облик культиста (клавиша «J», только ночью): Облик в балахоне, раздирающий врагов когтями и направляющий потоки пламени. За это приходится платить: каждый удар по нему наносит на 25% больше урона. Длится 1 минуту, перезарядка: 10 минут.\n",
"rov_compendium_fenrir_cultist_form_now_answers_by": "[Награда: Прародитель] Облик культиста теперь подчиняется как днем, так и ночью, и его можно удерживать сколько угодно.\n", "rov_compendium_fenrir_cultist_form_now_answers_by": "[Награда: Прародитель] Облик культиста теперь подчиняется как днем, так и ночью, и его можно удерживать сколько угодно.\n",
"rov_compendium_fenrir_cultist_form_s_cooldown_falls": "[Награда: Королева] Перезарядка облика культиста снижена до 5 минут (все еще только ночью, длительность 1 минута).\n", "rov_compendium_fenrir_cultist_form_s_cooldown_falls": "[Награда: Королева] Перезарядка облика культиста снижена до 5 минут (все еще только ночью, длительность 1 минута).\n",
"rov_compendium_fenrir_curse_pack": "Проклятие Стаи\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_h_key_night": "[Награда: Матерь] Облик фенринга (клавиша «H», только ночью): Станьте истинным Фенрингом — тяжелые когти, сокрушительный удар в прыжке и мощнейшая из четырех форм на данный момент. Этот облик держит строй: каждый удар по нему наносит на 30% меньше урона.\n",
"rov_compendium_fenrir_fenring_form_now_answers_by": "[Награда: Королева] Облик фенринга теперь доступен как днем, так и ночью.\n", "rov_compendium_fenrir_fenring_form_now_answers_by": "[Награда: Королева] Облик фенринга теперь доступен как днем, так и ночью.\n",
"rov_compendium_fenrir_g_now_calls_ulv_form": "[Награда: Матерь] Клавиша «G» теперь призывает облик Ульва вместо Волка и доступна и днем, и ночью.\n", "rov_compendium_fenrir_g_now_calls_ulv_form": "[Награда: Матерь] Клавиша «G» теперь призывает облик Ульва вместо Волка и доступна и днем, и ночью. Ульв — самый быстрый из ваших обликов, в нем удобно путешествовать.\n",
"rov_compendium_fenrir_senses_in_form": "В любой форме вы чувствуете любое неприрученное существо в радиусе $1 м, подсвечивая его характерным свечением, как Асвиды.\n",
"rov_compendium_fenrir_sunrise_breaks_any_night_bound": "Восход солнца прерывает любую ночную форму раньше срока и оставляет зверя истощенным, не позволяя перевоплощаться еще некоторое время.\n", "rov_compendium_fenrir_sunrise_breaks_any_night_bound": "Восход солнца прерывает любую ночную форму раньше срока и оставляет зверя истощенным, не позволяя перевоплощаться еще некоторое время.\n",
"rov_compendium_fenrir_title": "Тайны Фенрира", "rov_compendium_fenrir_title": "Тайны Фенрира",
"rov_compendium_fenrir_ulv_form_h_key_night": "[Награда: Масса костей] Облик ульва (клавиша «H», только ночью): Более тяжелая волчья форма — смертоносные укусы, по-прежнему скованные тьмой.\n", "rov_compendium_fenrir_ulv_form_h_key_night": "[Награда: Масса костей] Облик ульва (клавиша «H», только ночью): Более тяжелая волчья форма — смертоносные укусы, по-прежнему скованные тьмой.\n",
@ -140,7 +142,7 @@
"rov_compendium_skadi_one_stonecutter_holds_them_no": "Один камнерез поддерживает $1 таких стражей, и не более $2 могут находиться на расстоянии дневного перехода друг от друга. Сломайте камнерез — и сотворенный голем замрет навеки спустя $3 с.\n", "rov_compendium_skadi_one_stonecutter_holds_them_no": "Один камнерез поддерживает $1 таких стражей, и не более $2 могут находиться на расстоянии дневного перехода друг от друга. Сломайте камнерез — и сотворенный голем замрет навеки спустя $3 с.\n",
"rov_compendium_skadi_secrets_winter": "Тайны Зимы\n", "rov_compendium_skadi_secrets_winter": "Тайны Зимы\n",
"rov_compendium_skadi_skeleton_dragon_form_j_key": "[Награда: Прародитель] Облик дракона-скелета (клавиша «J»):", "rov_compendium_skadi_skeleton_dragon_form_j_key": "[Награда: Прародитель] Облик дракона-скелета (клавиша «J»):",
"rov_compendium_skadi_take_shape_frost_drake_right": "Примите облик ледяного дрейка. ПКМ поднимает вас в воздух: вы парите туда, куда смотрите; зажмите W, чтобы набирать высоту и скорость; зажмите с ней Shift, чтобы ускориться за счет выносливости; нажмите S, чтобы пятиться спиной назад, удерживая прицел. Отпустите клавиши управления — и вы замрете в воздухе на 5 секунд перед медленным снижением. Вода не удержит вас: крылья выдернут вас из морской пучины так же легко, как и с берега. В этой форме вы пока не можете атаковать.\n", "rov_compendium_skadi_take_shape_frost_drake_right": "Примите облик ледяного дрейка. ПКМ поднимает вас в воздух: вы парите туда, куда смотрите; зажмите W, чтобы набирать высоту и скорость; зажмите с ней Shift, чтобы ускориться за счет выносливости; нажмите S, чтобы пятиться спиной назад, удерживая прицел. Отпустите клавиши управления — и вы замрете в воздухе на несколько секунд перед медленным снижением. Вода не удержит вас: крылья выдернут вас из морской пучины так же легко, как и с берега. Но с перегрузом они вас не поднимут. В этой форме вы пока не можете атаковать.\n",
"rov_compendium_skadi_tear_cold_nothing_wakes_stone": "Слеза холодна. Ничто в камне не пробудится, пока владычица гор не падет.\n", "rov_compendium_skadi_tear_cold_nothing_wakes_stone": "Слеза холодна. Ничто в камне не пробудится, пока владычица гор не падет.\n",
"rov_compendium_skadi_title": "Тайны Скади", "rov_compendium_skadi_title": "Тайны Скади",
"rov_compendium_skadi_winter_incarnate_passive": "[Награда: Королева] Воплощение зимы (Пассивное):", "rov_compendium_skadi_winter_incarnate_passive": "[Награда: Королева] Воплощение зимы (Пассивное):",
@ -216,9 +218,9 @@
"rov_compendium_trenta_purple_rain_g_key": "[Награда: Древний] Purple Rain (клавиша «G»):", "rov_compendium_trenta_purple_rain_g_key": "[Награда: Древний] Purple Rain (клавиша «G»):",
"rov_compendium_trenta_sap_heartwood_conduct_lightning_turn": "Смола и сердцевина древесины проводят молнию и отваживают нежить: вы получаете половинный урон от молнии и духа. Но сухие ветви быстро разгораются, а топор дровосека безжалостен — урон от огня и рубящих атак увеличен в полтора раза. Мясо, рыба, яйца и мед противны вашей натуре; лишь то, что произрастает из земли, дает вам силы, и действует в $1 раз дольше, чем на обычного человека.\n", "rov_compendium_trenta_sap_heartwood_conduct_lightning_turn": "Смола и сердцевина древесины проводят молнию и отваживают нежить: вы получаете половинный урон от молнии и духа. Но сухие ветви быстро разгораются, а топор дровосека безжалостен — урон от огня и рубящих атак увеличен в полтора раза. Мясо, рыба, яйца и мед противны вашей натуре; лишь то, что произрастает из земли, дает вам силы, и действует в $1 раз дольше, чем на обычного человека.\n",
"rov_compendium_trenta_secrets_heartwood": "Тайны Сердцевины\n", "rov_compendium_trenta_secrets_heartwood": "Тайны Сердцевины\n",
"rov_compendium_trenta_spray_toxic_pollen_bursts_out": "Выброс токсичной пыльцы в радиусе $1 м: каждый союзник внутри исцеляется на $2 ед., а каждый враг отравляется на $3 ед. урона. Перезарядка: $4 с (сокращается до $5 с в облике Муспелля).\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_swamp_has_nothing_left_spoil": "Болотам нечего осквернять в вашем теле. Яд не может навредить вам, эффект сырости не накладывается, а плавание вовсе не расходует выносливость. В воде выносливость даже понемногу восстанавливается.\n",
"rov_compendium_trenta_swarm_hornets_has_made_its": "Рой шершней свил гнездо в вашей кроне. Любой враг, приблизившийся на расстояние ближе $1 м, получает $2 ед. урона ядом и колющими ударами каждые $3 с, пока не отступит или не погибнет.\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", "rov_compendium_trenta_take_shape_young_elder_root": "Примите облик юного Древнего, воплотив ярость корней и терновника. ЛКМ сотрясает землю, нанося $1 ед. урона в круге вокруг вас, а ПКМ выпускает пронзающий корень на $2 ед. урона — мощь обоих приемов зависит от навыка «Без оружия». В этой форме вы по-прежнему можете призывать Purple Rain с уменьшенным временем перезарядки.\n",
"rov_compendium_trenta_thorns_passive": "[Награда: Матерь] Шипы (Пассивное):", "rov_compendium_trenta_thorns_passive": "[Награда: Матерь] Шипы (Пассивное):",
@ -238,5 +240,9 @@
"rov_compendium_warvulture_goes_where_look_goes_as": "Она летит туда, куда обращен ваш взор, и летит так долго, как вы того пожелаете: полет со скоростью $1 м/с не стоит птице никаких сил. Зажмите клавишу бега — и она выдаст рывок со скоростью $2 м/с на $3 с, не дольше: птичьи силы не безграничны. Отпустите бег, и дыхание вернется к ней через $4 с прямо в воздухе. Садиться на землю не придется.\n", "rov_compendium_warvulture_goes_where_look_goes_as": "Она летит туда, куда обращен ваш взор, и летит так долго, как вы того пожелаете: полет со скоростью $1 м/с не стоит птице никаких сил. Зажмите клавишу бега — и она выдаст рывок со скоростью $2 м/с на $3 с, не дольше: птичьи силы не безграничны. Отпустите бег, и дыхание вернется к ней через $4 с прямо в воздухе. Садиться на землю не придется.\n",
"rov_compendium_warvulture_vulture_s_head_kept_stick": "Голова стервятника на шесте, и хищная птица повинуется ей. Поднимите ее — и птица опустится вам под ноги. Поднимите снова — и она понесет вас к земле, не слушая команд до самого приземления, а поднятая в третий раз — отпустит вас на лету.\n", "rov_compendium_warvulture_vulture_s_head_kept_stick": "Голова стервятника на шесте, и хищная птица повинуется ей. Поднимите ее — и птица опустится вам под ноги. Поднимите снова — и она понесет вас к земле, не слушая команд до самого приземления, а поднятая в третий раз — отпустит вас на лету.\n",
"rov_compendium_warvulture_war_vulture": "\n-- БОЕВОЙ СТЕРВЯТНИК --\n", "rov_compendium_warvulture_war_vulture": "\n-- БОЕВОЙ СТЕРВЯТНИК --\n",
"rov_compendium_warvulture_what_bird_has_left_bar": "Остаток выносливости птицы отображается шкалой под вашей собственной.\n" "rov_compendium_warvulture_what_bird_has_left_bar": "Остаток выносливости птицы отображается шкалой под вашей собственной.\n",
"rov_compendium_skeleton_diet_bones": "Голод не движет вами, и никакая еда вам не поможет: смертная пища ничто для сухих костей. Взамен мёртвые крепнут по мере падения своих владык: на вашей нынешней ступени у вас +$1 к максимальному здоровью.",
"rov_compendium_skeleton_diet_mortal": "Вы сохранили привычки плоти: вы едите, как живые, и ваше здоровье даёт пища, а не ступень.",
"rov_compendium_skeleton_effort_none": "И усилия вас не утомляют: выносливости у вас нет вовсе.",
"rov_compendium_skeleton_effort_mortal": "Усилия утомляют вас, как живых, и вы тратите выносливость, как все."
} }

View file

@ -45,12 +45,14 @@
"rov_hover_trenta_ready_empty": "готово: $1 $2\n[<color=yellow><b>$KEY_Use</b></color>] Опустошить", "rov_hover_trenta_ready_empty": "готово: $1 $2\n[<color=yellow><b>$KEY_Use</b></color>] Опустошить",
"rov_hover_trenta_rotting_minutes_left": "гниет, осталось $1 мин", "rov_hover_trenta_rotting_minutes_left": "гниет, осталось $1 мин",
"rov_hover_trol_call_warbands": "\n[<color=yellow><b>$KEY_Use</b></color>] Созвать боевые дружины", "rov_hover_trol_call_warbands": "\n[<color=yellow><b>$KEY_Use</b></color>] Созвать боевые дружины",
"rov_hover_trol_grab_log": "\n[<color=yellow><b>$1</b></color>] Взять бревно", "rov_hover_trol_grab_log": "\n[<color=yellow><b>$KEY_Use</b></color>] Взять бревно",
"rov_hover_trol_warbands": "дружины $1/$2", "rov_hover_trol_warbands": "дружины $1/$2",
"rov_hover_trol_yagluth_drop_hand_buys_king": "\n(трофей Яглута в руке позволит насадить голову конунга и нанять еще две дружины)", "rov_hover_trol_yagluth_drop_hand_buys_king": "\n(трофей Яглута в руке позволит насадить голову конунга и нанять еще две дружины)",
"rov_hover_ward_personal": "Личный", "rov_hover_ward_personal": "Личный",
"rov_hover_ward_race_menu_ward_progression_open": "$rov_piece_racemenuward_name\n$1 прогресс — $2 ($3/$4)\n[<color=yellow><b>$KEY_Use</b></color>] Открыть\n[<color=yellow><b>Использовать предмет</b></color>] Пожертвовать реликвию босса", "rov_hover_ward_race_menu_ward_progression_open": "$rov_piece_racemenuward_name\n$1 прогресс — $2 ($3/$4)\n[<color=yellow><b>$KEY_Use</b></color>] Открыть\n[<color=yellow><b>Использовать предмет</b></color>] Пожертвовать реликвию босса",
"rov_hover_ward_world": "Общий", "rov_hover_ward_world": "Общий",
"rov_hover_boneship_roster": "\nближний бой $1/$2 из $3\nлучники $4/$5 из $6\nна борту $7", "rov_hover_boneship_roster": "\nближний бой $1/$2 из $3\nлучники $4/$5 из $6\nна борту $7",
"rov_hover_boneship_bone_hand": "\nкость в руке — купить место" "rov_hover_boneship_bone_hand": "\nкость в руке — купить место",
"rov_hover_alfar_inngangskista": "Инганг-киста (вход)",
"rov_hover_alfar_eldividarkista": "Эльдивидар-киста (топливо)"
} }

View file

@ -81,8 +81,10 @@
"rov_item_trenta_rotseed_name": "Семя гнили", "rov_item_trenta_rotseed_name": "Семя гнили",
"rov_item_trol_giantslog_desc": "Исполинский ствол векового дерева, используемый как сокрушительное оружие.", "rov_item_trol_giantslog_desc": "Исполинский ствол векового дерева, используемый как сокрушительное оружие.",
"rov_item_trol_giantslog_name": "Бревно великана", "rov_item_trol_giantslog_name": "Бревно великана",
"rov_item_trolshammer_desc": "Молот, которым размахивает тот, кому никогда не приходилось пригибаться в дверях. Возводит те же постройки, что и обычный молот, из тех же материалов, но с истинным тролльим размахом.", "rov_item_trolshammer_desc": "Молот, которым размахивает тот, кому никогда не приходилось пригибаться в дверях. Возводит те же постройки, что и обычный молот, из тех же материалов, но с истинным тролльим размахом. Зажмите Alt и крутите колесо мыши, чтобы выбрать, насколько.",
"rov_item_trolshammer_name": "Молот тролля", "rov_item_trolshammer_name": "Молот тролля",
"rov_item_shrinkhammer_name": "Молот-уменьшитель",
"rov_item_shrinkhammer_desc": "Тонкий молот для мелкой работы. Возводит те же постройки, что и обычный молот, из тех же материалов, вплоть до четверти размера. Зажмите Alt и крутите колесо мыши, чтобы выбрать размер.",
"rov_item_warvulture_desc": "Высушенная голова стервятника. Поднимите ее — и птица опустится вам под ноги, неся вас вперед, пока вам не надоест (хотя силы для рывка у нее быстро сменяются плавным парением).", "rov_item_warvulture_desc": "Высушенная голова стервятника. Поднимите ее — и птица опустится вам под ноги, неся вас вперед, пока вам не надоест (хотя силы для рывка у нее быстро сменяются плавным парением).",
"rov_item_warvulture_name": "Боевой стервятник", "rov_item_warvulture_name": "Боевой стервятник",
"rov_piece_aswid_bloodrefinery_desc": "Загрузите плоть, бросьте кости — и то, что от них останется, выйдет алым соком.", "rov_piece_aswid_bloodrefinery_desc": "Загрузите плоть, бросьте кости — и то, что от них останется, выйдет алым соком.",

Some files were not shown because too many files have changed in this diff Show more