Compare commits

..

411 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
5b3b2ac88d refactor(eyes): bake the tuned eye corrections in, drop the sliders
The Eyes Position sections were a tuning tool. Their per-body, per-eye values
from playtest now live in RaceEyeTuning as constants, so every player gets
the tuned faces and Configuration Manager loses four sections. The Aswid -
Eyes section stays for now.
2026-10-27 17:46:36 +01:00
f7a4494b39 feat(eyes): male per-eye defaults from playtest
Male Aswid, Alfar and Dvergar eye values dialled in on screen become the
defaults of their Eyes Position sections, so male faces no longer start from
the untuned code placement.
2026-10-27 17:44:49 +01:00
06b7fc165c feat(eyes): Dvergar female right-eye defaults from playtest 2026-10-27 16:17:03 +01:00
a214a604e1 feat(eyes): Aswid and Alfar female per-eye defaults from playtest 2026-10-27 16:16:46 +01:00
132d7e034f feat(eyes): per-eye sliders, Aswid female defaults from playtest
Each Eyes Position section now has a set per body and per eye (the
character's own left and right), because the face is not symmetric enough for
one set to fit both eyes. The Aswid female defaults are the per-eye values
dialled in on screen; Alfar and Dvergar copy their female values to both eyes.
The old shared keys are dropped: they only ever existed in test builds.
2026-10-27 16:03:24 +01:00
ffba40650e fix(aswid): eye position sliders rotate on the face's axes
The Eyes Position rotation was added to the Aswid's own twist, which works on
the head bone's raw axes: bone X points out of the face and bone Z sideways,
so Rotation X rolled the eyes and the mirrored Rotation Z tipped one eye up
and the other down. The slider rotation is now conjugated by the face frame,
so X tips, Y turns toward the temple and Z raises the outer corner on both
eyes alike. The female rotation defaults go back to 0, since the old numbers
meant other axes.
2026-10-27 15:40:52 +01:00
20c12724fd feat(eyes): female eye defaults from playtest
The female slider values dialled in on screen for the Dvergar, Alfar and Aswid
become the defaults of their Eyes Position sections, so a fresh install lands
on the tuned faces. The Sverm keeps zeros: its helmet hides the eyes.
2026-10-27 15:38:52 +01:00
8b2b5180ed feat(eyes): per-race eye position sliders in Configuration Manager
One 'Eyes Position - <race>' section each for the Alfar, Aswid, Dvergar and
Sverm, with a female and a male set: forward, height, separation and size,
plus rotation X/Y/Z for the Alfar and Aswid. All are deltas on the computed
placement (0 and size 1 change nothing), read live, and left local by
ConfigSync because they only change how this client draws faces.
2026-10-27 15:21:19 +01:00
a7e9996441 fix(eyes): lower female eyes further, push Alfar/Dvergar out, enlarge Aswid points
Playtest on female characters: every race's eyes still sat about an eye-height
above the painted ones. Female height shift goes from -6 to -14 mm. Alfar and
Dvergar centres move 4 mm forward out of the face, and the Aswid socket goes
from 0.5 to 0.75 of the borrowed size so it covers the painted eye.
2026-10-27 15:15:10 +01:00
026def2fde fix(eyes): female face placement, smaller Dvergar/Aswid eyes, grey Alfar eyes
The female body maps the painted eyes about 6 mm lower and a quarter closer
together than the male one (read from bodymale/bodyfem and the skin UVs), so
every race's male-tuned eyes sat on the female brow. PlayerFace moves them for
the Dvergar, Aswid, Sverm and Alfar.

Dvergar eyes shrink to an 18 mm radius. The Aswid's borrowed sockets are
halved before the config multiplier and the smoke is off by default.

Alfar eyes become slanted, wrapped black almonds with a wet sheen. They are
placed in fixed head-local units: the live lossyScale under the non-uniform
Alfar body drifted as the head turned, and the 0.5 s cosmetic pass made the
eyes trail the face.
2026-10-27 15:01:44 +01:00
76085f14b0 Merge remote-tracking branch 'origin/main' into localisation 2026-10-26 16:09:04 +01:00
a927a6d4b3 chore(release): v1.6.1 - the Aswid rebalance
Version 1.6.1 in the manifests and PluginVersion. README: the New in
v1.6.1 block and the changelog, crediting the Discord reports.
2026-10-26 16:08:55 +01:00
876309e85c Merge branch 'fix-readme-texts': README matches the code; stale copies removed 2026-10-26 16:06:05 +01:00
04e540a89d Merge branch 'balance-aswid': the Aswid rebalance - stamina, devour, bat flight, weaknesses 2026-10-26 16:06:05 +01:00
1051324b56 chore: drop the stale README copies in JotunnModStub
The root README is the one players get: package.ps1 and nexus-readme.py
read it. JotunnModStub/README.md and Package/README.md had drifted for
versions, and edits kept landing in them by mistake. Both are gone. The
csproj links the root README, the publish scripts copy it into Package/
at release, and that generated copy is ignored.
2026-10-26 16:04:26 +01:00
cb546ee5e3 docs(readme): describe the Aswid rebalance and match other races to the code
The rebalance's README edits had gone into JotunnModStub/README.md and
Package/README.md, stale copies the build does not ship; the root README
is the one package.ps1 and nexus-readme.py read. It now has them.

Checked every race section against the code and fixed what drifted:
Draugh (unlocks rewritten from the code: no Wet immunity or faster swim,
Rotting Edge instead of Toxic Trace, poison and frost immunity tiers,
no skill loss rather than Corpse Run), Skadi (Freezing immunity at
Yagluth, frost immunity and Frost Aura at the Queen), Furling (+10%
speed), Trenta (camouflage covers six creature families, not everything)
and the Aswid (Auspex is a Moder unlock, the Queen line no longer claims
a fire/frost/spirit weakness).
2026-10-26 16:02:45 +01:00
c76341af0d feat(aswid): running water covers rivers and lakes; sway on boats
Open water now means any water: swimming in it, or flying over a metre
or more of it, sea, river or lake. Standing on anything solid stays safe,
so docks, bridges and wading do not count. On a boat there is still no
burn or drain, but the camera keeps swaying. 'Ocean Only' restores the
sea-only behaviour, and the settings say Open Water instead of Open Sea.

Also rewrites the README's per-boss Aswid section from the code: it
listed stats, unlocks and an aura that no longer exist.
2026-10-26 15:49:05 +01:00
a00db24ebd fix(aswid): name the food in the full-stomach devour message
$msg_nomore carries a $1 for the food's name, and the devour sent it
bare, so players read "can't eat more $1". Filled in the same way
vanilla's CanEat and the Trol do.
2026-10-26 15:30:01 +01:00
5c41d80cae feat(aswid): running water weakness and a seasick camera
Swimming costs double stamina, scaled on vanilla's own swim charge so
its drowning check does the rest at high settings. Over deep water in
the Ocean, swimming or flying, the Aswid loses health and stamina each
second; a boat protects. A gentle camera roll plays while the sea hurts,
kept local through ConfigSync so a server cannot force it on anyone.
2026-10-26 15:26:25 +01:00
9149d3f0b5 feat(aswid): sunlight, fire and pierce weaknesses
Each has its own switch under 'Aswid - Weaknesses'. Sunlight: by day
under open sky, slower regen and movement and a slow burn that stops at
30% health; roofs, dungeons, Swamp, Mistlands, night and Eclipse shield
you. Fire +25% until Fader, pierce +20%; both applied after resistances
and armor, so meads still help and Mist Form stays pierce-immune.
2026-10-26 15:12:05 +01:00
77cdc67e97 feat(aswid): bat flies on the Skadi's directed flight
The bat flew on vanilla's debug-fly flag: 50 m/s, free, blind to carry
weight, and invisible to monsters until six patches lied about the flag.
It now flies on m_flying with the drake's controls, moved out of
SkadiPatches into a shared DirectedFlight core that both forms feed
their own numbers into. Powered flight and the sprint cost stamina; out
of stamina the bat glides. Encumbered flight costs 15% more, or is
blocked with 'While Encumbered'. Optional duration and cooldown, off by
default. The aggro/damage patches, the debug-fly speed patch and their
three settings are removed; the drake's behaviour is unchanged.
2026-10-26 14:26:42 +01:00
824ddd8956 feat(aswid): Vampiric Aura is off in bat form until The Queen
A bat could glide over enemies that cannot reach it and drain them the
whole way. The aura now stays silent in bat form until the configurable
unlock state (7, The Queen), or always if 'Active In Bat Form' is on.
Also corrects the README's aura and Mist Form lines, which still
described the old block-to-channel aura and a weakness the code lacks.
2026-10-26 14:20:10 +01:00
83cd49c753 feat(aswid): devour feeds less health and some stamina
Devoured creatures feed 10% less health, and a share of it becomes
stamina: 60% for Meadows and Black Forest prey, 10% past them. Foods made
by the half-health formula are capped per biome, so a Troll no longer
feeds 150. The foods are rebuilt from their base values whenever a
setting changes or the server's values arrive.
2026-10-26 13:57:41 +01:00
ab0a21244d feat(aswid): replace infinite stamina with a boss-scaled pool
The Aswid shared the Skeleton's UseStamina skip, so stamina mods, foods
and skills did nothing for it. It now spends stamina, scaled by a cost
multiplier, and gets +25 max stamina plus 10 per boss added on top of its
food. The stamina bar shows again. Draugh and Skeleton are unchanged.
2026-10-26 13:54:44 +01:00
68b87d181a Merge remote-tracking branch 'origin/main' into localisation 2026-10-25 18:25:22 +01:00
7cd0aa234d Merge branch 'fix-alfar-texts': Kall, Utsog and the Nexus limit described as coded 2026-10-25 18:25:10 +01:00
40202d4793 fix(alfar): the compendium and README describe Kall, Utsog and the Nexus limit the code has
Kall pulls dropped items to you; it is not a lightning wave. Utsog gives
back 15% of any damage dealt, and the compendium printed it as 1500%.
One Ljoskjarne stands in every 1.6 square kilometers, not one per
square kilometer. EN/IT/RU.
2026-10-25 18:25:10 +01:00
4fcfe6fd7c Merge remote-tracking branch 'origin/main' into localisation 2026-10-25 17:58:37 +01:00
3c7b2d5f79 chore(release): v1.6.0 - the Alfar
Manifest description counts eleven races and names the Alfar. The v1.6.0
changelog picks up the Summon on Kill line change from after v1.5.15.
2026-10-25 17:58:23 +01:00
8e5f4916c2 Merge branch 'alfar': the Alfar, an eleventh race 2026-10-25 17:57:33 +01:00
Ferdinando
3f8cf1ee27 feat(alfar): v1.6.0 - the Alfar, an eleventh race
Grey, tall and thin, with black eyes. Eitr is armour and fuel (shield,
diet, soft fall, levitation), Heimkall sends a lethal blow home at one
health every 20 minutes. Caster powers from Skrid to the archon
Sameining, with on-screen cooldowns. Automated base around the
Ljoskjarne: drones, three constructs, crystals, Ljosgard, Prismavard.
Compendium page in EN/IT/RU.

README: New in block, race section, progression, station line, changelog.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-25 17:38:28 +01:00
9e9790d1e9 docs(readme): the v1.5.15 entry quotes the line that shipped
The new line goes out in v1.5.16 and is listed for that release.
2026-10-24 23:55:26 +02:00
6eb8348363 Merge branch 'fix-skeleton-raise-quote': Summon on Kill line is "Thy shall raise again." 2026-10-24 23:53:53 +02:00
0a843bad41 fix(skeleton): the Summon on Kill "on" line is "Thy shall raise again."
As written by the author; Italian "Tu rialzerai ancora.", Russian
"Ты вновь поднимешь.". README changelog line too.
2026-10-24 23:53:53 +02:00
d689834070 Merge remote-tracking branch 'origin/main' into localisation 2026-10-24 18:28:28 +02:00
20dec64fa0 chore(release): v1.5.15 - Skeleton health rebalance, Auto-Resurrect fix, Summon on Kill toggle
Skeleton max health is lower in the early and middle game, from 75 to
50 at the start and unchanged at Fader. Auto-Resurrect triggers only
on a hit that would really kill, dedicated servers included. Summon on
Kill toggles with G and shows a Raise the Dead icon while on.

README: New in block, Queen line, changelog entry.
2026-10-24 18:28:17 +02:00
de10b1795b Merge branch 'balance-skeleton-hp': lower Skeleton max-health bonus in the early and middle game 2026-10-24 16:52:50 +02:00
18593ae1d3 balance(skeleton): lower max-health bonus in the early and middle game
+25/+45/+65/+90/+125/+165/+215/+275 from no bosses to Fader, was
+50/+80/+110/+140/+170/+200/+230/+275. A fresh Skeleton starts at 50
max health instead of 75; Fader stays at 300. Asked for by several
players over three months, last by Jondar Korric. A Skeleton never eats
and never spends stamina, so it ran well ahead of a fed viking.

The hidden foods that carry its regeneration are picked to match the
new totals, so early-tier regen drops with them. README progression
updated; the compendium reads the value from code.
2026-10-24 16:36:52 +02:00
9308ce062c Merge branch 'fix-skeleton-resurrect-summon-toggle': Auto-Resurrect on the real deathblow, Summon on Kill toggle 2026-10-24 15:50:51 +02:00
e41f7b610e revert(skeleton): drop the Summon on Kill aura, keep the icon
Neither the Draugr's evil_smoke nor the torch smoke showed in game once
tinted dark. The Raise the Dead icon stays, with its per-player switch.
2026-10-24 15:50:05 +02:00
3591b7e375 fix(skeleton): the Summon on Kill aura borrows the torch smoke
The Draugr's evil_smoke is on 'Lux Lit Particles/ Bumped' and showed
nothing in game once tinted dark. The torch's own Smoke, from the
prefab the head flame burns from, is the grey everyone sees above a
torch; darkened to (0.08, 0.08, 0.09) at 0.45 alpha.
2026-10-24 15:44:16 +02:00
98b1a1b5f3 feat(skeleton): dark aura while Summon on Kill is on, archaic toggle messages
Beside the Raise the Dead icon, a faint near-black smoke now rises off
the whole body while Summon on Kill is on: the Draugr's looping smoke,
borrowed like the Draugh aura, emitted from a body-sized box in world
space. The owner writes the switch to the ZDO, so other players see
it. "Raise the Dead Icon" and "Raise the Dead Aura" under Skeleton -
Visuals let each player keep either or both, for a community vote.

The toggle now says "Thy dead shall rise again." / "Raising...
nevermore.", in English, Italian and Russian.
2026-10-24 15:38:42 +02:00
53f6fb71a2 fix(skeleton): Auto-Resurrect on the real deathblow; Summon on Kill toggle
Auto-Resurrect was decided in the Character.Damage prefix on the raw
hit: before armour, blocking and resistances, with poison and fire
counted in full. With good armour it fired on almost any hit. Damage
also runs on the attacker's owner, so on a dedicated server a mob
owned by the server or another player skipped the check entirely. It
now runs in an ApplyDamage prefix, on the victim's own client, against
the damage that is about to land. The rising-from-the-ground immunity
is checked there too.

Summon on Kill gets a toggle key (G, Skeleton - Keybinds) and a
gamepad radial entry. The choice is saved on the character, on by
default. A "Raise the Dead" status icon with the Dead Raiser's
picture shows while it is on. Texts in English, Italian and Russian.
2026-10-24 15:28:04 +02:00
fe8b3ea270 Merge remote-tracking branch 'origin/main' into localisation 2026-10-23 22:27:37 +02:00
7411680553 chore(release): v1.5.14 - Fenrir night eyes, form adrenaline, full-stomach eating
Fenrir eyes glow at night, brighter when a form is ready and yellow when
the Cultist is back. Form hits build adrenaline like a weapon hit. Race
foods replace a worn-down meal when the stomach is full. The stamina bar
comes back after leaving Aswid or Draugh. Other players see a Furling at
Furling size, and a Legacy True Form Trol hits as far as it reaches.

README: New in block, Fenrir night eyes, changelog entry, new Discord
link (also in the old JotunnModStub README).
2026-10-23 22:27:26 +02:00
e37084ac33 Merge branch 'fix-fenrir-form-adrenaline': Fenrir form hits build adrenaline like a weapon hit 2026-10-23 22:23:20 +02:00
d8dcecb573 fix(fenrir): form hits build adrenaline like a weapon hit
Vanilla grants a hit's adrenaline inside Attack. The forms skip Attack
and call Damage directly, so only the stagger bonus in Character.Damage
reached the player: meadow mobs, quick to stagger, filled the bar, while
Lox, Tar, Brutes and Furlings gave nothing until staggered.

FormMelee.GrantAdrenaline adds the player's unarmed attack adrenaline
times the target's multiplier after each claw or bite, and a fifth of
it per 0.2s tick of the Cultist's fire.
2026-10-23 22:17:17 +02:00
e5a9dc0046 Merge branch 'feat-fenrir-eye-glow': Fenrir eyes glow at night, bright when a form is ready 2026-10-23 22:08:57 +02:00
8b7e88e077 fix(fenrir): faint night glow at 0.675, as tuned in game 2026-10-23 22:08:05 +02:00
418d2462bd fix(fenrir): a softer ready glow
1.2 read too strong in game; 0.9 by default. The faint glow stays at 0.6.
2026-10-23 20:12:30 +02:00
c2bc73b3a0 feat(fenrir): eyes turn the Cultist's yellow when it is back from cooldown
The ready flag becomes an int: none, a form, or the Cultist. The Cultist
wins only while its rules give it a cooldown (Yagluth and Queen), since
that is the one return worth announcing. Its body shares the Fenring's
material and its breath is white flame tinted by texture, so the colour
comes from its death effect: FlameRoundYellowParticle's emission,
(2.691, 1.797, 0.455), bundle c4210710.
2026-10-23 20:06:49 +02:00
2becb81b6f fix(fenrir): the faint night glow is bright enough to see
At 0.35 the red channel stayed under 1, so bloom never picked it up and
a Fenrir with no form ready looked like it had no glow at all. 0.6 puts
it just over.
2026-10-23 19:58:35 +02:00
d1f328a496 feat(fenrir): eyes glow at night, bright when a form is ready
A community suggestion: an indicator on the character instead of the
"<form> is Ready!" text. FenrirVisuals borrows the Skeleton's eye_l and
eye_r the way AswidVisuals does, with the Aswid's playtested placement,
and tints them with the Fenring's own emission colour (2.0, 0.372, 0),
read from bundle c4210710.

Dark by day and in a beast form. At night they glow faintly, and
brightly while one of the three keys would transform. That uses the
same gates as TryTransformWithRules: tier, night, sun sickness,
cooldown. The owner writes it to the ZDO only on a change, so remote
players see the same.

New local section "Fenrir - Appearance": Ready Message (on by
default), Eye Glow, and the night and ready strengths.
2026-10-23 19:33:00 +02:00
f1f8ed245c Merge branch 'fix-stamina-bar-return': the stamina bar comes back after leaving the Aswid or the Draugh 2026-10-23 19:23:43 +02:00
1b1dae5f0b Merge branch 'fix-full-food-slots': race foods replace a worn-down meal when the stomach is full 2026-10-23 19:23:43 +02:00
f1597dd646 fix(hud): the stamina bar comes back after leaving the Aswid or the Draugh
Both races hide the stamina bar root from a Hud.UpdateStamina prefix.
Vanilla activates that root once, when the HUD is built, so after a
race change the bar stayed hidden until relog. The prefix now switches
it back on for every other race.
2026-10-23 19:22:31 +02:00
eba537fa07 fix(food): race foods replace a worn-down meal when the stomach is full
Trenta seeds, Draugh raw flesh and Aswid meals each go through an
EatFood prefix that, with three slots full and none holding the same
food, answered false. Vanilla would replace the most depleted meal past
half its time. The UseItem callers also never showed why: EatFood says
nothing on a refusal, so the click did nothing at all. That is the
Reddit report of a Trenta who could not eat any seeds.

The prefixes now hand that case to native EatFood, the Aswid's
CanConsumeItem postfix keeps vanilla's answer instead of forcing false,
and the Trenta and Draugh callers ask CanEat(item, true) for vanilla's
own message when a meal is refused.
2026-10-23 19:18:53 +02:00
cacc8ead4a Merge branch 'main' into localisation 2026-10-23 19:07:23 +02:00
557664c41f Merge branch 'fix-furling-remote-scale': other players see a Furling at Furling size 2026-10-23 19:07:14 +02:00
e125c6bc67 Merge branch 'fix-trol-legacy-weapon-reach': a resized player's weapon hits as far as it is drawn 2026-10-23 19:07:14 +02:00
95c8a7b1b6 fix(furling): other players see a Furling at Furling size
The 0.81 scale was applied from a Player.Update postfix that returned for
anyone but the local player and read the race from the local m_customData.
Scale is not replicated, so a Furling was small only on their own screen.
The postfix now sizes every player, with the race read off the ZDO the way
the Dvergar and the Trol already do it.
2026-10-23 19:03:58 +02:00
691ccc211b fix(visuals): a resized player's weapon hits as far as it is drawn
Attack.DoMeleeAttack and DoAreaAttack measure range and ray width from
the unscaled root, so a Legacy True Form Trol at 2.5 still hit at a
human's 2 m while the drawn mace reached five. Both now grow by the
Visual's world scale (never below 1), the factor HeldItemScaleFix sizes
the weapon by. Height stays at the feet so a flat swing does not pass
over small enemies. F8 toggles an in-game readout of the stretched
numbers and what a cast straight ahead passes through.
2026-10-20 03:17:08 +02:00
99f409c8be Merge remote-tracking branch 'origin/main' into localisation 2026-10-19 14:30:42 +02:00
9dd6600287 chore(release): v1.5.13 - no faction AI freeze, Dvergar build discount
With factions on, destroying a piece a mob was targeting froze every AI in
the area on servers. Dvergar pieces now build at the discounted metal cost
the menu shows, and refund what was paid.

README: New in block and changelog entry. Compendium: the Dvergar smithing
discount also covers building, in English, Italian and Russian.
2026-10-19 14:30:35 +02:00
b3bdb0f75a Merge remote-tracking branch 'origin/main' into localisation 2026-10-19 14:26:56 +02:00
64fbd66987 Merge branch 'fix-static-target-null': no AI freeze when a targeted piece is destroyed 2026-10-19 14:24:31 +02:00
faea08901c Merge branch 'fix-dvergr-build-discount': build pieces accept the Dvergar smithing discount 2026-10-19 14:20:40 +02:00
32c49a8af0 fix(dvergar): build pieces accept the smithing discount
The build menu showed the discounted metal cost, but Player.HaveRequirements(Piece)
read m_amount directly, so placing a piece still needed the full vanilla amount.
It now goes through GetAmount like the rest of the cost path.

Piece.DropResources also read m_amount, which would have refunded 10 tin for a
cauldron that cost 6. A piece placed by a Dvergar now stores the discount paid,
and dismantling it drops that amount.
2026-10-19 14:20:28 +02:00
6d9f07217e fix(factions): no AI freeze when a targeted piece is destroyed
FactionStaticTargetPatch read m_targetStatic as a boxed object, so the
null check missed Unity's destroyed-object state. A piece destroyed
while a mob targeted it passed the check, and reading its gameObject
threw. The throw escaped into MonoUpdaters.FixedUpdate and stopped
every AI after that mob, every frame, until the field changed.

Cast to Component and use Unity's null check; clear a dead target.
2026-10-18 13:33:21 +02:00
92c80e3b87 Merge branch 'main' into localisation 2026-10-18 00:19:25 +02:00
9d459fbc99 chore(release): v1.5.12 - hair back after a form with Valkyr
With the Valkyr body replacer, leaving any monster form brought the body back
without its hair. Fixed in PlayerVisualHider.

README: New in block and changelog entry.
2026-10-18 00:18:36 +02:00
b028a309d2 Merge branch 'fix-valkyr-hair': hair comes back after a form with Valkyr 2026-10-18 00:17:16 +02:00
5dff5e1b84 fix(forms): hair comes back after a form with Valkyr
Valkyr sets its hair's forceRenderingOff on every visual update. The hider
read that flag as "not hidden yet", recorded the hair a second time with
enabled already false, and the revert left it off. Track hidden renderers
in a set instead of trusting the flag.
2026-10-18 00:09:14 +02:00
589127b7df Merge branch 'main' into localisation 2026-10-17 20:30:37 +02:00
f1d00f6eff chore(release): v1.5.11 - True Form troll, race stations, Ravager attacks
Trol True Form wears the vanilla forest troll, with a per-player Legacy
switch for model mods. Race stations show and require their race and go on
floors and in caves. Fenrir forms sneak and stand still to attack; the Ulv
sleeps when the player sits. The Ravager attacks on the Brute's own clips.
Fixes: ResetRace, troll cave collapse, [msg_] texts, build-mode attacks,
War Vulture startup error.

README: New in block, changelog entry, Trol/Fenrir/Sverm feature lines and
the stations section.
2026-10-17 20:30:37 +02:00
174e615ed9 Merge branch 'main' into localisation 2026-10-17 20:28:54 +02:00
7e6d3d0936 Merge branch 'fix-ravager-attacks': Ravager attacks follow the Brute's clips, ram lunges, slam digs per claw; War Vulture startup error gone 2026-10-17 20:28:54 +02:00
63e252d9e9 feat(sverm): the Ravager's ram lunges with the clip's root motion
Vanilla only takes root motion during a native attack, which this form never
starts, so a relay on the costume's Animator collects it and a prefix on
Character.ApplyRootMotion applies it to the player the same way (x55).
2026-10-17 20:24:43 +02:00
d05cea7f08 fix(warvulture): strip dependents first, no more Can't remove Humanoid at startup
The startup error came from WarVultureVisual.BuildTemplate, not from the
Ravager costume: its passes tried Humanoid before CharacterDrop. Components
another one still requires now wait for a later pass.
2026-10-17 20:24:43 +02:00
61a74320c5 fix(sverm): Ravager attacks follow the Brute's clips; the slam hits once per claw
Hits land on the clip's own Hit events and the hold-still lasts until the
animator leaves the attack state, instead of fixed delays. The slam has two
Hit events, one per claw: each one hits and digs under the claw that came down.
2026-10-17 20:05:36 +02:00
1c2da77603 fix(sverm): the Ravager stands still to attack and its slam digs
The hidden player kept walking under the costume, so every swing slid
toward whatever WASD held. A SetControls prefix holds it still while an
attack runs, as Fenrir and the True Form troll do. The middle-click slam
now digs a crater on bare terrain (digg_v3), never inside a ward without
access, behind a new Ground Slam Crater option.
2026-10-17 19:51:33 +02:00
5cf1ae7fb0 fix(sverm): the Ravager costume no longer keeps a live Humanoid
The BepInEx log showed "Can't remove Humanoid (Script) because
CharacterDrop (Script) depends on it" right after the Ravager template
was built from SeekerBrute. The strip was one pass in component order,
and Unity refuses to destroy a component another still requires, so
the Brute's Humanoid survived on the costume and on every copy a
player wore: the leftover that once broke the hammer for every piece.

ModelBorrow.StripBehaviours destroys only what nothing remaining
requires through [RequireComponent], round after round, and logs any
survivor by name. Used by the Ravager template, by ModelBorrow.Attach
and by the Skeleton's rise costume, which had the same single pass.
2026-10-17 19:42:14 +02:00
20e08432b8 Merge branch 'main' into localisation 2026-10-17 19:39:13 +02:00
ee154ccab4 Merge branch 'fix-form-build-gate-chair' 2026-10-17 19:39:13 +02:00
ba7f56550d fix(forms): no form attacks in build mode; chair pose 1 m out, turned
RaceInput.AttackDown and AttackHeld now return false while the player
is in place mode (hammer, hoe, cultivator). Right click removes a piece
there and middle click picks a snap point, and every form read both as
its own attacks. Allowed only covered the piece selection panel. Every
form reads the mouse through RaceInput, so all of them are covered.

On a chair the form now settles 1 m in front of the seat and turns a
quarter counter-clockwise, at the player's request after the first try.
2026-10-17 19:34:51 +02:00
a28fb19845 Merge branch 'main' into localisation 2026-10-17 19:33:39 +02:00
9662ec6b38 Merge branch 'feat-form-sleep-sneak': Ulv sleeps when the player sits 2026-10-17 19:33:39 +02:00
5c0f092c89 fix(fenrir): a form on a chair settles in front of the seat
On a chair the player sits on the seat, and the form stood inside the
chair at seat height. The form's root now goes 0.5 m in front of the
seat, on whatever is under that point, skipping the seat's own
colliders. The seat is found by a short raycast under the player, so
it works for onlookers too, who have no attach point. Back to zero on
standing up; the sit key is untouched.
2026-10-17 19:28:42 +02:00
e83c3c5d74 fix(fenrir): enter the Ulv's sleep by its real state path
scripts/dump_controller.py reads an AnimatorController's states and
transitions offline from Valheim's bundles with UnityPy. On
ulv_animator it shows the entry state "check sleeping" picks Sleep only
at start-up and Movement has no way back into it, so the bool alone
could never work. The cross-fade now targets "Base Layer.Sleep".
2026-10-17 19:22:34 +02:00
fb354c2387 fix(fenrir): enter the Ulv's Sleep state by hand when the player sits
A vanilla Ulv is born asleep: its controller only knows the way out
of Sleep, so setting the bool from Idle did nothing. The state is now
cross-faded into when the player sits; standing drops the bool and the
controller's own 'Sleep to Idle' plays. The log names the state found.
2026-10-17 19:13:47 +02:00
9cf3f5386c fix(fenrir): the Ulv sleeps when the player sits
Sitting now zeroes the form's speed. The seated player's Animator keeps
a forward_speed above zero, which kept the Ulv in its Walk clip on the
spot and out of reach of its Sleep state, which leaves from idle. The
debug log showed it: sitting, sleeping=true, clip 'Walk'.
2026-10-17 19:09:50 +02:00
4cb6da801b Revert "debug: log the Ulv's sleep state while the player sits (temporary)"
This reverts commit 2df8264c42.
2026-10-17 19:09:38 +02:00
d28f9e353a Merge branch 'main' into localisation 2026-10-17 19:07:01 +02:00
727338c400 Merge branch 'main' into feat-form-sleep-sneak 2026-10-17 19:07:01 +02:00
1592282a46 Merge branch 'feat-form-sleep-sneak': sneak at a walk, stand still to attack 2026-10-17 19:07:00 +02:00
2df8264c42 debug: log the Ulv's sleep state while the player sits (temporary) 2026-10-17 19:06:08 +02:00
96dc8e4158 fix(fenrir): Ulv sleeps on the sit key; forms stand still to attack
Humanoid.IsSitting asks about the "sitting" animator tag, which belongs
to chairs. The sit key is an emote that Player.StartEmote writes on the
ZDO as "sit", so the Ulv never saw the player sit down. FormLocomotion
now reads the ZDO emote too, which every client sees. Of the four
forms only ulv_animator has a sleeping state.

The hidden player kept walking under the form through an attack, so a
bite slid toward whatever WASD held. Each form's isAttacking now also
sets FenrirForms.LocalAttacking, and a SetControls prefix holds the
player still while it is set, as the True Form troll does. The leaps
move the body directly and are untouched. Cleared on every revert.
2026-10-17 19:01:03 +02:00
580ef6d468 feat(fenrir): forms sneak at a walk and sleep when the player sits
FormLocomotion zeroed the speed whenever the player crouched, so a
sneaking form slid across the ground in its idle pose. Only airborne
reads as still now: crouched, the player moves at sneaking speed and
the creature's controller picks its walk.

Sitting sets the "sleeping" bool the creature's own MonsterAI uses,
when its controller has one; the log says once per controller which do.
IsSitting reads the replicated animator state, so onlookers' copies
sleep too. Covers every Fenrir form, local and remote, and the True
Form troll, which share FormLocomotion. Mirror now takes the Player.

Requested by a player on Discord.
2026-10-17 18:51:14 +02:00
d120ec8dc2 Merge branch 'main' into localisation 2026-10-17 17:15:54 +02:00
8843e773b1 Merge branch 'fix-race-requirement-first' 2026-10-17 17:15:54 +02:00
7647b66aa0 fix(stations): the race requirement comes first in the build panel
The race took the first free row after the materials and the crafting
station. Each of those rows now moves one to the right and the race
takes row 0: it decides whether the rest matters at all.
2026-10-17 16:39:56 +02:00
a2a4bcf451 Merge branch 'main' into localisation 2026-10-17 16:24:09 +02:00
ce21036373 Merge branch 'feat-race-station-requirement' 2026-10-17 16:24:09 +02:00
5b2e5f4f86 feat(stations): the race is a build requirement, shown in the panel
Every race station is listed in RaceStationLock with the race (or
races) that may build it. The build panel shows it in the requirement
row after the materials and the crafting station, with the race's icon
from the race menu and its translated name, blinking red when the
player is not of that race, the way vanilla flags a missing station.
Player.HaveRequirements answers false for CanBuild, so the piece is
greyed and a click gets vanilla's "Missing requirements". IsKnown and
CanAlmostBuild stay vanilla, so every station is still listed.

Seven stations had no race lock at all and are now locked too: Cursed
Body Pile, Pack Trough, Bone Pile, Bound Sentry, Blood Refinery,
Composter and Heartwood Grove. The stations' own placement gates stay
for their boss-tier checks and for no-cost debug building.
2026-10-17 16:24:09 +02:00
b6e085e378 Merge branch 'main' into localisation 2026-10-17 16:22:29 +02:00
cf5c9ef3ce Merge branch 'fix-totem-ghost' 2026-10-17 16:22:29 +02:00
0cc10b437e Revert "debug: F8 dumps the build ghost and the placement ray (temporary)"
This reverts commit edc7fd33b7.
2026-10-17 16:21:50 +02:00
e1bd3b66e1 fix(trol): War Totem ghost invisible everywhere
The totem borrowed its look from the GoblinTotem item, whose root holds
a ParticleSystem while the mesh sits in its attach child.
Player.SetupPlacementGhost switches off every GameObject with a
ParticleSystem, so it took the root and the mesh with it: the F8 dump
showed TotemModel/model/attach/model active=False on the ghost. The
Yagluth head (TrophyGoblinKing) is built the same way.

Both now borrow the item's attach child, which is the mesh itself.
ModelBorrow switches the copy on, since an item's attach is stored
inactive in its prefab.
2026-10-17 16:19:03 +02:00
edc7fd33b7 debug: F8 dumps the build ghost and the placement ray (temporary) 2026-10-17 16:11:16 +02:00
268ed47589 Merge branch 'main' into localisation 2026-10-17 15:59:09 +02:00
ea1efef56e Merge branch 'fix-placement-ghost' 2026-10-17 15:59:08 +02:00
916ba5bd6f fix(pieces): placement ghost vanished off terrain for most stations
Eleven pieces set m_groundPiece. Player.UpdatePlacementGhost switches
the ghost off outright and returns whenever the aim is not on a
Heightmap, which vanilla means for hoe and cultivator pieces. Floors,
rocks and a troll cave's mesh floor are not a Heightmap, so players
saw no ghost at all there, and with either flag Valheim never shows
the blue placement marker. Reported for the Trol War Totem.

m_groundPiece is off everywhere now. The stations (War Totem, Cursed
Body Pile, Dvergar Bank, Rune Barrel, Pack Trough, Skadi Golem, Bone
Servants) drop m_groundOnly too and go on floors, foundations and in
caves, like the Bone Pile since 1.5.8. The living pieces (Furling
bushes, Sverm nest and Hive Market, Trenta Elder Root) keep
m_groundOnly: terrain only, and the ghost shows red elsewhere.
2026-10-17 15:59:08 +02:00
03cca64a48 Merge branch 'main' into localisation 2026-10-17 15:51:54 +02:00
b8661b78f3 Merge branch 'fix-missing-msg-texts' 2026-10-17 15:51:54 +02:00
e86e1e3da5 Merge branch 'fix-faction-pieces' 2026-10-17 15:51:54 +02:00
87d0f2642c fix(texts): four messages showed as [msg_...]
Four tokens the mod printed exist in no vanilla table (checked on
Valheim 1.0.20) and were never registered by the mod, so players saw
the raw name in brackets.

- $msg_eatanother (Trol, a food still being digested): vanilla's
  $msg_nomore, "You can't eat more $1", called as Player.CanEat calls it.
- $msg_canteatanymore (Trol, every stomach full): vanilla's $msg_isfull.
- $msg_ate (Aswid, Vae Victis): vanilla's $msg_consumed.
- $msg_notenoughmoney (Dvergar bank, Trol totem): a new mod text,
  rov_msg_not_enough_coins, in English, Italian and Russian.
2026-10-17 15:51:53 +02:00
b566adbfb9 fix(factions): allied mobs spare a race's buildings with nobody home
FactionStaticTargetPatch only vetoed a mob's piece target while an
allied player stood within 100 m. Inside a troll cave that was the
collapse bug: the Trol walks out, the resident Troll (its prefab has
m_attackPlayerObjects) finds nobody to stop it, and the cooking station
built there is in pieces when the Trol comes back.

Every piece now carries the race of its builder on its ZDO, stamped in
Piece.SetCreator at placement, and in Piece.Awake for older pieces the
first time their builder loads them, so no timer and no scan. An
allied mob of that race can't pick the piece as a target and its blows
do it no damage, which also covers a swing at a foreign wall that
would have hit the Trol's workbench next to it. A mob holding a grudge
against the builder gets no such truce.
2026-10-17 15:50:41 +02:00
e38df0b7e0 Merge branch 'main' into localisation 2026-10-17 15:32:06 +02:00
d16524beec Merge branch 'feat-trol-true-form-model' 2026-10-17 15:32:06 +02:00
b2346c1437 feat(trol): Legacy True Form switch, chosen per player
The Troll Model option becomes Legacy True Form, off by default. On,
True Form is the old one: the player's own Trol grown bigger, weapons
in hand, body untouched, which player model mods such as VRM need.

It is a local preference, not a synced one, so a server cannot force
the troll costume on a VRM user. The owner publishes the choice on the
ZDO and every other client reads it from there, so onlookers see each
Trol the way that Trol's owner picked.
2026-10-17 15:32:06 +02:00
a9e66aeeb7 fix(trol): True Form log visible, slam reaches the ground, skin tint
The log in the troll's fist was there but switched off: an item's
attach child is stored inactive in its prefab and VisEquipment turns
it on after the Instantiate. It is now switched on, hung with the
item's equipoffset, and sized to the costume, since AttachItem keeps
an attach at its world size and the costume is not at scale 1.

The slam never ran its slam code. troll_groundslam is a Vertical
attack in vanilla, not Area, so asking the attack type sent every slam
down the punch's sweep: damage, but no AoE, no dust and no crater. The
slam now goes by the key that was pressed.

The tint multiplied _Color, which the creature shader does not read.
It now shifts _Hue, _Saturation and _Value, as LevelEffects does for
starred creatures, by the distance from the vanilla troll's colour to
the player's skin colour.
2026-10-14 17:17:20 +02:00
db29f868ea fix(trol): True Form troll size, log, reach, root during attacks, slam
The troll pulsed several times a second and stayed small because
PlayerVisualHider.Hide put the hidden Visual back to scale 1 every
frame while Trol_PlayerUpdate_Patch grew it back, and the troll follows
that scale. Hide and Show take keepScale now, and the Trol calls pass
it. The camera height, which reads the same scale, stops jumping too.

The log in the troll's hand is the troll's own log model, hung the way
VisEquipment does it, instead of the Trol's, which was built for a
person's hand and came out huge and sideways.

Punch and slam reach further and hit wider, with a new Troll Attack
Reach option (1.3). The player is held still through every attack
clip, throw included.

The ground slam spawns the troll's own troll_groundslam_aoe with the
player's damage, kept off friends, plus its trigger and terrain
effects. It carries chop and pickaxe at least equal to its blunt, so
it breaks trees and rocks, and with Ground Slam Crater on it digs into
the terrain where it lands, never inside a ward without access.
2026-10-14 17:08:20 +02:00
c64cb393c7 feat(trol): True Form wears Valheim's own troll
True Form now hides the Trol's body and puts the vanilla forest troll's
model in its place, on the owner's client and on every other player's.
The costume stands as tall as the old True Form did: it follows the
Visual scale Trol_PlayerUpdate_Patch already grows and publishes, so
the grow-in, the shrink back and the size others see come for free.
It takes the Trol skin colour from Trol - Appearance.

Weapons are out while it is up. Left click is the troll's punch, right
click its ground slam, and with a log in hand they become its two log
swings, which wear the log down per hit as a club swing did. Throw
Rock plays the troll's throw. The attacks, their triggers and reach are
read off the troll's own weapons at runtime, and each hit lands on the
troll's OnAttackTrigger event rather than a fixed delay.

Damage is a share of the troll's own (Troll Attack Damage, 0.5), scaled
by the Clubs skill like a club and hit as Clubs, so the True Form and
tier melee bonuses still add on top.

Other players see the troll from the existing True Form ZDO flag, with
attacks replayed from a new trigger key. New options in Trol - True
Form: Troll Model (on/off), Troll Model Size, Troll Attack Damage.
2026-10-14 16:56:34 +02:00
bf63b790f1 Merge branch 'main' into localisation 2026-10-14 16:41:52 +02:00
927bda1bbc Merge branch 'fix-resetrace-cleanup' 2026-10-14 16:41:52 +02:00
d5c2d58636 fix(resetrace): drop every form and every mod status effect on reset
ResetRace now undoes each race's form on the spot before it touches
status effects: Aswid bat and mist, Fenrir, Skadi drake, Trol True
Form, Trenta Muspell and Sverm Ravager. Each race gets a
HardResetForReset that stops the form's coroutine, so a transform
caught mid-gesture can't finish after the reset and a revert can't
hand out its cooldown after the sweep.

The hand-written status effect list is gone. The reset now removes
everything the mod registers through Jotunn (ModRegistry), which
covers the True Form and its cooldowns, Bat and Mist Form, the
Skeleton resurrect cooldown and Skadi's ability cooldowns.

It also puts the player and the Visual back to scale 1, clears the
Sverm's static Ravager cooldown and the Trol's wasTrueFormActive flag,
and prints what it removed to the console and the BepInEx log.
2026-10-14 16:40:27 +02:00
65b488b5dc feat(trol): skin and hair colour pickers in Trol - Appearance
Two Color entries, Skin Color and Hair Color (hair and beard), defaulting
to the old peacock blue and golden blonde so no Trol changes on update.
Each Trol publishes its choice on its own ZDO and every client paints
that player with it; a Trol on an older build publishes nothing and shows
the defaults. The menu preview, with no ZDO, reads the local config.
The section is kept local by ConfigSync.

README: New in block, Trol features line and a 1.5.10 changelog entry.
2026-10-14 14:14:06 +02:00
bb1ca57924 chore(release): v1.5.10 - Skeleton body switch for player model mods
New client-side option Skeleton - Visuals -> Body Model Enabled. Off,
a Skeleton takes the human branch of the VisEquipment postfix: vanilla
body on, no bone meshes, eye glow, jaw correction or skull flame, and
the helmet is left alone. Requested by players using EnhancedValheimVRM,
where the bones floated around the replacement model.

README: New in block for v1.5.10, changelog entry (also the Russian
fixes since 1.5.9), and a line under the Skeleton features.
2026-10-13 20:00:03 +02:00
358b537cef Merge branch 'main' into localisation 2026-10-08 18:22:13 +02:00
aca3eabb2f Merge branch 'localisation' 2026-10-08 18:22:13 +02:00
fb32a49576 Merge remote-tracking branch 'origin/localisation-russian' into localisation 2026-10-08 18:22:05 +02:00
f1fbebb8c7 Обновить JotunnModStub/Translations/Russian/items.json 2026-10-08 08:14:18 +02:00
d86609acef Обновить JotunnModStub/Translations/Russian/hover.json 2026-10-08 08:13:43 +02:00
a1261af0f1 Обновить JotunnModStub/Translations/Russian/compendium.json 2026-10-08 08:12:25 +02:00
a75655d3e5 Обновить JotunnModStub/Translations/Russian/messages.json 2026-10-08 08:05:10 +02:00
875024e649 Обновить JotunnModStub/Translations/Russian/messages.json 2026-10-08 07:58:42 +02:00
3c86d48aad Обновить JotunnModStub/Translations/Russian/merchants.json 2026-10-08 07:57:46 +02:00
9f11cab70d Обновить JotunnModStub/Translations/Russian/hover.json 2026-10-08 07:57:09 +02:00
c45ca80d99 Обновить JotunnModStub/Translations/Russian/compendium.json 2026-10-08 07:52:10 +02:00
8bad4092be Обновить JotunnModStub/Translations/Russian/races.json
по канону Valheim 
Драуг - Драугр
2026-10-08 07:45:13 +02:00
Ferdinando
0159f1e8c4 bugfix 07/10/26 + evil laugh 2026-10-07 17:31:29 +02:00
b63f810a8f Merge branch 'localisation' into localisation-russian 2026-10-07 04:11:26 +02:00
3815f2bf53 Merge remote-tracking branch 'origin/main' into localisation 2026-10-07 04:11:24 +02:00
eaa87f892a Merge branch 'fix-skeleton-revive-bonepile' 2026-10-07 04:11:08 +02:00
68cdbd6de6 chore(release): v1.5.8 - Skeleton rise, truce for bound troops
README: the New in block is v1.5.8 only, a changelog entry for the three
fixes, and the Skeleton stations line says the pile and the Sentry go on
floors too.
2026-10-07 04:11:08 +02:00
1848725f2a fix(skeleton): rise on resurrect, truce for bound troops, pile and sentry on floors
The Yagluth auto-resurrect now plays the crypt rise. The player rig has no
rise state, so the body is hidden and the skeleton model is worn for the
length of the clip with "wakeup" set; the start time goes on the ZDO so
other clients play it too. The player takes no damage and does not move
until it is out.

Wild faction mobs left the player alone but attacked the player's thralls,
which are tamed and so in the Players faction. IsEnemy now gives a thrall
the same truce through its m_commandingRace, broken by a grudge against
any player. Covers every race with thralls.

The Bound Bone Pile and the Bound Sentry seed drop m_groundPiece and
m_groundOnly, so both can be built on floors and foundations.
2026-10-07 04:11:08 +02:00
19e6a3ce50 Merge branch 'main' into localisation-russian 2026-10-06 14:20:25 +02:00
41020a0fab Merge branch 'main' into localisation 2026-10-06 14:20:23 +02:00
02c640e1d9 chore(release): v1.5.7 - Bone Ships and the Russian translation
README: the stack of "New in" blocks at the top is down to the latest
release, a languages line with flags sits under the intro, Bone Ships gets
its own section, and the Translations section credits Rudra and Axibed for
the Russian. nexus-readme.py keeps an image inside a line of text inline,
so the flags do not come out as 350 px pictures on Nexus.
2026-10-06 14:20:22 +02:00
8cad29f5a1 Merge branch 'localisation' into localisation-russian
# Conflicts:
#	JotunnModStub/Translations/Russian/compendium.json
#	JotunnModStub/Translations/Russian/hover.json
#	JotunnModStub/Translations/Russian/items.json
#	JotunnModStub/Translations/Russian/merchants.json
#	JotunnModStub/Translations/Russian/messages.json
#	JotunnModStub/Translations/Russian/races.json
#	JotunnModStub/Translations/Russian/status_effects.json
2026-10-06 14:00:02 +02:00
04053d64cc Merge branch 'main' into localisation 2026-10-06 13:59:54 +02:00
60e9b0ab72 localisation(ru): add Russian translation
Merged from two community translations (Rudra and Axibed). Axibed's set is
the base; Rudra's lines replace it where they read better or are more
faithful, mostly the merchant jokes. Boss, creature and resource names follow
vanilla Valheim's own Russian (Матерь, Прародитель, Драугр, Эйтр,
Быкоящер, Пеплозавр, Масса костей). Ability names that are quotes or song
titles stay in English, as in Italian. The bone-ship and thrall-order keys
that neither translation had are translated here.
2026-10-06 13:59:52 +02:00
e331708682 Merge branch 'localisation' into localisation-russian 2026-10-06 13:46:53 +02:00
9e943d5442 Merge remote-tracking branch 'origin/main' into localisation 2026-10-06 13:46:51 +02:00
2f744cf3b3 scripts: add sync-localisation.sh to carry main into the translation branches 2026-10-06 13:46:46 +02:00
f4652de7e5 Merge branch 'localisation' into localisation-russian 2026-10-06 13:46:01 +02:00
c5eef16dc2 docs: add translator guide 2026-10-06 13:46:00 +02:00
b9dc72fdd0 localisation(ru): add Russian skeleton from English 2026-10-06 13:36:31 +02:00
Ferdinando
553303d0fd bugfix 06/10/26 + bone ship 2026-10-06 11:36:18 +02:00
Ferdinando
7a863b07a6 bugfix 05/10/26 2026-10-05 11:39:38 +02:00
Ferdinando
9690d4d2a1 docs: drop the 'not tested in game yet' notes from the public changelog
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-04 07:34:11 +02:00
Ferdinando
5113225981 chore(release): v1.5.5 - Sverm Gjall bombs spare the player and the ticks they hatch are tame
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-04 07:31:16 +02:00
Ferdinando
9a3ab78666 chore(release): v1.5.4 - Sverm troops keep their own place around the player and the boat
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-03 08:11:05 +02:00
Ferdinando
a047ea45cf bugfix 01/10/26 + deepnorth food 2026-10-01 08:21:50 +02:00
Ferdinando
b9ac02fe50 chore(release): v1.5.3
Version bumped in manifest.json, the packaging manifest and PluginVersion.
Valheim 1.0's new creatures for the Aswid and the Draugh (seal, moose,
Elaking, Jotun, Barka, Deep North Goblin and every Dvergr), the Elaking
Hair Bundle in the blood refinery, and the Skeleton choosing its look at
the barber.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-01 08:19:47 +02:00
c5ff57530d Merge branch 'release-v1.5.2' 2026-09-30 22:43:45 +02:00
fa0e2cbb06 chore(release): v1.5.2
Version bumped in manifest.json, the packaging manifest and PluginVersion.
The one change is the Thunderstore package keeping the mod under plugins/,
so mod managers no longer take the Translations folders apart. The
changelog explains why 1.5.1's zip fix was not enough, and the README
leads with it.
2026-09-30 22:43:44 +02:00
2f7401099e Merge branch 'fix-thunderstore-plugins-folder' 2026-09-30 22:42:59 +02:00
d866f137fb fix(package): the Thunderstore package keeps the mod under plugins/
Mod managers (r2modman, the Thunderstore Mod Manager, Gale) copy what is
inside a top-level plugins/ folder into BepInEx/plugins/<Author-Mod>/
with its structure, and flatten folders they do not recognise. 1.5.1's
Translations/English/items.json landed as a loose items.json beside the
DLL, the Italian copy of each file overwrote the English one, and Jotunn
found no translations. Reproduced in a clean r2modman profile; with the
DLL and Translations under plugins/ the import keeps both language
folders and the texts show.
2026-09-30 22:42:59 +02:00
46df449c82 Merge branch 'fix-thunderstore-readme-anchors' 2026-09-30 19:52:12 +02:00
2ccb09e67a fix(package): the Thunderstore README has no in-page anchor links
Thunderstore renders the README on the mod page but does not resolve
anchors, so links like [changelog](#v151) went nowhere. The package now
gets a copy with those links turned into plain text, as nexus-readme.py
already does for Nexus. The repo README keeps them, since they work on
the wiki and the git host.
2026-09-30 19:03:06 +02:00
22237d647d Merge branch 'release-v1.5.1' 2026-09-30 16:04:17 +02:00
ecc238a728 chore(release): v1.5.1
Version bumped in manifest.json, the packaging manifest and PluginVersion.
The Unreleased changelog becomes v1.5.1 with the "TO BE TESTED" tags
removed, the translation entry now covers mod-manager installs and says
to reinstall if keys still show, and the lead section describes 1.5.1.
2026-09-30 16:04:17 +02:00
c5fb99fbbd docs(changelog): reach grows with height 2026-09-30 14:00:47 +02:00
782d49e0eb Merge branch 'fix-interact-range-scale' 2026-09-30 14:00:46 +02:00
d502eda748 fix(visuals): a taller player reaches as far as they are tall
Vanilla only takes a hover target within m_maxInteractDistance (5 m) of
the eye, and RaceEyeHeight raises the eye with the model. A True Form
Trol's eye stands about 4 m up, so a log at its feet was already out of
reach and Grab Log worked on one small spot under the camera. The range
now grows by the same ratio as the eye (10-12.5 m in True Form, the
Muspell by its own eye), and never drops below vanilla for smaller races.
2026-09-30 13:57:51 +02:00
be1c676c2f docs(changelog): Sverm dorsal spines off for now 2026-09-30 13:51:12 +02:00
74363e12ee Merge branch 'fix-sverm-spines-off' 2026-09-30 13:51:12 +02:00
0cd09bc862 fix(sverm): the dorsal spines are off by default until they are placed right
On a body wearing armour the crest came out through the chest and
shoulder pieces instead of standing off the back. A new "Enabled" entry
under Sverm - Dorsal Spines, false by default, removes it at once; the
placement settings are kept for when it comes back.
2026-09-30 13:49:44 +02:00
f0cbef64a9 docs(changelog): Sverm brood eggs, Blister Tick effect, Frost Troll log 2026-09-30 13:46:54 +02:00
057ecd2d47 Merge branch 'fix-frost-troll-and-blister-names' 2026-09-30 13:46:54 +02:00
ff4f79f452 fix(sverm): the nest lays brood eggs while its owner is around
Settle ran every second and restarted the egg clock at "now" each time.
One second is 1/20 of an egg, which integer division rounds to none, so
with the owner near the nest twenty seconds never went by and the clutch
stayed empty. Every troop and the Blister Tick cost an egg, so the whole
Hive Market shelf stayed grey. The clock now moves on only by the eggs
actually laid, and is held at now while the clutch is full.
2026-09-30 13:42:32 +02:00
6c23d4e206 fix(sverm): the Blister Tick's burst shows its effect (vfx_BombBlob_explode_poison) 2026-09-30 13:22:48 +02:00
3485665d4e fix(trol): the True Form log is borrowed from TrollFrost, the real Gammeltroll
"Gammeltroll" is only the developers' name: the prefab is TrollFrost,
whose clips fire the sfx_gameltroll_* sounds and whose Attack TreeThrow
throws a treebundle (dumpanim TrollFrost). No prefab is called
Gammeltroll, so since v1.4.16 every True Form throw fell back to the
physical log. The loose "gammel" substring fallback is gone too: it
matched nothing in vanilla and could match another mod's prefab.
2026-09-30 13:22:48 +02:00
8274baf74b docs(changelog): Trol log and food, Muspell camera tested 2026-09-30 13:12:19 +02:00
5c22c5d96f docs(changelog): Trol log and food, Trenta Muspell camera and idle 2026-09-30 13:11:28 +02:00
3a538bb942 Merge branch 'fix-trenta-muspell-camera' 2026-09-30 13:11:15 +02:00
0872bca116 Merge branch 'fix-trol-log-and-food' 2026-09-30 13:11:15 +02:00
1a461dc81b fix(trenta): restart the Muspell's idle with Play, found by weight
The first loop fix never fired. The idle shares a locomotion blend tree
with the Swagger Walk clips, so it is not always the first clip listed:
it is now found by name with most of the weight. And a cross-fade from
a state into itself can be ignored by Unity, so the state is restarted
with Play once it reaches its end.
2026-09-30 13:10:29 +02:00
b201c3a637 fix(trenta): the Muspell's idle loops instead of freezing
The Elder's "Unarmed Idle" clip is not a looping clip (loop=False,
1.90s), so after standing up or attacking the form played it once and
froze on the last frame. The state is now cross-faded into itself just
before its end while the form stands idle.
2026-09-30 13:03:58 +02:00
7d88bc78d0 fix(trenta): the camera rises to the Muspell's head
The form hides the player's body by shrinking its Visual to 0.001, and
RaceEyeHeight reads anything that small as hidden and leaves the eye
where it was, at a person's height. The Muspell now measures its head
height when the clone is made and hands RaceEyeHeight that height times
the form's current scale, so the camera follows the grow and shrink.
2026-09-30 12:55:15 +02:00
c4b119b406 fix(trol): no food in two slots at once, and Pukeberries empty slots 4 and 5
Vanilla only checks its own three slots, so a meal still digesting in
the 4th or 5th stomach was eaten again as new as soon as a vanilla slot
freed up. The extra stomachs are now asked first, in both CanConsumeItem
and EatFood. Pukeberries remove food through RemoveOneFood, which only
picked from the vanilla three; slots 4 and 5 now join the same draw.
2026-09-29 04:55:24 +02:00
2f64bcfc38 fix(trol): the grabbed log keeps its own size in True Form
Its 0.4 scale was set by eye on the size it had before held items
started following the model, so in True Form it came out two and a
half times too big. HeldItemScaleFix now leaves TrolWeapon_* alone.
2026-09-29 04:55:23 +02:00
5027d2d84f docs(changelog): Trol item size, Furling fire and zip path fixes; mark untested entries 2026-09-29 04:25:29 +02:00
7b425c69c2 Merge branch 'fix-package-zip-paths' 2026-09-29 04:25:04 +02:00
d0e3cbc46c Merge branch 'fix-fenrir-forms' 2026-09-29 04:25:04 +02:00
1c92eaef35 Merge branch 'fix-furling-fire-reset' 2026-09-29 04:23:14 +02:00
fb2a440afa Merge branch 'fix-trol-trueform-item-scale' 2026-09-29 04:23:14 +02:00
5af7c0205d fix(furling): Through Fire and Flames goes out when the player changes race
The ability is vanilla's Burning set to 999 minutes. FurlingRace.Update
returned before ticking it for anyone who was not a Furling, and
ResetRace never removed it, so the fire followed the player onto any
race and came back visible if they picked the Furling again. The tick
now runs for every race and puts out a Burning longer than an hour when
the player is not a tier 8 Furling; ResetRace does the same at once.
2026-09-29 02:50:47 +02:00
e8ca631dee fix(visuals): sheathed items follow the model's scale, not the back joint's
The back joints sit inside the armature, authored at 100x, so scaling a
sheathed item by its joint's world scale put a shield on a Trol's back
at 250 times its size. Items are now scaled by the Visual's world scale.
2026-09-29 02:48:58 +02:00
598d709af1 fix(visuals): weapons and shields drawn by a resized player match their size
VisEquipment.AttachItem parents the item with SetParent(joint), which
keeps its world size, so on a scaled model the item's local scale was
divided by the model's. A Trol drew items 23% too small at base size,
and after sheathing in True Form they came back at human size on a
2.5x body. The item is now scaled back by the joint's scale, as if
parented without keeping world size, and follows the model from there.
2026-09-29 02:33:54 +02:00
6b020fb80a fix(package): zip paths use / so the translation files survive extraction
Compress-Archive on Windows PowerShell 5.1 wrote the entries as
Translations\English\items.json. The zip format only allows /, so on
Linux and Steam Deck each text file came out as one flat file with
backslashes in its name, Jotunn found no Translations folder and every
mod text showed as [key]. The zips are now built by scripts/package.ps1.
2026-09-29 02:07:55 +02:00
b4b6fe3758 fix(fenrir): hidden human no longer attacks or blocks under a form
The attack block patched Character.StartAttack, which Humanoid overrides
without calling the base, so it never ran; and it covered the Fenring only.
Every form swing also fired the hidden human's attack: stamina spent,
regen held at zero while it played, and forward_speed dropped to 0. Patch
Humanoid.StartAttack for all four forms, and clear m_blocking after
SetControls so the pad's heavy attack stops raising the guard.

Forms treat the player as airborne only after 0.25 s off the ground, so
bumps no longer flicker run to idle. Melee reach ignores the target's own
colliders and accepts a clear line from the eyes or the attack point, with
an opt-in hit log. Sunrise names the key that still works by day.
2026-09-28 22:19:37 +02:00
19d331789a Merge branch 'fix-allied-raids' 2026-09-28 21:44:16 +02:00
df9c768f92 feat(factions): no raids made only of allies, and allies spare the whole base
A raid whose every spawn is at peace with the player's race is struck from
the list the client sends as possibleEvents, and from the server's valid
event points when raids are world-based.

The structure veto covered only 20 m from the creature, but
FindClosestStaticPriorityTarget searches the whole view range. It now holds
while any allied player is within 100 m, and reads the per-race lists too.
2026-09-28 21:41:29 +02:00
5807e562ad docs(readme): lead with the v1.5.0 localisation, and trim the changelog
The opening section now introduces the localisation and the release's most
visible fixes instead of the Sverm, whose own section further down is
unchanged. The changelog keeps v1.5.0 back to v1.4.20; older versions are
on the wiki's release notes, which the closing line points to.
2026-09-28 20:22:06 +02:00
a8d7c95e2b chore(release): v1.5.0
Version bumped in manifest.json, the packaging manifest and PluginVersion.
The changelog covers the localisation work, the Valheim 1.0 build menu
fix and the fixes since 1.4.24, and corrects the 1.4.24 note that claimed
Fenrir sounds had been writing into the world save. A Translations section
explains how to add a language, and the install step now names the folder.
2026-09-28 19:50:33 +02:00
27079af19f Merge branch 'feat/translations-merchants' 2026-09-28 19:39:17 +02:00
29bd557eb9 feat(text): Italian merchant jokes, from the adaptations Nando wrote
The 90 closing jokes in Italian, taken from Factions_Battute_Mercanti.txt,
where each pun was adapted rather than translated wherever the English
wordplay had no Italian equivalent. The file wrote accents as trailing
apostrophes; they are proper accented letters here.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-28 19:35:11 +02:00
6ec8fe327d feat(text): Italian compendium, and quotes and song titles kept in the original
The compendium's 204 texts in Italian. Ability names that are quotes or
song titles stay as written in every language, by the author's call:
Purple Rain, Weight of Shadows, Like a Bat out of Hell, Swarm of Terror,
Steal Their Breath and the like, including the Italian status effects and
messages that had been translated before.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-28 19:09:14 +02:00
5910c4f746 feat(text): the race compendium comes from translation files
Every paragraph of the compendium pages now reads from compendium.json.
Values computed from the config become $1, $2; the Sverm fire clause, which
had two wordings folded into one sentence, is two sentences. The pages'
titles are tokens that the game's Texts dialog localizes, and since those
titles are also the pages' keys in the saved m_knownTexts, the refresh
clears the old English keys too. Boss names use the game's tokens.

Song titles and quotes stay in the original, in every language.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-28 19:03:59 +02:00
1bd09ed31d feat(text): merchants, troops and the hive's shelf come from translation files
The faction merchants' 90 jokes, their generic lines and their names now
read from merchants.json. Merchant names use the game's own creature
tokens where one matches, so they arrive translated in every language
Valheim ships; the Dverg keeps a key of its own, since vanilla's token
reads "Dvergr Rogue".

The Dvergar and Trol troop names and terms, and the Sverm hive's goods,
refusals, stage names and brood kinds, follow. Their panels fill TMP texts
themselves, so they localize the names where they draw them.

The jokes have English text only for now.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-28 18:50:54 +02:00
594b333f68 Merge branch 'feat/translations-hover' 2026-09-28 15:13:59 +02:00
2c5079bf8c fix(build): the mod's stations appear under Crafting in Valheim 1.0's build menu
Valheim 1.0 lists pieces by Piece.m_usage tags. Jotunn sets only the old
category, so a cloned piece kept its source's tags: the Crystal Golem and
the Bound Sentry, cloned from guard_stone, landed under Decorations. A
postfix on PieceManager.AddPiece now sets the tag from the category for
every Hammer piece of this mod.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-28 15:06:22 +02:00
83bade65cb fix(trol): True Form no longer switches itself off as it comes on
The plugin adds TrolRace itself, but Instance did not know that and built
a second copy on first read, so two Updates read every key. Past Fader the
True Form key is a toggle: one copy put the form on, the other saw it on
in the same frame and took it off. The Trol grew and shrank back with no
status. Awake now registers the plugin's copy and removes any other.
FurlingRace had the same pattern, harmless there, and gets the same fix.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-28 15:06:21 +02:00
b555da99f2 feat(text): the Tame and Grab Log hover prompts come from translation files
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-28 13:55:45 +02:00
99a1817eb0 feat(text): hover texts come from translation files
What the stations, thralls, the ward and the hive show under the
crosshair now reads its text through ModText.Get, and hover.json holds
50 texts in English and Italian.

The Aswid thralls and the Race Menu Ward wrote the use key as a literal
E; they now use $KEY_Use, which shows the key the player actually bound.
For that to work, ModText.Get runs a second localization pass when a $
is left in the result: Valheim resolves tokens once and never looks
inside what it inserted, and hover texts go to the HUD without another
pass.

The Sverm hive stage names stay English for now: the compendium and the
hive's goods show them too, and those come with the merchants step.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-28 13:55:14 +02:00
19d7cbacbd Merge branch 'feat/translations-messages' 2026-09-28 13:50:08 +02:00
0a0d9410e7 fix(skadi): Middle Mouse in Drake form no longer spends the attack cooldown on nothing
PerformAttackCoroutine starts the cooldown and shows its icon before it
looks at the form, and the Drake has no Middle Mouse attack, so the press
cost a cooldown and fired nothing. HasAttackForButton now answers for the
Drake too and guards all three buttons, as it already did Left Mouse.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-27 00:52:01 +02:00
b0d18b0654 feat(text): on-screen messages come from translation files
Every message the mod puts in the middle or corner of the screen now reads
its text through ModText.Get, and messages.json holds 191 texts in English
and Italian. Values computed in code become $1, $2 in the text, so a
translator can put them wherever the sentence needs them. Branching
messages get one key per branch.

A few messages travel through a field before they are shown: thralls'
refusals and the building limits now hold a token or key there. Boss and
form names inside messages use tokens too, the bosses the game's own, so
"The Elder" arrives translated.

ModText.Get now localizes each argument before inserting it. A token
argument left for a later pass ran into the text after it: "$1's power"
became the unknown token "enemy_eikthyr's".

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-26 20:30:03 +02:00
b3641e5bf4 Merge branch 'feat/translations-status-items' 2026-09-26 20:24:28 +02:00
b177c89c71 feat(text): item, piece and creature names come from translation files
The mod's own items, build pieces and summoned creatures now carry
$rov_item_, $rov_piece_ and $rov_creature_ tokens for their names and
descriptions, and items.json holds the texts in English and Italian.
Valheim localizes these fields wherever it shows them: tooltips, hover
texts, messages, the build menu.

Where a name doubles as an identifier, both sides use the same constant,
so the comparisons still hold. The Aswid foods keep their prefix as a
constant for the refinery's check and now name the creature with its
vanilla token, so "Boar" translates too. The Furling crops get one whole
description per crop instead of an English sentence with the metal dropped
in. The Race Menu Ward's panel title is a mod UI Text, so it reads the
translation directly.

Saves are unaffected: items and eaten foods are stored by prefab name.
The Sverm hive's goods stay for the merchant step.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-26 19:58:53 +02:00
9bf144aedc feat(text): status effect names and tooltips come from translation files
Every status effect the mod registers now carries a $rov_se_ token instead
of English, and status_effects.json holds the texts in English and Italian.
Valheim localizes both fields itself when it shows them. The blood
potion's tooltip has numbers in it, so SE_BloodPotion fills its $1 and $2
in GetTooltipString, at display time.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-26 19:51:10 +02:00
c055455027 Merge branch 'feat/translations-races' 2026-09-26 19:48:29 +02:00
73b67cd6ce feat(text): the race menu reads its texts from translation files
First step of moving every piece of text out of the code so modders can
translate the mod. The texts live in Translations/<Language>/*.json, one
file per kind of text, which Jotunn finds on its own and falls back to
English for. ModText reads them; values take Valheim's $1, $2 placeholders.

This step covers the race selection menu: title, buttons, every race's
name and description, in English and Italian. The race ID and the name on
screen are now separate strings. The ID is what the save and the ZDO hold,
so it must never be translated.

The files are deployed to plugins\RacesOfValheim\Translations and packed
into both release zips.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-26 19:43:48 +02:00
a835a58003 Merge branch 'fix/cold-spell-tier-text' 2026-09-26 19:30:57 +02:00
19c9347772 fix(skadi): the Cold Spell key's description says tier 2+, where it unlocks
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-26 19:30:56 +02:00
731125901e Merge branch 'feat/eclipse-dusk' 2026-09-26 19:27:22 +02:00
52c26d9b52 feat(aswid): the Eclipse's dusk spends its time on the sunset
An even sweep from the afternoon to midnight looked still for three
seconds and then fell dark in half of one, because the sky hardly changes
between 0.25 and 0.75 and does its darkening around sunset. The dusk now
walks keyframes: half a second to late afternoon, three through the
sunset band, half a second to midnight.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-26 19:24:23 +02:00
055635d1b4 feat(aswid): Eclipse runs the sky through dusk instead of cutting to night
While EnvMan's debug time is on it copies the value straight onto the sky,
so setting midnight in one go made night fall in a single frame. The clock
now eases forward from the current hour to midnight over 3.5 seconds. The
dawn already eased back on its own, because EnvMan smooths towards the real
time once the switch is off.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-26 19:16:08 +02:00
0403b6a9df Merge branch 'fix/aswid-eclipse' 2026-09-26 19:14:14 +02:00
2d718a09ec Merge branch 'main' into fix/aswid-eclipse 2026-09-26 19:04:09 +02:00
bb6af1c877 Merge branch 'fix/fenrir-sounds-spawn-like-vanilla' 2026-09-26 19:04:07 +02:00
0674329592 fix(fenrir): spawn sounds the way vanilla spawns effects, without ghost init
Ghost init was meant to keep a sound's ZNetView from writing a ZDO. It
does not: ZNetView.Awake still creates the ZDO and only skips registering
the instance, so ZNetScene sees an unbuilt ZDO and builds a second copy.
Vanilla's EffectList.Create uses a plain Instantiate, and TimedDestruction
deletes the ZDO through ZNetScene.Destroy when the sound ends. The spawn
now does the same.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-26 18:50:51 +02:00
8f477dd3be fix(aswid): Eclipse brings the night instead of dying on its first line
The coroutine set EnvMan's two debug-time fields the wrong way round and
asked for 0.5, which is noon. Handing a bool to the float field threw, so
the cast stopped right after the announcement and IsEclipseActive stayed
true, and every later press returned without a word. The fields are now
set directly, to midnight, and a finally frees the ability if anything in
there throws again.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-26 18:29:34 +02:00
e4694f6cd9 Merge branch 'fix/ulv-footsteps' 2026-09-26 18:23:46 +02:00
5bdd7200a5 fix(fenrir): the Ulv no longer asks the player for feet called LeftHand
The form's CharacterAnimEvent finds its FootStep on the nearest Character
up the hierarchy, which for a form parented under the player is the player.
The Ulv's Run clip names its front paws LeftHand and RightHand, a human rig
has neither, and vanilla logged "FAiled to find foot" twice per stride.

The form's receivers are now cut from the player's FootStep, on the local
form and on the copy other players see. The footsteps stay: the hidden
human animator keeps running and FootStep steps off its curve.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-26 18:17:37 +02:00
58874457e0 Merge branch 'fix/radial-swallows-attack-input' 2026-09-26 18:12:36 +02:00
97d02855e5 feat(skadi): say why a Cold Spell press did not cast, and log each step of the cast
Every gate on the spell was silent, so "it does nothing" looked the same as
"it was never pressed". Each refusal now logs its reason once per session,
and the cast logs each step before taking it, because the crash it chases
kills the process without a stack trace. The prefab descriptions run after
the Instantiate, so reading them can't be what makes the spawn safe.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-26 18:12:34 +02:00
e973e21003 chore(input): quieten the radial proof to one line per state
The transition log did its job - it showed Hud.InRadial() reporting False at
spawn with no wheel on screen, which is what the gate depends on and what the
method's name alone could not promise. Left in, because that proof is worth
one line in every player's log, but said once per state instead of twice per
use of the wheel.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-26 17:30:35 +02:00
2b900d91e7 fix(input): the radial menu no longer swings the form it is opening a menu on
Clicking an entry in the race wheel also fired the transformed form's attack.
The click picks the entry AND is read here as a raw mouse button, because the
forms read the device directly rather than going through Humanoid.StartAttack.
Vanilla attacks never had this: they go through ZInput, which the radial
already blocks, so only input read straight off the device got through - which
is all of ours.

Hud.InRadial() answers it, the same shape of call as the
Hud.IsPieceSelectionVisible() already here for the hammer's build panel. That
is now the second GUI Player.TakeInput knows nothing about.

CHECKED IN AttackDown AND NOT IN Allowed, deliberately. The radial fires an
ability by queueing its keybind through Press(), and the ability's own reader
picks that up inside an Allowed gate - so blocking Allowed while the wheel is
open would risk the wheel swallowing the abilities it exists to trigger.

The second half is the same bug one layer down: an ability bound to a mouse
BUTTON does not go through AttackDown at all. Skadi's cold spell sits on middle
mouse, so middle-clicking an entry in the wheel cast it. IsDownIgnoringHeldKeys
now takes the queued press first and without any gate - that one is the radial
itself - and ignores a raw mouse button while the wheel is up. Keys at the
keyboard are untouched: nothing about an open wheel makes pressing K ambiguous.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-26 17:15:21 +02:00
7ad1d6920e fix(fenrir): the Ulv was mouthing a silent howl
The howl code took a playing animation as proof the sound was coming, because
the wolf's does bring it: 'C_Hawl' fires an Effect event at 0.39s holding
sfx_wolf_haul. The Ulv is the same family on the same rig and its 'Idle Howl'
carries no event at all - events=0, read straight off dumpanim - so pressing
the key as an Ulv played the animation and nothing else. The muzzle went up in
silence.

Which creatures bring their own sound is now written down rather than assumed,
and it is only the wolf. FenrirCreatureSound.Howl does the whole thing -
animation, trigger published for the other clients, and a sound unless the
animation is already carrying one - so the four forms call one line and the
distinction lives in one place.

The Ulv's hold also went from 3.3s to 3.8s: it was the wolf's clip length,
copied, and 'Idle Howl' runs 3.67s.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-26 16:55:19 +02:00
cd10722594 docs: say that the Cultist's fire breath runs on eitr
The feature list said "Transform into a Cultist to use fire abilities" and
never mentioned a cost. The flames take 12.5 eitr per second, and eitr comes
from the Mistlands while the form unlocks at Yagluth - so the form can be had
with its signature attack still out of reach. Both the feature bullet and the
changelog say so now.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-26 16:27:42 +02:00
6b43d3544e feat(fenrir): say why the fire breath did not come, and log a Draugh's parry
Holding right mouse as a Cultist with no eitr did nothing whatsoever - no
flames, no sound, no reason given. The form arrives at Yagluth and eitr is a
Mistlands thing, so a Cultist meets that silence before it ever meets the
fire. It now says "Only breath comes out. The fire wants eitr." on a
three-second timer, since the button is read every frame and the message would
otherwise be a wall.

The parry that fires the Draugh's poison splash is logged, with the block
timer against the window and whether the splash effect resolved. A parry has
to land inside a quarter-second window while blocking, so "nothing looks
different after tier 3" is as likely to mean the window was missed as it is to
mean the splash did not draw, and there was no way to tell those apart.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-26 14:00:21 +02:00
1c8fa7357f chore(release): sync the packaging manifest to 1.4.24
JotunnModStub/Package/manifest.json is a second copy of the root manifest,
kept by hand and differing from it only in the version - a third place for the
version to drift, on top of the two MAINTAINING.md already warns about. It was
still on 1.4.23.

Synced rather than fixed: the packaging step should copy the root manifest
instead of there being two, which is a change to make when the artifacts are
built rather than in a version bump.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-26 01:50:21 +02:00
421bc72eb7 chore(release): v1.4.24
Version bumped in both places that carry it - manifest.json is what
Thunderstore ships, PluginVersion is what the game logs - since those two have
drifted apart before.

The Nexus description is generated now rather than rewritten by hand. It had
fallen thirteen versions behind the README, which is how a hand-maintained
copy of a 72KB document goes. scripts/nexus-readme.py converts README.md to
the BBCode the page wants, following what the 1.4.11 page did by hand so the
two are comparable, and writes dist/NEXUS_README_<version>.bbcode.txt.

The wiki link was on the Nexus page and had never been in the README, so every
other channel shipped without it. It is in the README now, which means it
reaches Nexus, Thunderstore and the repository from one place.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-26 01:45:08 +02:00
148ca5b39e Merge branch 'fix/skeleton-fire-aura-prefab-hijack'
Six commits: the Skeleton fire aura no longer borrows another mod's VFX by
name, every prefab lookup name in the mod now exists in vanilla, the Draugh's
Human Meat is a real item, the Fenrir forms have their own voices and howl on
demand, and dumpanim reads an animator instead of guessing at it.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-26 01:42:04 +02:00
da896179fd feat(fenrir): howl on demand, in every form
The howl key was only ever read by the two Fenring forms. As a wolf or an Ulv
it did nothing at all - not a misconfiguration, the classes simply never
looked at it. All four forms read it now.

The wolf and the Ulv perform the creature's own howl animation and NO SOUND
IS SPAWNED, because their clip already carries one: 'C_Hawl' fires an
animation event at 0.39s holding sfx_wolf_haul, and the game's own
AnimationEffect plays it. The audio comes out of the animation, at the
instant the animation means it to, which no prefab fired on a keypress can
match. Spawning one as well would be a second howl over the first.

A trigger is looked for before a state, and that is about multiplayer rather
than tidiness: FenrirAttackSync replicates trigger names, so a howl fired
through a trigger is one the other clients see and hear, while Animator.Play
is local and nobody else knows. Which route was taken is logged once per
creature, and if neither exists the log prints the animator's whole parameter
list rather than leaving another keypress that quietly does nothing.

The Fenring and the Cultist have no howl clip in vanilla - 19 and 18 clips,
none of them a howl, and their taunt fires no sound event - so they keep the
Taunt animation and take the wolf's howl as their voice.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-26 01:41:00 +02:00
22170087ae feat(debug): dumpanim, for reading an animator instead of guessing at it
Guessing at animation has cost this mod real time: a howl looked for under
three wrong names, a taunt animation nobody knew played, and a sound prefab
that kills the process when spawned on its own.

dumpanim <prefab> lists a creature's parameters, layers, every clip in its
controller with name and length, and every AnimationEvent on every clip - the
instant, the method called, and the asset an event hands over. That last
column is where a sound wired into an animation lives, and it is what finally
found the wolf's howl.

It also prints the components beside the Animator, because an animation event
is delivered to those and nowhere else. On a prefab with no animator at all
it falls back to dumping the hierarchy, the components and the audio setup,
which is how a sound prefab gets looked at without being spawned - and some
of them must not be spawned.

dumpanim live watches every animator under the player and reports each clip
change as it happens. Standing still in wolf form and reading the log is what
showed 'C_Hawl' coming round in the idle rotation on its own.

What Unity will not give up, and it is worth knowing before starting: the
state machine. States and transitions are editor-only and
GetCurrentAnimatorStateInfo returns hashes with no names, so a state can only
be guessed and then confirmed.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-26 00:20:42 +02:00
9907cae292 fix(fenrir): give the forms a voice, and stop the sounds writing to the save
Every sound the Fenrir forms played was looked up by a name, and most of
those names are not prefabs in this game. The chains hid it: PlaySFX walks
its arguments and stops at the first that resolves, so a claw that asked for
"sfx_fenring_attack", "sfx_fenring_attack_claw", "sfx_wolf_attack" had a
Fenring swinging with a wolf's voice through a fallback nobody noticed. The
cultist's double claw asked for three dead names in a row and was silent from
the day it was written.

The creatures do have their own sounds. The forms now use them:
sfx_fenring_claw_start for the swing, sfx_fenring_claw_hit for the landing,
sfx_fenring_fireclaw to open the fire breath. The Ulv keeps the wolf's, since
vanilla ships it nothing but sfx_ulv_death.

THE HOWL WAS NEVER A PREFAB TO LOOK UP. It is an AnimationEvent inside the
wolf's 'C_Hawl' clip, firing at 0.39s with the sound handed over as an object
reference - and a player in wolf form idles through that clip and howls out
loud already, with the game's own AnimationEffect doing the work. Three
spellings of one word are why this took so long to find: the clip is
'C_Hawl', the sound is 'sfx_wolf_haul', and the mod was looking for
'sfx_wolf_howl', the only correct spelling of the three and the only one that
does not exist. The Fenring has no howl of its own at all, so it borrows the
wolf's over its Taunt.

The jump attack's impact moved to where the jump lands, next to the damage,
instead of firing before the dash while the form is still standing.

FenrirCreatureSound.Spawn is the other half. Some vanilla sound prefabs carry
a ZNetView - sfx_fenring_alerted does - and one that wakes with no init ZDO
writes a persistent record into the world, once per swing. Spawning now runs
inside ZNetView.StartGhostInit, the game's own answer, so no ZDO is made. All
nine sound spawns in these forms go through it.

sfx_fenring_howl resolves to an ordinary sound prefab and hard-exits the
process when spawned on its own. It is named in a Suspect set, described in
the log and never instantiated, because a name nobody records is a name
somebody adds back.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-26 00:20:31 +02:00
276ff93834 feat(draugh): add the Human Meat item the Bonemass perk has always promised
Two places in the mod used an item called "HumanMeat" and nothing registered
it: the drop in Draugh_DeathAura_Patch and the "fatal to the living" block in
DraughFoodPatches. Both check for null, so the perk has been a no-op since
it was written - a README line with no item behind it. The two consumers are
unchanged; what was missing was the producer.

Built from two vanilla items, one for the look and one for the numbers.
RawMeat gives the model and icon, because that is what a piece of somebody
looks like and because raw flesh is the Draugh's whole food identity.
BloodPudding gives the nourishment, copied field by field at start-up rather
than written down here, so the item stays balanced against the game's own
progression and follows any change made to it.

Blood Pudding's stamina goes onto health and stamina is left at zero. A
Draugh does not use stamina, so nourishment spent there is thrown away: the
food slot would read full while giving the race half of what it cost.

RawMeat is a Material in vanilla - raw meat is not edible - so m_itemType is
forced to Consumable. That is the one assumption worth knowing about, and
the registration logs what it produced so a silent failure cannot hide. The
meat is tinted on copies of the materials, never the shared ones, or every
piece of raw meat in the world would darken with it.

The README said humanoids drop it. The patch is on Player.OnDeath and always
was, so the line now says what the code does: a player who dies inside the
death aura, the Draugh included.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-26 00:20:16 +02:00
e75c7072c4 fix(prefabs): replace every lookup name that does not exist in vanilla
An audit of all 59 prefab names the mod resolves, against the game's own
asset manifests, found nine that are not in Valheim at all. A name vanilla
does not use has no vanilla candidate to beat in Jotunn's name cache, so it
is a free slot for whoever ships one - which is how another mod's weapon
trail became the Skeleton's fire aura in 00d4fd6.

Eight of the nine failed in silence, which is why none of them was ever
reported:

  vfx_corpse_destruction  ->  _medium, _large for the Muspell. The puff that
      covers a transformation. Fenrir and Skadi at least had their sparks;
      the Muspell swapped bodies in plain view with nothing at all.
  vfx_surtling_death      ->  vfx_wraith_death for the Aswid's Mist Form,
      which reads as mist by construction and is the same creature the form
      already borrows its Visual from; vfx_corpse_destruction_medium for the
      thrall, where nothing is misty. Vanilla has no surtling death effect
      under any spelling.
  TrophyTroll             ->  TrophyForestTroll.
  TrophyBat               ->  TrophyDeathsquito. Vanilla ships no bat trophy,
      so the Aswid's two status effects and its radial entry had no icon.
  vfx_smoke               ->  gone. It was the Trenta's fallback for Purple
      Rain's particle material behind Greydwarf_Shaman, and the day the
      Shaman failed to resolve it would have worn whatever a mod supplies.
      Purple Rain is purple by design, so nobody would ever have reported it.

The ninth did not fail in silence. vfx_OozeHit was passed to Instantiate
unguarded, so every successful Draugh parry threw ArgumentException and took
the North Wind nova below it down as well. It is vfx_blob_hit.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-26 00:20:02 +02:00
00d4fd6e46 fix(skeleton): stop the fire aura borrowing another mod's VFX by name
The tier-5 fire aura looked for "vfx_smoke", then "vfx_surtling_death".
Neither name exists in Valheim, checked against the game's own asset
manifests, so both lookups came back null and the aura has never been
visible in a plain install.

The dead branch was not harmless. PrefabManager.Cache resolves by asset
name across everything in memory, other mods' asset bundles included, and
its tie-break for a duplicate name ends in "newest wins". A name vanilla
does not use has no vanilla candidate to beat, so it is a free slot.

Magic_Supremacy fills it. The lookup resolved to
'EncounterCreatureRikoMountain_DO/vfx_smoke', a child node of one of its
creatures carrying 'club_trail_riko_DO' on 'Dreanegade/ParticleAlphaEmission'
- a weapon trail, on an emissive shader, sprayed through a 4.5m sphere on
the player. That is the purple smoke around the burning skull users
reported, on every client that could see the skeleton.

The aura now draws nothing on purpose, which costs it nothing it had. Its
damage, radius and tick are untouched. The two identical EnsureFireAuraVFX
copies in SkeletonRace and ZdoVisualSync are replaced by one
SkeletonVisuals.EnsureFireAura, shaped like DraughVisuals.EnsureAura; the
call sites stay, so reinstating the visual needs no change in either file.
The comment on it records the whole chain and the way to build it properly,
through BorrowEffect, the way HeadFlame already does.

Also keeps a resolution log on the model lookup: every magic mod in the
report ships an object called "Skeleton", which is this race's own tier-0
model name. The vanilla creature won during the repro; root=False in that
log is what says it stopped winning.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-25 15:54:21 +02:00
Ferdinando
f64fe83d9d bugfix 25/09/26 2026-09-25 12:26:51 +02:00
Ferdinando
9bebcf340b bugfix 24/09/26 2026-09-24 10:30:39 +02:00
Ferdinando
e7325e4d25 chore(release): v1.4.21 - dragon form multiplayer sync, Sverm Ravager networking, dorsal spine fix
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-23 11:56:09 +02:00
Ferdinando
6499eb71df chore(release): v1.4.20 - refused buildings cost nothing, Skadi pad cold spell
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-21 17:38:53 +02:00
Ferdinando
64d8869f98 bugfix 21/09/26 2026-09-21 09:05:56 +02:00
Ferdinando
834d6647fd chore(release): v1.4.19 - eye height, remote forms, food refresh, faction retaliation
Race body scale moved the model and not the camera: Character.m_eye hangs
off the unscaled root, so a Trol or a Dvergar changed height for everyone
but themselves. RaceEyeHeight moves the eye by whatever scale the Visual
is wearing, for every player, so aim rays follow too.

Remote copies of a Fenrir form had no one writing to their Animator and
stood in the controller's default state, sliding. RemoteFenrirAnimator
mirrors the four local behaviours off the player's own replicated
animator, the way RemoteSkadiAnimator already did for Skadi.

Player.Food.m_time is time remaining, not time elapsed: the Aswid, Trenta
and Draugh repeat-meal branches all set it to 0 and expired the slot they
meant to renew, and left the nutrition values stale. RaceFoodRefresh does
what vanilla's own branch does, in one place instead of three. The Trenta
prefix now reports __result, or a working refresh would have renewed the
slot without consuming the seed.

Aswid devour was gated by one timestamp shared by every corpse, so a pack
killed at once fed the player once; it is now per corpse, floored at a
second, and a refused meal says $msg_nomore.

MonsterAI.UpdateTarget discards any target IsEnemy refuses, so a truced
mob could not retaliate at all - it stood still or fled. RaceGrudge
records the hit on the AI owner's client and both truce postfixes stand
down for that pair. The Aswid drain and the Skadi frost aura now skip
kin, as the Skeleton's fire aura already did, or an always-on aura would
hold every truce permanently broken.

Faction sets matched exact prefab names with families half-listed:
added Skeleton_NoArcher and Draugr_Ranged to the Swamp, Greyling to the
Black Forest.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-20 08:26:22 +02:00
Ferdinando
5f74c57e72 fix: race buildings keep their own message when an item is used on them
Humanoid.UseItem shows the generic $msg_cantuseon whenever the
interactable's UseItem returns false, covering the refusal message the
building had just shown. Same fix as the Trol totem in v1.4.18, applied
to the Servant table, Dvergar barrel and bank, Fenrir trough, Draugr and
Skeleton piles, Blood Refinery, Grove and Composter: an item in hand
always counts as handled. Empty-handed interactions are unchanged.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-18 17:13:16 +02:00
Ferdinando
c7cbd6bece chore(release): v1.4.18 - Valheim hotfix flight fix, 1.0 shop fixes, Fenrir speed
Drake flight resolves ZInput.GetJoyLeftStickY at runtime, since the
hotfix dropped its bool parameter. Faction merchant TradeItems now set
the 1.0 fields StoreGui dereferences (m_tooltip, m_buyPlayerEffects),
and the Dvergar trader discount clones the whole TradeItem instead of
rebuilding four fields. Trol totem refusals return true so vanilla's
$msg_cantuseon no longer covers them. The Fenrir curse speed modifier
is the bonus alone (SE_Stats adds it), not 1 + bonus. New Discord link.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-18 17:10:24 +02:00
Ferdinando
8aa917cfcb chore(release): v1.4.16 - Trol True Form toggle past Fader, Gammeltroll thrown log
Past Fader the Trol's True Form never expires (SE ttl 0) and the key
toggles it off with no cooldown. The True Form log throw now fires one
projectile read off the Gammeltroll's own weapons at runtime, hitting
with the rock's damage formula, and falls back to the old physical log
if none is found; 'dumpgammel' logs what was resolved.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-13 11:33:47 +02:00
Ferdinando
6e87be3c77 minor bugfix and pad support 2026-09-12 10:42:01 +02:00
Ferdinando
ce671e7124 jotunn 2.30 compatibility + minor bugs 2026-09-10 19:14:05 +02:00
Ferdinando
6193b3ee2d 1.0 compatibility 2026-09-10 18:05:24 +02:00
5104f86ede chore(release): v1.4.11 - Bone Servant, input-lockout and Sverm beehive-cap fixes
Bumps the version and rolls the tester-fixes merge into the changelog:
the Bone Servant cook losing meat and the furnace starving on fuel, an
input gate that let abilities fire with the build menu open, and the
Sverm beehive cap that was configured but never actually read.
2026-08-30 19:07:17 +02:00
45b63dc7c6 Merge remote-tracking branch 'origin/tester-fixes' 2026-08-30 19:03:11 +02:00
6968480749 chore(release): v1.4.10 - Skeleton Summon on Kill fully fixed
Bumps the version and rolls the changelog entry documenting the whole
Summon on Kill fix chain from this session into README.md. Also trims
the changelog to start at v1.4.0 - everything older now points at the
wiki's release notes instead of being duplicated here.
2026-08-29 16:24:45 +02:00
8c24ae3340 fix(skeleton): Summon on Kill was completely dead - fix the whole chain
Queen/Fader-tier Skeletons were supposed to raise a tamed ally from every
kill, but nothing ever spawned. Several independent bugs stacked up:

- Kill attribution failed whenever the death blow was a poison DOT tick
  (SE_Poison builds its own attacker-less HitData every second, and
  Character.ApplyDamage overwrites m_lastHit on every one of those ticks).
  Since PoisonAttacks bakes bonus poison onto every Skeleton hit from
  Bonemass on, this was the common case, not an edge case. Character_Damage_Patch
  now tracks recent player hits per ZDOID as a fallback (RecentSkeletonHits),
  the same pattern Aswid's own life-drain-kill check already uses.
- SummonPrefabName pointed at "Skeleton_friendly", which isn't a real
  prefab (confirmed against the live ZNetScene registry). Reuses the
  Bound Bone Pile's own SkeletonThrall_Melee instead - tamed, loot-stripped,
  forced-melee, and already proven to work.
- The rise VFX names ("vfx_skeleton_spawn", "vfx_bloodmagic_aoe") were
  guesses that never existed either; fx_summon_skeleton_spawn is the real
  one. Same fix applied to the pre-existing Auto-Resurrect effect, which
  had the identical wrong names.
- The actual "climbing out of the ground" motion is a separate Animator
  bool ("wakeup") set via ZSyncAnimation - the exact call vanilla's own
  CreatureSpawner makes. Without it the model was simply active from
  frame one, VFX playing around a skeleton that was already standing.
- Vanilla skeletons carry no Tameable component, which spammed "is tamed
  but missing tameable or monster AI script!" every time a raised one
  landed a hit. Same fix Fenrir already uses for the Ulv and Fenring:
  copy one in from the vanilla Wolf, done once at prefab registration so
  it also quietly fixes the Bound Bone Pile's own thralls.
- Added RaisedThrall.SetExpiry(), a station-independent hard lifespan -
  these skeletons are never bound to a pile, so the existing anchor/wither
  pair had nothing to key off. Summoned skeletons now wither 2 minutes
  after being raised.

Also adds a permanent `listprefabs <substring>` debug console command -
queries the live ZNetScene registry directly, which is how the wrong
prefab/VFX names above were actually confirmed rather than guessed.
2026-08-29 16:01:23 +02:00
Ferdinando
819abb1a27 tester-fixes 2026-08-29 11:47:49 +02:00
Ferdinando
7ac7f99287 feat(sverm): enforce the beehive cap, and put the aura and the nest limits in config
"Beehives per Aura" was bound into the config and then read by nobody.
SvermConfigManagement.Beehives had no callers and neither did the
constant behind it, so the entry described a limit that did not exist and
a player could raise thirty hives in one aura and get thirty workers.

SweepAura is two passes now, with the cap between them. The first applies
to hives already taken and counts them - that maintenance is not
skippable, it is what survives a zone reload - and only then are new
candidates considered. One pass would have let the order the physics
query happens to return decide whether a hive counted against the cap or
was measured by it. The minute keeps running on a hive that does not fit
today, so when a taken hive is destroyed the one that has waited longest
is claimed on the next sweep instead of starting over; lowering the cap
never hands a hive back.

Three limits are now the player's: Aura Radius, Nests per Radius and Nest
Spacing Radius. PieceDensityLimit.Register takes a snapshot of its
numbers, so the Hive Market and the Brood Mound both watch their entries
and re-register when one moves - Register replaces an entry rather than
stacking a second limit on the same piece.

All three are clamped, and the reason is not tidiness: Register REFUSES a
radius of zero or a maximum below one, and a refused limit is no limit at
all. A player typing 0 into "Nests per Radius" to mean "no nests" would
have been handed unlimited nests.

Every player-facing string that stated the old numbers now reads the live
ones - the two build refusals, the orphaned market's message and hover,
and the two Compendium lines. The nest's hover shows the cap next to the
count, so moving the knob has visible effect.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-29 08:45:28 +02:00
Ferdinando
fcb6cae3ee fix(input): abilities no longer fire while the hammer's build menu is open
Skadi's cold spell is bound to middle mouse and kept casting with the
piece selection panel open. The gate was already there - HandleColdSpell
sits behind RaceInput.Allowed - but the gate itself was incomplete:
Player.TakeInput tests Chat, Console, TextInput, StoreGui, InventoryGui,
Menu, TextViewer, the map, free-fly and the barber, and nothing else
(read off the IL). Vanilla does not need the build menu in that list
because build input is handled separately in UpdatePlacement; a mod
ability reading UnityEngine.Input directly does.

Hud.IsPieceSelectionVisible is static, public and null-safe on its own
instance, so it costs one call and no reflection. Checked before
TakeInput so it holds on the fail-open path too.

Fixed in RaceInput rather than in Skadi: that class is the mod's single
input gate, so this covers every race and every bound ability - the
transformations, the flight toggle and the three dragon-form attacks
included.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-29 08:45:17 +02:00
Ferdinando
03c1006511 fix(butler): the cook's lost meat, the furnace that starved, the coal with nowhere to go
Three tester reports against the Bone Servant, all with the same shape:
the servant was doing what the code said and the code said the wrong
thing. Two vanilla methods were re-read off the IL rather than trusted.

RPC_RemoveDoneItem empties ONE slot per call - it finds the first Done
slot, spawns its item, clears it and returns - not every slot, as the
comment on PullOutput claimed. DoCollect also swept the ground BEFORE
pulling, so each visit collected the previous visit's item and dropped a
fresh one; since Plan() diverts to PlanDelivery the moment the payload is
non-empty, the servant then left for the chest and abandoned what it had
just pulled. A working hearth therefore always had exactly one cooked
meat lying beside it. Now it pulls first, in a loop bounded by a new
ButlerStation.OutputPulls - the slot count for a cooking station, 1
everywhere else, because the fermenter's Ready survives its own tap for
the length of the animation and a bare while(HasOutput) would spam
RPC_Tap.

PlanFuel sat last, behind PlanLoad, and FreeSlots goes back above zero
the instant a furnace eats one ore - so loading always had an answer and
refuelling never got a turn. The blast furnace burned down to nothing.
PlanFuel now runs ahead of PlanLoad, which cannot starve loading in
return because FuelWanted is 0 for a station with no work, and it scores
candidates by the walk the way PlanLoad does now that the choice matters.

PlanDelivery offers the load to the nearest station that will CONSUME it,
as material or as fuel, after the chest search fails and before dropping
it on the floor. UpdateSmelter only calls SpawnProcessed once the ore
queue empties, so the charcoal kiln releases its whole batch at once -
exactly the delivery a nearly full chest cannot absorb. The coal now
walks into the furnace beside it instead of onto the ground.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-29 08:45:09 +02:00
e042579e17 Fix Bone Servant crash when dropping a payload it can't place
DropPayload() cloned template.m_itemData straight off the ObjectDB
prefab and handed the clone to ItemDrop.DropItem, which instantiates
item.m_dropPrefab - a field a clone off a raw prefab never carries
(same pitfall already fixed in AswidBloodPotions.MakeFood). The result
was an unhandled ArgumentException instantiating null.

This fires whenever a servant is holding something with nowhere sealed
to put it - e.g. chests without the sigil item yet, as in the bug
report - and since the exception aborts before m_payload.Clear() runs,
the same broken load is retried, and crashes, on every AI tick after:
relogging or killing the servant doesn't clear it, because the payload
lives in the ZDO, not the character.

Fix: set clone.m_dropPrefab = prefab before dropping, same as the
existing fix.
2026-08-25 22:48:30 +02:00
Ferdinando
c99a386e4f docs(readme): correct three claims that no longer matched the code
- The Sverm intro still promised flight after Yagluth; the Stinger Morph was
  replaced by the Ravager Strain, which is a Seeker Brute and does not fly.
- Trol progression put the 4th food slot behind Bonemass. TrolFoodPatches
  gates only the 5th (state >= 6); the 4th has never had a gate.
- Trol melee bonus listed +10 at Yagluth and left axes out at both tiers.
  TrolConfig has BonemassMeleeBonus 10 and YagluthMeleeBonus 5, and
  TrolDamagePatches sends axes to m_slash, so axes do get it.

Same three corrections the compendium already got; the README had been
missed.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-25 19:37:33 +02:00
Ferdinando
cca594015a docs(changelog): shorten the serpent meat line to match the published one
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-25 19:36:33 +02:00
Ferdinando
163ad205e7 chore(release): v1.4.9 - Factions on/off switches, serpent meat price, Draugh cooking fix
Version bumped in the three places that carry it: manifest.json (the one the
packaging target reads), Package/manifest.json and PluginVersion.

README: changelog entry for the release, and the Factions section now
documents both switches - including the part worth knowing before flipping
one, that the truce switch covers every race's own peace and not just the
faction rules.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-25 19:27:14 +02:00
Ferdinando
a60f5e8217 fix(factions): make the truce switch cover every player truce, not one of five
Reported from a live game: with "Faction truce" off, a Trenta's Greydwarves
stayed friendly. The switch was working - it just was not switched over the
patch that mattered.

Five separate Harmony postfixes answer BaseAI.IsEnemy, and only
FactionHostilityPatch was gated. A Trenta reads its Black Forest truce from
RaceHostilityManager, which had no switch, so turning the faction one off
changed nothing visible. The same held for the Fenrir's wolves, the Aswid's
progression list, the Draugh's undead, the Sverm's invertebrates, the
Furling's Plains roster and the Skeleton's undead.

Gated all four player-facing ones behind the existing flag rather than
adding a switch each: from the player's side there is one question being
asked, and a switch that answers a fifth of it is worse than none.

DvergarMercenaryTrucePatch is deliberately left alone - it is a truce
between a hired thrall and a wild dvergr, two NPCs, and has nothing to do
with whether mobs come after the player.

Key stays "Faction truce" though its scope grew: renaming it would orphan
the entry in every .cfg already written, and the file beats the default in
code, so anyone who had switched it off would silently get the truce back.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-25 19:13:16 +02:00
Ferdinando
34bdf35325 Merge branch 'war-vulture' into main
Sverm Ravager Strain (replacing the Stinger Morph), Trenta Elder Root, the
Trol food and Black Forest truce work, and the faction FindEnemy patch.

Conflicts resolved:

- FactionHostilityPatch.cs: both sides added a class at the same spot and
  they cover different holes, so both are kept - FactionStaticTargetPatch
  (main, stops same-faction mobs smashing structures) and
  FactionHuntPlayerPatch (war-vulture, closes the HuntPlayer fall-through).

- RaceCompendium.cs: both branches independently fixed the same off-by-one
  in the Trol's progression gates. Took main's wording, which matches the
  code - Axes are in the melee bonus (TrolDamagePatches sends them to
  m_slash), the 4th food slot has no gate at all, and Yagluth is +5 not +10
  (TrolConfig.YagluthMeleeBonus). Kept war-vulture's two new lines, the
  Kindling fire weakness and the Black Forest truce.

- Package/manifest.json: 1.4.8, which is what the root manifest and
  PluginVersion already said.

RacesOfValheim.cs referenced SvermConfig.StingerSE/StingerCdSE, which
war-vulture renamed to Ravager. Git merged those lines without a conflict
and the result did not compile; renamed.

Also in this commit:

- Factions on/off switches (FactionsConfig): "Faction truce" and "Faction
  merchants", both default on, both read live so they take effect without a
  restart. The truce gates its three postfixes; the merchants gate the
  Character.Awake setup plus every behavioural patch, so turning them off
  drops the prompt and the trade window on mobs already awake.

- SerpentMeat sells for 200 instead of 1 at the Fuling bench, moved to keep
  the list's ascending price order (the sell panel renders it as declared).

- DraughFoodPatches mapped "SerpentMeatRaw", which is not a prefab; the
  internal id is SerpentMeat, so serpent meat never cooked for a Draugh.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-25 18:52:10 +02:00
Ferdinando
ee5a2e2e7b warvulture 2026-08-24 19:17:47 +02:00
3352e84438 Merge branch 'limit-cave-build-debug-log' into main 2026-08-24 14:10:24 +02:00
Ferdinando
4b95e705e7 warvulture 2026-08-21 11:22:52 +02:00
Ferdinando
e9d6e78ec8 warvulture 2026-08-19 19:18:24 +02:00
280 changed files with 34343 additions and 3667 deletions

27
.claude/launch.json Normal file
View file

@ -0,0 +1,27 @@
{
"version": "0.0.1",
"configurations": [
{
"name": "nandor-museum",
"runtimeExecutable": "npm",
"runtimeArgs": [
"--prefix",
"C:/Users/FERDINANDO/Desktop/JotunnModStub-master/NandorMuseum",
"run",
"dev"
],
"port": 5190
},
{
"name": "nandor-museum-build",
"runtimeExecutable": "npm",
"runtimeArgs": [
"--prefix",
"C:/Users/FERDINANDO/Desktop/JotunnModStub-master/NandorMuseum",
"run",
"preview"
],
"port": 5191
}
]
}

1
.gitattributes vendored Normal file
View file

@ -0,0 +1 @@
*.sh text eol=lf

2
.gitignore vendored
View file

@ -28,3 +28,5 @@ Thumbs.db
# How to setup Configuration Manager # How to setup Configuration Manager
CONFIGURATION-MANAGER-HOWTO.md CONFIGURATION-MANAGER-HOWTO.md
# Written by scripts/publish.* on a Release build from the root README; never edit or commit it.
/JotunnModStub/Package/README.md

View file

@ -0,0 +1,179 @@
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// SAMEINING, the archon (Alfar_Progettazione.txt sec. 13.8): Fader's power, an all-or-nothing form.
///
/// - needs 75% of the maximum eitr and a READY Heimkall, and spends ALL the eitr;
/// - lasts up to three minutes: bigger (x1.5), glowing, +20% speed;
/// - instead of armour there is a POOL of points, three per eitr spent: every blow lands on it,
/// and when it is gone the form ends early;
/// - no weapons: a psionic pulse strikes everything hostile around the body, once a second;
/// - Ljosstorm and Geisli cost nothing in the form, but wait a few seconds between uses;
/// - it ENDS (time up, pool gone) with a teleport home at one hit point, eitr at zero, and the
/// Heimkall wait starting. The form IS a Heimkall spent on purpose.
///
/// The form is published in the ZDO so other players see the size and the glow.
/// </summary>
public static class AlfarArchon
{
public const string ZdoKey = "Alfar_Archon";
public static bool Active { get; private set; }
public static float Pool { get; private set; }
public static float EndsAt { get; private set; }
public static float StartedAt { get; private set; }
private static float nextPulse;
/// <summary>True for any player in range: the form is read off the ZDO, not local state.</summary>
public static bool IsArchon(Player player)
{
if (player == null) return false;
ZNetView nview = player.GetComponent<ZNetView>();
return nview != null && nview.IsValid() && nview.GetZDO().GetInt(ZdoKey, 0) == 1;
}
public static bool IsLocalActive => Active && Player.m_localPlayer != null;
private static void Publish(Player player, bool on)
{
ZNetView nview = player.GetComponent<ZNetView>();
if (nview != null && nview.IsValid()) nview.GetZDO().Set(ZdoKey, on ? 1 : 0);
}
// ─── Entering ────────────────────────────────────────────────────────
public static bool TryActivate(Player player)
{
if (Active || player == null) return false;
float max = player.GetMaxEitr();
float eitr = player.GetEitr();
if (max <= 0f || eitr < max * AlfarPowerConfig.ArchonThreshold.Value)
{
player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_alfar_archon_not_charged"));
return false;
}
if (!AlfarHeimkall.IsReady(player))
{
player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_alfar_archon_not_ready"));
return false;
}
// Everything goes in: the strength of the form is what the Alfr had eaten.
Pool = eitr * AlfarPowerConfig.ArchonPoolPerEitr.Value;
AlfarEitr.Spend(player, eitr);
Active = true;
StartedAt = Time.time;
EndsAt = Time.time + AlfarPowerConfig.ArchonSeconds.Value;
AlfarStatusEffects.ShowTimer("archon", AlfarPowerConfig.ArchonSeconds.Value);
nextPulse = Time.time + AlfarPowerConfig.ArchonPulseInterval.Value;
Publish(player, true);
Jotunn.Logger.LogInfo($"[Alfar] Sameining on: pool {Pool:0} for {AlfarPowerConfig.ArchonSeconds.Value:0}s.");
player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_alfar_archon_on"));
return true;
}
// ─── In the form ─────────────────────────────────────────────────────
/// <summary>
/// Takes a blow into the pool. Called from the shield prefix before anything else, because in
/// the form the pool IS the defence: every type of damage, drowning and the edge of the world
/// included, since nothing else can end the form but the pool and the clock.
/// </summary>
public static void Absorb(Player player, HitData hit)
{
if (!Active || hit == null) return;
float total = hit.m_damage.GetTotalDamage();
hit.m_damage = default(HitData.DamageTypes);
if (total <= 0f) return;
Pool -= total;
// The exit itself is done in Tick, outside the damage call.
}
public static void Tick(Player player)
{
if (!Active) return;
if (player == null || player.IsDead())
{
// The body is gone (or the world is): nothing to teleport, only the state to drop.
Active = false;
if (player != null) Publish(player, false);
return;
}
if (Pool <= 0f || Time.time >= EndsAt)
{
Exit(player, Pool <= 0f ? "pool gone" : "time up");
return;
}
if (Time.time >= nextPulse)
{
nextPulse = Time.time + AlfarPowerConfig.ArchonPulseInterval.Value;
// 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);
}
}
// ─── Leaving ─────────────────────────────────────────────────────────
public static void Exit(Player player, string reason)
{
if (!Active) return;
Active = false;
Pool = 0f;
Publish(player, false);
AlfarStatusEffects.ClearTimer("archon");
// Eitr to zero, then the Heimkall: the form spends the one that was ready.
AlfarEitr.Spend(player, player.GetEitr());
AlfarHeimkall.TryTrigger(player, "Sameining " + reason, force: true);
player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_alfar_archon_off"));
Jotunn.Logger.LogInfo($"[Alfar] Sameining off ({reason}).");
}
/// <summary>The cooldown Ljosstorm and Geisli wait in the form, instead of costing eitr.</summary>
public static float FreePowerCooldown => AlfarPowerConfig.ArchonFreePowerCooldown.Value;
/// <summary>
/// NO WEAPONS in the form: the psionic pulse is the attack. Humanoid.StartAttack is the one
/// door every swing, shot and draw goes through (verified, doc sec. 16B); returning false
/// with a false result is "nothing started".
/// </summary>
[HarmonyLib.HarmonyPatch(typeof(Humanoid), "StartAttack")]
public static class Alfar_Archon_NoWeapons_Patch
{
public static bool Prefix(Humanoid __instance, ref bool __result)
{
if (Active && __instance == Player.m_localPlayer)
{
__result = false;
return false;
}
return true;
}
}
/// <summary>Clears the state without teleporting (used by the reset command).</summary>
public static void ForceClear(Player player)
{
Active = false;
Pool = 0f;
if (player != null) Publish(player, false);
AlfarStatusEffects.ClearTimer("archon");
}
}
}

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

@ -0,0 +1,148 @@
using System.Collections.Generic;
using Jotunn.Configs;
using Jotunn.Entities;
using Jotunn.Managers;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// The EIRINNSIGLI, the verdigris seal (Alfar_Progettazione.txt sec. 9.2c): a bronze nail turned at
/// the forge. Put inside a chest it tells the drones NOT to look there - the inverse of the
/// Butler's, where the seal says "this one is yours". Only the colour differs from the nail: a model
/// recolour does not touch the inventory icon (guide 5.2), so in the pack it looks like a bronze
/// nail and only the name tells it apart.
/// </summary>
public static class AlfarSigil
{
public const string PrefabName = "AlfarSigil";
public const string DisplayName = "$rov_item_alfar_sigil_name";
public static void Register()
{
GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(PrefabName, "BronzeNails");
if (prefab == null)
{
Jotunn.Logger.LogWarning("[Alfar] Could not clone BronzeNails: no verdigris seal.");
return;
}
ItemDrop drop = prefab.GetComponent<ItemDrop>();
if (drop == null || drop.m_itemData == null || drop.m_itemData.m_shared == null) return;
ItemDrop.ItemData.SharedData shared = drop.m_itemData.m_shared;
shared.m_name = DisplayName;
shared.m_description = "$rov_item_alfar_sigil_desc";
AlfarConstructs.Tint(prefab, new Color(0.36f, 0.68f, 0.58f, 1f));
ItemManager.Instance.AddItem(new CustomItem(prefab, fixReference: false));
ItemManager.Instance.AddRecipe(new CustomRecipe(new RecipeConfig
{
Item = PrefabName,
Amount = 1,
CraftingStation = CraftingStations.Forge,
MinStationLevel = 1,
Requirements = new[] { new RequirementConfig("BronzeNails", 1, 0, true) },
}));
}
}
/// <summary>
/// The two special chests (sec. 9.2c): built like an ordinary chest with Greydwarf eyes added to
/// the price. The ENTRY chest is where everything is thrown and where the drones sort from; the
/// WOOD chest holds the wood the drones may burn - the only wood they ever consume.
/// </summary>
public static class AlfarChests
{
public const string EntryName = "AlfarInngangskista";
public const string WoodName = "AlfarEldividarkista";
public static void Register()
{
RegisterOne(EntryName, "$rov_piece_alfar_inngangskista_name", "$rov_piece_alfar_inngangskista_desc",
"$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",
"$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, string hoverName, Color tint,
System.Func<GameObject, bool> build, string iconResource)
{
GameObject source = PrefabManager.Cache.GetPrefab<GameObject>("piece_chest_wood");
if (source == null)
{
Jotunn.Logger.LogWarning("[Alfar] No 'piece_chest_wood': the chest " + pieceName + " is not registered.");
return;
}
GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(pieceName, source);
if (prefab == null) return;
// The price of a plain chest, read from the game (guide 3.2), plus the eyes.
var requirements = new List<RequirementConfig>();
Piece vanilla = source.GetComponent<Piece>();
if (vanilla != null && vanilla.m_resources != null)
{
foreach (Piece.Requirement r in vanilla.m_resources)
{
if (r.m_resItem == null) continue;
requirements.Add(new RequirementConfig(r.m_resItem.gameObject.name, r.m_amount, 0, true));
}
}
requirements.Add(new RequirementConfig("GreydwarfEye", AlfarNexusConfig.ChestEyes.Value, 0, true));
// The hover and the chest window say what the chest is for, not only its name.
Container container = prefab.GetComponent<Container>();
if (container != null) container.m_name = hoverName;
Piece piece = prefab.GetComponent<Piece>();
if (piece == null) { Jotunn.Logger.LogWarning("[Alfar] The chest has no Piece: " + pieceName); return; }
piece.m_name = display;
piece.m_description = description;
// 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
{
Name = display,
Description = description,
PieceTable = PieceTables.Hammer,
Category = PieceCategories.Crafting,
Icon = icon,
Requirements = requirements.ToArray(),
}));
// One of each inside the reach of a Ljoskjarne, and only for the Alfar, and only where a core stands.
PieceDensityLimit.Register(pieceName, AlfarNexusConfig.NexusRadius.Value, 1, "rov_msg_build_limit_alfar_chest");
PieceDensityLimit.RegisterGate(pieceName, (player, position) =>
{
if (!AlfarRace.IsLocalAlfar())
{
if (player != null) player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_alfar_only_alfar"));
return false;
}
if (AlfarNexusBehaviour.Covering(position) == null)
{
if (player != null) player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_alfar_chest_needs_nexus"));
return false;
}
return true;
});
AlfarPieces.Extra.Add(pieceName);
}
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

@ -0,0 +1,110 @@
using Jotunn.Entities;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// Test helpers for the Alfar, in the F5 console. They exist so the phases of Alfar_Test.txt can
/// be walked through without waiting twenty minutes between steps.
///
/// alfarstatus what the race is doing right now (eitr, Heimkall timer, SE, form...)
/// alfarreset clears every Alfar timer and cooldown
/// alfareitr <n|full|0> sets the eitr pool: a number, "full", or 0
/// alfarhp <n> sets the current health, to try the lethal-blow case without dying
/// </summary>
public class AlfarStatusCommand : ConsoleCommand
{
public override string Name => "alfarstatus";
public override string Help => "[DEBUG] Prints the Alfar's eitr, health, Heimkall timer and passive.";
public override void Run(string[] args)
{
Player player = Player.m_localPlayer;
if (player == null) { Console.instance.Print("No local player."); return; }
string race = AlfarVisuals.GetPlayerRace(player);
Print($"race={race} progression state={BossProgressionManager.GetCurrentProgressionState()}");
Print($"health={player.GetHealth():0}/{player.GetMaxHealth():0} eitr={player.GetEitr():0.0}/{player.GetMaxEitr():0}");
float left = AlfarHeimkall.Remaining(player);
Print($"Heimkall: {(left <= 0f ? "READY" : (left / 60f).ToString("0.0") + " min left")} " +
$"(cooldown now {AlfarHeimkall.CooldownSeconds() / 60f:0} min)");
bool se = player.GetSEMan().HaveStatusEffect(SE_AlfarStats.EffectName.GetStableHashCode());
Print($"passive status effect: {(se ? "on" : "OFF")}");
}
private static void Print(string text)
{
Console.instance.Print("[Alfar] " + text);
Jotunn.Logger.LogInfo("[Alfar] " + text);
}
}
public class AlfarResetCommand : ConsoleCommand
{
public override string Name => "alfarreset";
public override string Help => "[DEBUG] Clears the Alfar's Heimkall timer and every power cooldown.";
public override void Run(string[] args)
{
Player player = Player.m_localPlayer;
if (player == null) return;
AlfarHeimkall.ResetTimer(player);
AlfarHeimkall.InvulnerableUntil = 0f;
AlfarPowers.ResetCooldowns(player);
Console.instance.Print("[Alfar] Heimkall timer and power cooldowns cleared.");
}
}
public class AlfarEitrCommand : ConsoleCommand
{
public override string Name => "alfareitr";
public override string Help => "[DEBUG] alfareitr <number|full|0> - sets the Alfr's current eitr.";
public override void Run(string[] args)
{
Player player = Player.m_localPlayer;
if (player == null || args.Length == 0) { Console.instance.Print("alfareitr <number|full|0>"); return; }
float target;
if (args[0].ToLower() == "full") target = player.GetMaxEitr();
else if (!float.TryParse(args[0], System.Globalization.NumberStyles.Float,
System.Globalization.CultureInfo.InvariantCulture, out target))
{
Console.instance.Print("alfareitr <number|full|0>");
return;
}
target = Mathf.Clamp(target, 0f, player.GetMaxEitr());
float delta = target - player.GetEitr();
if (delta > 0f) player.AddEitr(delta);
else if (delta < 0f) AlfarEitr.Spend(player, -delta);
Console.instance.Print($"[Alfar] eitr = {player.GetEitr():0.0}/{player.GetMaxEitr():0}");
}
}
public class AlfarHpCommand : ConsoleCommand
{
public override string Name => "alfarhp";
public override string Help => "[DEBUG] alfarhp <number> - sets the current health, to test the lethal-blow case.";
public override void Run(string[] args)
{
Player player = Player.m_localPlayer;
if (player == null || args.Length == 0) { Console.instance.Print("alfarhp <number>"); return; }
if (!float.TryParse(args[0], System.Globalization.NumberStyles.Float,
System.Globalization.CultureInfo.InvariantCulture, out float hp))
{
Console.instance.Print("alfarhp <number>");
return;
}
player.SetHealth(Mathf.Clamp(hp, 1f, player.GetMaxHealth()));
Console.instance.Print($"[Alfar] health = {player.GetHealth():0}/{player.GetMaxHealth():0}");
}
}
}

View file

@ -0,0 +1,168 @@
using BepInEx.Configuration;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// Every number the Alfar use. Nothing numeric lives in the logic files (guide 3.4), and every
/// value here is a STARTING value: Alfar_Progettazione.txt sec. 19 says they will all be
/// corrected in play.
///
/// Only the look is bound so far. The shield, the powers and the base add their own sections as
/// they are written.
/// </summary>
public static class AlfarConfig
{
/// <summary>
/// Written into m_customData["Race"] and the ZDO. Chosen once and never changed: renaming it
/// later leaves every saved Alfar character unrecognised and back to human (the Brandr
/// lesson, design doc sec. 2).
/// </summary>
public const string RaceId = "Alfar";
// ─── Look ────────────────────────────────────────────────────────────
/// <summary>The tint written into _SkinColor. Ash grey: low saturation, a hair cool.</summary>
public static ConfigEntry<Color> SkinColor;
/// <summary>
/// Height against a normal Viking: +5%, design doc sec. 7.1. Applied to the Visual child's Y,
/// never the root (RaceEyeHeight explains why).
/// </summary>
public static ConfigEntry<float> HeightScale;
/// <summary>
/// Width and depth: "barely visibly thinner", about -8%. Together with HeightScale this is a
/// NON-UNIFORM scale, which is where held weapons and the first-person camera tend to look
/// squashed - doc sec. 7.2. If it does, raise this toward 1 before touching anything else.
/// </summary>
public static ConfigEntry<float> WidthScale;
/// <summary>
/// Scales the almond eyes (EyeExtent). The default 0.8 is the tuned grey look; raise it for
/// bigger eyes.
/// </summary>
public static ConfigEntry<float> EyeSizeMultiplier;
// A grey's eyes, on the Sverm's eye spot: offsets are metres in the head bone's OWN frame
// at human scale, so they land on the same part of the face at any body scale.
// Pushed apart and forward of the Sverm's, because an almond this wide would otherwise
// meet its twin over the nose and sink into the cheek.
public const float EyeSeparation = 0.037f;
public const float EyeForward = 0.090f;
public const float EyeHeight = 0.183f;
// Full width, height and depth of one eye in metres at Eye Size Multiplier 1. The saved
// default of 0.8 makes that 50 x 28 x 18 mm.
public static readonly Vector3 EyeExtent = new Vector3(0.0625f, 0.035f, 0.0225f);
// Degrees. Slant raises the outer corner; wrap turns each eye out toward its temple.
public const float EyeSlant = 22f;
public const float EyeWrap = 20f;
// ─── Eitr: diet, shield, soft fall ───────────────────────────────────
/// <summary>
/// What each food adds to the maximum eitr besides its own: min(hp, stamina) times this.
/// 1 is the design (sec. 3): native eitr plus the lower of hp and stamina.
/// </summary>
public static ConfigEntry<float> DietMultiplier;
/// <summary>
/// Eitr spent per point of damage. 1:1, FIXED, for ever (sec. 4.1): progression comes from
/// the food raising the pool, not from a better rate.
/// </summary>
public static ConfigEntry<float> ShieldRate;
/// <summary>Lightning and spirit cost this many times the rate (sec. 5.1: the double cost).</summary>
public static ConfigEntry<float> ConductiveMultiplier;
/// <summary>
/// Falls cost nothing while there is any eitr (sec. 4.5: soft fall). Off, a fall is shielded
/// like any other blow.
/// </summary>
public static ConfigEntry<bool> SoftFall;
/// <summary>
/// The fastest an Alfr falls while there is eitr, in metres per second. The vanilla Feather
/// Cape caps at 5; a little under that reads as floating.
/// </summary>
public static ConfigEntry<float> FeatherFallSpeed;
// ─── Heimkall: the death that costs a wait ───────────────────────────
/// <summary>Minutes before a second Heimkall is possible, before Yagluth (sec. 6).</summary>
public static ConfigEntry<float> HeimkallMinutes;
/// <summary>The same, once Yagluth is down.</summary>
public static ConfigEntry<float> HeimkallMinutesAfterYagluth;
/// <summary>The same, once Fader is down.</summary>
public static ConfigEntry<float> HeimkallMinutesAfterFader;
/// <summary>
/// Seconds of invulnerability on arrival, so a lethal blow does not simply repeat at the
/// bed. Without it a burning or drowning death would loop.
/// </summary>
public static ConfigEntry<float> HeimkallInvulnerableSeconds;
public static void Bind(ConfigFile config)
{
const string heimkall = "Alfar - Heimkall";
HeimkallMinutes = config.Bind(heimkall, "Cooldown Minutes", 20f,
new ConfigDescription("Minutes between two Heimkalls (the lethal-blow teleport to the bed). Inside this wait, a lethal blow kills normally.",
new AcceptableValueRange<float>(0f, 120f)));
HeimkallMinutesAfterYagluth = config.Bind(heimkall, "Cooldown Minutes After Yagluth", 15f,
new ConfigDescription("The cooldown once Yagluth is defeated.",
new AcceptableValueRange<float>(0f, 120f)));
HeimkallMinutesAfterFader = config.Bind(heimkall, "Cooldown Minutes After Fader", 10f,
new ConfigDescription("The cooldown once Fader is defeated.",
new AcceptableValueRange<float>(0f, 120f)));
HeimkallInvulnerableSeconds = config.Bind(heimkall, "Invulnerable Seconds", 5f,
new ConfigDescription("Seconds nothing can hurt the Alfr after arriving.",
new AcceptableValueRange<float>(0f, 30f)));
const string eitr = "Alfar - Eitr";
DietMultiplier = config.Bind(eitr, "Diet Multiplier", 1f,
new ConfigDescription("Each food adds its native eitr plus min(hp, stamina) times this to the maximum eitr.",
new AcceptableValueRange<float>(0f, 3f)));
ShieldRate = config.Bind(eitr, "Shield Rate", 1f,
new ConfigDescription("Eitr spent per point of damage absorbed (1 = 1:1).",
new AcceptableValueRange<float>(0.1f, 5f)));
ConductiveMultiplier = config.Bind(eitr, "Lightning And Spirit Multiplier", 2f,
new ConfigDescription("Lightning and spirit damage cost this many times the shield rate.",
new AcceptableValueRange<float>(1f, 5f)));
SoftFall = config.Bind(eitr, "Soft Fall", true,
new ConfigDescription("Falling does no damage, and is slowed, while the Alfr has any eitr."));
FeatherFallSpeed = config.Bind(eitr, "Feather Fall Speed", 4f,
new ConfigDescription("Maximum falling speed (m/s) while the Alfr has eitr. Lower floats more.",
new AcceptableValueRange<float>(1f, 20f)));
const string look = "Alfar - Look";
SkinColor = config.Bind(look, "Skin Color", new Color(0.86f, 0.88f, 0.88f, 1f),
new ConfigDescription("How light the ash-grey skin is. The skin texture itself is made grey; this only sets its brightness."));
HeightScale = config.Bind(look, "Height Scale", 1.05f,
new ConfigDescription("Body height against a normal Viking (1.05 = +5%).",
new AcceptableValueRange<float>(0.8f, 1.3f)));
WidthScale = config.Bind(look, "Width Scale", 0.92f,
new ConfigDescription("Body width and depth against a normal Viking (0.92 = 8% thinner).",
new AcceptableValueRange<float>(0.7f, 1.2f)));
EyeSizeMultiplier = config.Bind(look, "Eye Size Multiplier", 0.8f,
new ConfigDescription("Scales the black almond eyes. 0.8 is the default look; raise it for bigger eyes.",
new AcceptableValueRange<float>(0.5f, 3f)));
}
}
}

View file

@ -0,0 +1,397 @@
using System.Collections.Generic;
using Jotunn.Entities;
using Jotunn.Managers;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// The three constructs, the Alfar's only troops (Alfar_Progettazione.txt sec. 8.5):
///
/// Neistvordr a Surtling: hp 60 and a shield of 60 (the vanilla Surtling has 20), fire thrower
/// Steinvordr the StoneGolem: hp 800, the tank, ONE per Nexus
/// Eldingvordr a smaller Abomination at half its hp, which fires a lightning sphere every 8 s
///
/// Everything that makes them the Alfar's is done by what is added, not by rewriting attacks:
/// AlfarMark turns whatever they deal into lightning and keeps it off friends and buildings,
/// AlfarCreatureShield gives them a shield that returns by itself, and RaisedThrall gives them
/// the follow and stay orders every other race's troops already have.
///
/// They are NOT repaired and do not heal: the damage to the body is permanent. RaisedThrall's
/// sentinel regeneration (SkeletonSentryBehaviour) is therefore left off, and the creature's own
/// slow vanilla regeneration is switched off too.
/// </summary>
public static class AlfarConstructs
{
public const string Neistvordr = "AlfarNeistvordr";
public const string Steinvordr = "AlfarSteinvordr";
public const string Eldingvordr = "AlfarEldingvordr";
public const string SphereProjectile = "AlfarLightningSphere";
public const string SphereWeapon = "AlfarSphereAttack";
public class Kind
{
public string PrefabName;
public string Display;
public string Source;
public float Health; // 0 = keep the vanilla creature's
public float HealthFactor; // applied after Health when Health is 0
public float Scale; // 1 = the vanilla size
}
public static readonly Kind[] Roster =
{
new Kind { PrefabName = Neistvordr, Display = "$rov_creature_alfar_neistvordr_name", Source = "Surtling", Health = 60f, Scale = 1f },
new Kind { PrefabName = Steinvordr, Display = "$rov_creature_alfar_steinvordr_name", Source = "StoneGolem", Health = 0f, HealthFactor = 1f, Scale = 0.6f },
new Kind { PrefabName = Eldingvordr, Display = "$rov_creature_alfar_eldingvordr_name", Source = "Abomination", Health = 0f, HealthFactor = 0.5f, Scale = 0.4f },
};
public static Kind Find(string prefabName)
{
foreach (Kind kind in Roster) if (kind.PrefabName == prefabName) return kind;
return null;
}
// ─── Registration ────────────────────────────────────────────────────
public static void Register()
{
// The sphere first: the Eldingvordr's weapon needs it.
bool sphere = RegisterSphere();
foreach (Kind kind in Roster)
{
if (kind.PrefabName == Eldingvordr && !sphere)
{
Jotunn.Logger.LogWarning("[Alfar] No lightning sphere: the Eldingvordr keeps the Abomination's melee.");
}
RegisterOne(kind, sphere);
}
}
private static void RegisterOne(Kind kind, bool sphere)
{
GameObject source = PrefabManager.Cache.GetPrefab<GameObject>(kind.Source);
if (source == null)
{
Jotunn.Logger.LogWarning($"[Alfar] No '{kind.Source}' to build {kind.Display} from.");
return;
}
GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(kind.PrefabName, source);
if (prefab == null) return;
Character character = prefab.GetComponent<Character>();
if (character != null)
{
character.m_name = kind.Display;
character.m_faction = Character.Faction.Players;
if (kind.Health > 0f) character.m_health = kind.Health;
else character.m_health *= kind.HealthFactor;
// The damage to the body is permanent: no slow regeneration either.
character.m_regenAllHPTime = 0f;
}
if (!Mathf.Approximately(kind.Scale, 1f))
{
prefab.transform.localScale = Vector3.one * kind.Scale;
ZNetView nview = prefab.GetComponent<ZNetView>();
if (nview != null) nview.m_syncInitialScale = true;
}
BaseAI ai = prefab.GetComponent<BaseAI>();
if (ai != null) ai.m_randomMoveRange = AlfarNexusConfig.ConstructLeash.Value;
MonsterAI monster = prefab.GetComponent<MonsterAI>();
if (monster != null)
{
// The vanilla creatures attack player-built objects. Ours never touch a building.
monster.m_attackPlayerObjects = false;
monster.m_alertRange = AlfarNexusConfig.ConstructAlertRange.Value;
monster.m_maxChaseDistance = AlfarNexusConfig.ConstructAlertRange.Value;
}
// A construct that dropped Coal, a Surtling core or a trophy would be a loot farm.
foreach (CharacterDrop drops in prefab.GetComponentsInChildren<CharacterDrop>(true))
{
if (drops != null) Object.DestroyImmediate(drops);
}
if (kind.PrefabName == Eldingvordr && sphere) GiveSphereWeapon(prefab);
if (kind.PrefabName == Neistvordr) BlueFlames(prefab);
else Tint(prefab, new Color(0.85f, 0.52f, 0.2f, 1f));
AlfarMark mark = prefab.AddComponent<AlfarMark>();
mark.Role = "construct";
// What a destroyed construct gives back: the METAL it was built from, and nothing else - the
// crystals and the refined eitr are spent for good (design sec. 8.5).
AlfarRefund refund = prefab.AddComponent<AlfarRefund>();
refund.Item = kind.PrefabName == Neistvordr ? "Bronze" : kind.PrefabName == Eldingvordr ? "Iron" : "BlackMetal";
refund.Amount = kind.PrefabName == Neistvordr ? AlfarNexusConfig.NeistMetal.Value
: kind.PrefabName == Eldingvordr ? AlfarNexusConfig.EldingMetal.Value
: AlfarNexusConfig.SteinMetal.Value;
AlfarCreatureShield shield = prefab.AddComponent<AlfarCreatureShield>();
shield.MaxShield = character != null ? character.m_health : 0f;
shield.Shield = shield.MaxShield;
RaisedThrall thrall = prefab.AddComponent<RaisedThrall>();
thrall.m_kind = kind.PrefabName;
thrall.m_commandingRace = AlfarConfig.RaceId;
thrall.m_maxFollowers = -1; // the cap is the Nexus's, per type, counted at the Nexus
thrall.m_witherSeconds = AlfarNexusConfig.WitherSeconds.Value;
thrall.m_homeCheckRange = AlfarNexusConfig.NexusRadius.Value;
thrall.m_refusalMessage = "$rov_msg_thrall_refusal_alfar";
PrefabManager.Instance.AddPrefab(prefab);
Jotunn.Logger.LogInfo($"[Alfar] Registered '{kind.PrefabName}' from '{kind.Source}'.");
}
// ─── The lightning sphere ────────────────────────────────────────────
/// <summary>
/// The Eldingvordr's shot: a sphere that bursts in a small area, hurts only enemies, and never
/// touches a building (doc sec. 8.5 and 16B V12). Cloned from the Dverger ice projectile, the
/// clean base the probe found: an area burst and NO lingering effect spawned on impact (the
/// fire one drops a fire field and also spawns on buildings).
/// </summary>
private static bool RegisterSphere()
{
GameObject source = PrefabManager.Cache.GetPrefab<GameObject>("DvergerStaffIce_projectile");
if (source == null)
{
Jotunn.Logger.LogWarning("[Alfar] DvergerStaffIce_projectile not found: no lightning sphere.");
return false;
}
GameObject projectile = PrefabManager.Instance.CreateClonedPrefab(SphereProjectile, source);
if (projectile == null) return false;
Projectile settings = projectile.GetComponent<Projectile>();
if (settings == null) return false;
settings.m_gravity = 0f;
settings.m_ttl = 4f;
settings.m_aoe = 3f;
settings.m_aoeSkipWearNTear = true;
settings.m_hitFriendly = false;
settings.m_noDamageFriendly = true;
settings.m_hitOwner = false;
settings.m_statusEffect = "";
Tint(projectile, new Color(0.55f, 0.85f, 1f, 1f));
PrefabManager.Instance.AddPrefab(projectile);
// The weapon that fires it: the Surtling's own fireball weapon, because a creature that
// shoots needs an item with a projectile attack, and that is the one that exists.
GameObject surtling = PrefabManager.Cache.GetPrefab<GameObject>("Surtling");
Humanoid surtlingHumanoid = surtling != null ? surtling.GetComponent<Humanoid>() : null;
GameObject fireball = surtlingHumanoid != null && surtlingHumanoid.m_defaultItems != null &&
surtlingHumanoid.m_defaultItems.Length > 0
? surtlingHumanoid.m_defaultItems[0]
: null;
if (fireball == null)
{
Jotunn.Logger.LogWarning("[Alfar] The Surtling's fireball weapon was not found: no sphere weapon.");
return false;
}
GameObject weapon = PrefabManager.Instance.CreateClonedPrefab(SphereWeapon, fireball);
if (weapon == null) return false;
ItemDrop drop = weapon.GetComponent<ItemDrop>();
if (drop == null || drop.m_itemData == null || drop.m_itemData.m_shared == null) return false;
ItemDrop.ItemData.SharedData shared = drop.m_itemData.m_shared;
shared.m_name = "$rov_item_alfar_sphere_name";
// One shot every eight seconds (design): the AI waits this long between uses.
shared.m_aiAttackInterval = AlfarNexusConfig.SphereIntervalSeconds.Value;
shared.m_aiAttackRange = AlfarNexusConfig.SphereRange.Value;
shared.m_aiAttackRangeMin = 4f;
HitData.DamageTypes damage = default(HitData.DamageTypes);
damage.m_lightning = AlfarNexusConfig.SphereDamage.Value;
shared.m_damages = damage;
if (shared.m_attack != null)
{
shared.m_attack.m_attackProjectile = projectile;
// The Abomination's right hand: where the sphere leaves from.
shared.m_attack.m_attackOriginJoint = "r.hand";
}
ItemManager.Instance.AddItem(new CustomItem(weapon, fixReference: false));
return true;
}
private static void GiveSphereWeapon(GameObject prefab)
{
Humanoid humanoid = prefab.GetComponent<Humanoid>();
GameObject weapon = PrefabManager.Instance.GetPrefab(SphereWeapon);
if (humanoid == null || weapon == null) return;
humanoid.m_defaultItems = new[] { weapon };
humanoid.m_randomWeapon = new GameObject[0];
humanoid.m_randomArmor = new GameObject[0];
humanoid.m_randomShield = new GameObject[0];
humanoid.m_randomSets = new Humanoid.ItemSet[0];
}
// ─── Colour ──────────────────────────────────────────────────────────
/// <summary>
/// A tint on every mesh, through renderer.materials (an instanced copy) and NEVER .material or
/// sharedMaterial: the vanilla creature uses the same asset and must stay as it is (guide 3.5).
/// This is a recolour and not a retexture: a true repaint of the golem and the Abomination is
/// still to do (test file, phase 6).
/// </summary>
public static void Tint(GameObject prefab, Color color)
{
foreach (Renderer renderer in prefab.GetComponentsInChildren<Renderer>(true))
{
if (renderer is ParticleSystemRenderer || renderer is TrailRenderer || renderer is LineRenderer) continue;
Material[] materials = renderer.materials;
foreach (Material material in materials)
{
if (material == null) continue;
if (material.HasProperty("_Color")) material.color = color;
if (material.HasProperty("_EmissionColor"))
{
material.SetColor("_EmissionColor", color * 0.08f);
material.EnableKeyword("_EMISSION");
}
}
renderer.materials = materials;
}
foreach (Light light in prefab.GetComponentsInChildren<Light>(true)) light.color = color;
}
/// <summary>
/// The Surtling is made of particles and lights, not textures, and the vanilla prefab ALREADY
/// carries blue variants of its flames, switched off (probe, doc 16C P2): turn those on, turn
/// the red ones off, and recolour the glow of the body and the point light.
/// </summary>
private static void BlueFlames(GameObject prefab)
{
foreach (Transform child in prefab.GetComponentsInChildren<Transform>(true))
{
if (child.name == "flames_world_BLUE") child.gameObject.SetActive(true);
else if (child.name == "flames" || child.name == "flames_world" || child.name == "flames_world_Purple")
{
child.gameObject.SetActive(false);
}
}
Color blue = new Color(0.25f, 0.55f, 1f, 1f);
foreach (Light light in prefab.GetComponentsInChildren<Light>(true)) light.color = blue;
foreach (Renderer renderer in prefab.GetComponentsInChildren<SkinnedMeshRenderer>(true))
{
Material[] materials = renderer.materials;
foreach (Material material in materials)
{
if (material != null && material.HasProperty("_EmissionColor"))
{
// The vanilla emission is white-hot (73): keep the strength, change the hue.
material.SetColor("_EmissionColor", new Color(0.25f, 0.55f, 1f, 1f) * 30f);
}
}
renderer.materials = materials;
}
}
// ─── Counting and spawning (called by the Nexus) ─────────────────────
/// <summary>
/// A destroyed construct drops the metal it cost, on the ground where it fell. Only a DEATH:
/// a zone unloading destroys the object too and must not pay anyone (the same rule as the
/// Butler's payload).
/// </summary>
public class AlfarRefund : MonoBehaviour
{
public string Item = "";
public int Amount;
}
[HarmonyLib.HarmonyPatch(typeof(Character), "OnDeath")]
public static class Alfar_Refund_Patch
{
public static void Postfix(Character __instance)
{
AlfarRefund refund = __instance != null ? __instance.GetComponent<AlfarRefund>() : null;
if (refund == null || refund.Amount <= 0 || ObjectDB.instance == null) return;
GameObject prefab = ObjectDB.instance.GetItemPrefab(refund.Item);
ItemDrop template = prefab != null ? prefab.GetComponent<ItemDrop>() : null;
if (template == null || template.m_itemData == null) return;
int left = refund.Amount;
int max = Mathf.Max(1, template.m_itemData.m_shared.m_maxStackSize);
Vector3 at = __instance.transform.position + Vector3.up * 0.5f;
while (left > 0)
{
int stack = Mathf.Min(left, max);
ItemDrop.ItemData clone = template.m_itemData.Clone();
clone.m_dropPrefab = prefab;
ItemDrop.DropItem(clone, stack, at + Random.insideUnitSphere * 0.3f, Quaternion.identity);
left -= stack;
}
refund.Amount = 0; // once only
}
}
public static int CountAlive(Vector3 anchor, string prefabName)
{
int count = 0;
foreach (RaisedThrall thrall in RaisedThrall.BoundTo(anchor))
{
if (thrall != null && thrall.Kind == prefabName) count++;
}
return count;
}
public static bool Spawn(Vector3 anchor, string prefabName)
{
GameObject prefab = ZNetScene.instance != null ? ZNetScene.instance.GetPrefab(prefabName) : null;
if (prefab == null)
{
Jotunn.Logger.LogWarning($"[Alfar] No '{prefabName}' in ZNetScene: it cannot be built.");
return false;
}
Vector3 where = SpawnSpot(anchor);
GameObject spawned = Object.Instantiate(prefab, where, Quaternion.Euler(0f, Random.Range(0, 360), 0f));
RaisedThrall thrall = spawned != null ? spawned.GetComponent<RaisedThrall>() : null;
if (thrall != null) thrall.Bind(anchor);
return spawned != null;
}
/// <summary>A free spot on a ring around the Nexus, on the ground, or due south as a last resort.</summary>
public static Vector3 SpawnSpot(Vector3 centre)
{
const float radius = 3.5f;
int obstacleMask = LayerMask.GetMask("Default", "static_solid", "Default_small", "piece", "vehicle");
float start = Random.Range(0f, 360f);
for (int i = 0; i < 12; i++)
{
float angle = (start + i * 30f) * Mathf.Deg2Rad;
Vector3 candidate = centre + new Vector3(Mathf.Cos(angle), 0f, Mathf.Sin(angle)) * radius;
if (ZoneSystem.instance != null) candidate.y = ZoneSystem.instance.GetGroundHeight(candidate);
if (Physics.CheckSphere(candidate + Vector3.up * 1.5f, 1f, obstacleMask)) continue;
return candidate + Vector3.up * 0.3f;
}
Vector3 fallback = centre + new Vector3(0f, 0f, -radius);
if (ZoneSystem.instance != null) fallback.y = ZoneSystem.instance.GetGroundHeight(fallback);
return fallback + Vector3.up * 0.3f;
}
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,710 @@
using System.Collections.Generic;
using HarmonyLib;
using Jotunn.Entities;
using Jotunn.Managers;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// The LJOSVAETTIR, the Alfar's drones (Alfar_Progettazione.txt sec. 9): a Deathsquito without legs,
/// stinger or buzz, bronze, with blue light. One kind of drone does every job (the work itself is
/// AlfarDroneWork); the only thing apart is the GRAFVAETTIR, the same creature thrown like a
/// grenade to dig the precious ores around a point for two minutes and then vanish.
///
/// What a drone is by itself: 25 hp and a shield of 25, tamed, tied to its Ljoskjarne, and able to
/// defend itself with a lightning zap of 1 damage every two seconds. It never attacks anything
/// outside the Nexus's radius and never goes after anything: it is a worker, not a soldier.
///
/// The Deathsquito is ONE skinned mesh with one material (probe, doc 16C P1): the legs are bones, so
/// they are hidden by scaling the bones to zero, and the blue is an emission on a bronze body, not
/// separate eyes and wings - a true repaint is still to do.
/// </summary>
public static class AlfarDrones
{
public const string DroneName = "AlfarDrone";
public const string MinerName = "AlfarGrafvaettir";
public const string ZapWeapon = "AlfarDroneZap";
private static readonly Color Bronze = new Color(1f, 0.62f, 0.25f, 1f);
private static readonly Color ElectricBlue = new Color(0.25f, 0.65f, 1f, 1f);
public static void Register()
{
GameObject source = PrefabManager.Cache.GetPrefab<GameObject>("Deathsquito");
if (source == null)
{
Jotunn.Logger.LogWarning("[Alfar] No 'Deathsquito' to build the drones from.");
return;
}
bool zap = RegisterZap(source);
RegisterOne(source, DroneName, "$rov_creature_alfar_drone_name", zap, miner: false);
RegisterOne(source, MinerName, "$rov_creature_alfar_grafvaettir_name", zap, miner: true);
}
/// <summary>The Deathsquito's sting turned into a zap: 1 lightning, every two seconds.</summary>
private static bool RegisterZap(GameObject deathsquito)
{
Humanoid humanoid = deathsquito.GetComponent<Humanoid>();
GameObject sting = humanoid != null && humanoid.m_defaultItems != null && humanoid.m_defaultItems.Length > 0
? humanoid.m_defaultItems[0]
: null;
if (sting == null) return false;
GameObject weapon = PrefabManager.Instance.CreateClonedPrefab(ZapWeapon, sting);
if (weapon == null) return false;
ItemDrop drop = weapon.GetComponent<ItemDrop>();
if (drop == null || drop.m_itemData == null || drop.m_itemData.m_shared == null) return false;
ItemDrop.ItemData.SharedData shared = drop.m_itemData.m_shared;
shared.m_name = "$rov_item_alfar_zap_name";
HitData.DamageTypes damage = default(HitData.DamageTypes);
damage.m_lightning = AlfarNexusConfig.DroneZapDamage.Value;
shared.m_damages = damage;
shared.m_aiAttackInterval = AlfarNexusConfig.DroneZapInterval.Value;
ItemManager.Instance.AddItem(new CustomItem(weapon, fixReference: false));
return true;
}
private static void RegisterOne(GameObject source, string prefabName, string display, bool zap, bool miner)
{
GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(prefabName, source);
if (prefab == null) return;
Character character = prefab.GetComponent<Character>();
if (character != null)
{
character.m_name = display;
character.m_faction = Character.Faction.Players;
character.m_health = AlfarNexusConfig.DroneHealth.Value;
}
Humanoid humanoid = prefab.GetComponent<Humanoid>();
if (humanoid != null)
{
GameObject weapon = zap ? PrefabManager.Instance.GetPrefab(ZapWeapon) : null;
// A miner does not fight at all; the worker only defends itself.
humanoid.m_defaultItems = !miner && weapon != null ? new[] { weapon } : new GameObject[0];
humanoid.m_randomWeapon = new GameObject[0];
humanoid.m_randomArmor = new GameObject[0];
humanoid.m_randomShield = new GameObject[0];
humanoid.m_randomSets = new Humanoid.ItemSet[0];
}
MonsterAI monster = prefab.GetComponent<MonsterAI>();
if (monster != null)
{
monster.m_attackPlayerObjects = false;
monster.m_alertRange = AlfarNexusConfig.NexusRadius.Value;
monster.m_maxChaseDistance = AlfarNexusConfig.NexusRadius.Value;
}
BaseAI ai = prefab.GetComponent<BaseAI>();
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))
{
if (drops != null) Object.DestroyImmediate(drops);
}
// The buzz: the continuous sound child, and the flying loop effect.
foreach (Transform child in prefab.GetComponentsInChildren<Transform>(true))
{
if (child != null && child.name == "SFX") Object.DestroyImmediate(child.gameObject);
}
if (character != null) character.m_flyingContinuousEffect = new EffectList { m_effectPrefabs = new EffectList.EffectData[0] };
HideLegs(prefab);
Look(prefab);
prefab.AddComponent<AlfarDroneLook>();
AlfarMark mark = prefab.AddComponent<AlfarMark>();
mark.Role = miner ? "miner" : "drone";
AlfarCreatureShield shield = prefab.AddComponent<AlfarCreatureShield>();
shield.MaxShield = AlfarNexusConfig.DroneHealth.Value;
shield.Shield = shield.MaxShield;
if (miner)
{
// The mining drone has no anchor and no leash: it lives two minutes and vanishes.
prefab.AddComponent<AlfarMiner>();
}
else
{
// The worker is NOT a RaisedThrall: that brings the follow command on E, and a drone
// that can be walked out of the base stops working (the Butler's reasoning, Butler 9).
// AlfarDroneAI keeps its own anchor to the Nexus and its own wither.
AlfarDroneAI work = prefab.AddComponent<AlfarDroneAI>();
work.m_fightsBack = true; // it defends itself with the zap
work.m_homeDistance = 4f;
}
PrefabManager.Instance.AddPrefab(prefab);
Jotunn.Logger.LogInfo($"[Alfar] Registered '{prefabName}'.");
}
/// <summary>
/// No legs: the mesh is one skinned body, so the leg bones are scaled to zero and take their
/// part of the mesh with them. The stinger has no bone of its own and is left (doc 16C P1).
/// </summary>
private static void HideLegs(GameObject prefab)
{
foreach (Transform bone in prefab.GetComponentsInChildren<Transform>(true))
{
string n = bone.name;
if (n == "L.leg1" || n == "R.leg1") bone.localScale = Vector3.zero;
}
}
private static void Look(GameObject prefab)
{
foreach (Renderer renderer in prefab.GetComponentsInChildren<SkinnedMeshRenderer>(true))
{
Material[] materials = renderer.materials;
foreach (Material material in materials)
{
if (material == null) continue;
if (material.HasProperty("_Color")) material.color = Bronze;
if (material.HasProperty("_EmissionColor"))
{
material.SetColor("_EmissionColor", ElectricBlue * 0.15f);
material.EnableKeyword("_EMISSION");
}
}
renderer.materials = materials;
}
foreach (Light light in prefab.GetComponentsInChildren<Light>(true)) light.color = ElectricBlue;
}
/// <summary>
/// The same look, applied to the LIVE body at spawn and re-applied after the animator every
/// frame for the bones: edits made on the registered clone may not reach the instance, and the
/// animator can write the leg scale back.
/// </summary>
public class AlfarDroneLook : MonoBehaviour
{
private Transform[] legs;
private void Awake()
{
var list = new System.Collections.Generic.List<Transform>();
foreach (Transform bone in GetComponentsInChildren<Transform>(true))
{
if (bone.name == "L.leg1" || bone.name == "R.leg1") list.Add(bone);
}
legs = list.ToArray();
Look(gameObject);
}
private void LateUpdate()
{
foreach (Transform leg in legs) if (leg != null) leg.localScale = Vector3.zero;
}
}
// ─── Counting and spawning ───────────────────────────────────────────
public static int CountAlive(Vector3 anchor)
{
int count = 0;
foreach (AlfarDroneAI drone in AlfarDroneAI.All)
{
if (drone != null && drone.IsBoundTo(anchor)) count++;
}
return count;
}
public static bool Spawn(Vector3 anchor)
{
GameObject prefab = ZNetScene.instance != null ? ZNetScene.instance.GetPrefab(DroneName) : null;
if (prefab == null)
{
Jotunn.Logger.LogWarning($"[Alfar] No '{DroneName}' in ZNetScene: no drone can be made.");
return false;
}
Vector3 where = AlfarConstructs.SpawnSpot(anchor) + Vector3.up * 1.5f;
GameObject spawned = Object.Instantiate(prefab, where, Quaternion.identity);
AlfarDroneAI work = spawned != null ? spawned.GetComponent<AlfarDroneAI>() : null;
if (work != null) work.Bind(anchor);
return spawned != null;
}
}
/// <summary>
/// A MINING DRONE: thrown to a point, it digs the precious ores around that point for a fixed time
/// and then vanishes (design sec. 9.3). It takes over its own AI tick like the Butler's servants do
/// (a prefix on MonsterAI.UpdateAI), flies to the nearest deposit on the list and strikes it with
/// pickaxe damage at a tool tier high enough for any of them. The ore falls where it stands.
///
/// Whatever it breaks is on the list in AlfarMiner.Deposits; a name list in the config so a
/// wrong or missing name is a config edit, not a rebuild.
/// </summary>
public class AlfarMiner : MonoBehaviour
{
public Vector3 Centre;
public float Radius = 12f;
public float LiveSeconds = 120f;
// 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 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 =
AccessTools.Method(typeof(BaseAI), "MoveTo", new[] { typeof(float), typeof(Vector3), typeof(float), typeof(bool) });
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)
{
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)
{
if (!loaded) Load();
if (Now - bornAt >= LiveSeconds)
{
ZNetView nview = GetComponent<ZNetView>();
if (nview != null && nview.IsValid() && nview.IsOwner()) ZNetScene.instance.Destroy(gameObject);
return true;
}
// A deposit another drone just broke is still there until the end of the frame, with a
// 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; }
// 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);
lastDistance = distance;
if (distance > Reach)
{
if (MoveToMethod != null) MoveToMethod.Invoke(ai, new object[] { dt, point + Vector3.up * 1.5f, 2f, true });
return true;
}
ai.StopMoving();
if (Time.time < nextStrike) return true;
nextStrike = Time.time + 1f;
Strike(target, area, point);
strikes++;
return true;
}
private static string[] names;
private static string namesSource;
// 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)
{
if (prefabName.IndexOf(wanted.Trim(), System.StringComparison.OrdinalIgnoreCase) >= 0) return true;
}
return false;
}
private Component FindDeposit()
{
Component best = null;
float bestDistance = float.MaxValue;
foreach (Collider collider in Physics.OverlapSphere(Centre, Radius, ~0, QueryTriggerInteraction.Ignore))
{
Component deposit = DepositOf(collider);
if (deposit == null) continue;
if (!Live(deposit)) continue;
string prefabName = DepositName(deposit);
if (!IsPrecious(prefabName)) continue;
float distance = Vector3.Distance(transform.position, deposit.transform.position);
if (distance < bestDistance) { best = deposit; bestDistance = distance; }
}
return best;
}
/// <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;
if (destructible == null) { lastHit = $"{deposit.GetType().Name} is not IDestructible"; return; }
HitData hit = new HitData();
hit.m_damage.m_pickaxe = AlfarNexusConfig.MinerDamage.Value;
hit.m_toolTier = 100;
hit.m_dodgeable = false;
hit.m_blockable = false;
hit.m_hitCollider = area;
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>());
// Overwritten by the patches below at each step the hit gets through. Vanilla runs the
// RPC on this machine at once when we own the deposit, so `striking` is still set then.
lastHit = "Damage not entered";
striking = this;
rpcRan = false;
try
{
destructible.Damage(hit);
// 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; }
}
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")]
public static class Alfar_Miner_UpdateAI_Patch
{
public static bool Prefix(MonsterAI __instance, float __0, ref bool __result)
{
if (__instance == null) return true;
AlfarMiner miner = __instance.GetComponent<AlfarMiner>();
if (miner == null) return true;
__result = miner.Tick(__instance, __0);
return false;
}
}
}
}

View file

@ -0,0 +1,166 @@
using System.Reflection;
using HarmonyLib;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// The Alfar's one resource (Alfar_Progettazione.txt sec. 3, 4 and 5.1): food becomes eitr, and
/// eitr is the shield.
///
/// Every signature and call order here was read from assembly_valheim.dll (doc sec. 16B V1-V4),
/// not remembered:
/// - Character.ApplyDamage is the single final stage for direct hits, burning and poison
/// ticks AND falls, so one prefix on it covers all three;
/// - Player.RPC_UseEitr spends eitr and arms the vanilla regeneration delay, which is the
/// only brake the shield has - writing m_eitr by hand would skip the delay;
/// - Player.GetTotalFoodValue is what UpdateFood hands to SetMaxEitr.
/// </summary>
public static class AlfarEitr
{
private static readonly MethodInfo UseEitrRpc =
AccessTools.Method(typeof(Player), "RPC_UseEitr", new[] { typeof(long), typeof(float) });
/// <summary>
/// Spends eitr WITHOUT Game.m_eitrRate scaling, so the rate is exactly the configured one.
/// UseEitr would multiply by the world modifier first; the RPC does not, and it is what
/// arms the regeneration delay (V3).
/// </summary>
public static void Spend(Player player, float amount)
{
if (player == null || amount <= 0f) return;
if (UseEitrRpc == null)
{
Jotunn.Logger.LogWarning("[Alfar] Player.RPC_UseEitr not found: the shield cannot spend eitr.");
return;
}
UseEitrRpc.Invoke(player, new object[] { 0L, amount });
}
// ─── Diet ────────────────────────────────────────────────────────────
/// <summary>
/// Each food adds min(hp, stamina) to the maximum eitr, on top of the eitr it already has.
/// Clarified by the user: the minimum is between hp and stamina ONLY, so a plain cooked
/// meat (40 / 30 / 0) is worth +30 eitr and a balanced food is better than a lopsided one.
///
/// Locally only: GetTotalFoodValue is the owner's own bookkeeping. Positional parameters
/// (guide 5.16): __0 hp, __1 stamina, __2 eitr.
/// </summary>
[HarmonyPatch(typeof(Player), "GetTotalFoodValue")]
public static class Alfar_FoodValue_Patch
{
public static void Postfix(Player __instance, ref float __2)
{
if (__instance == null || !AlfarVisuals.IsAlfarPlayer(__instance)) return;
float bonus = 0f;
foreach (Player.Food food in __instance.GetFoods())
{
bonus += Mathf.Min(food.m_health, food.m_stamina);
}
__2 += bonus * AlfarConfig.DietMultiplier.Value;
}
}
// ─── Shield and soft fall ────────────────────────────────────────────
/// <summary>
/// Blows land on the eitr first, 1 for 1.
///
/// - No cooldown: the shield absorbs for as long as one point of eitr remains.
/// - Lightning and spirit cost double (the cost, not the damage: DamageModifier.Weak is a
/// flat +50% and cannot be made to double anything).
/// - A blow bigger than the pool is shared out: the eitr takes the share it can, the body
/// takes the rest.
/// - Drowning and the edge of the world skip the shield altogether; falls are free while
/// there is eitr and shielded like anything else once there is none left.
///
/// The prefix edits the HitData and lets ApplyDamage run: with nothing left in it,
/// ApplyDamage returns at once ("took no damage"). Positional parameters, and the argument
/// types are in the attribute so the patch binds to the real overload (guide 5.16).
/// </summary>
[HarmonyPatch(typeof(Character), "ApplyDamage",
new[] { typeof(HitData), typeof(bool), typeof(bool), typeof(HitData.DamageModifier) })]
public static class Alfar_ApplyDamage_Patch
{
public static void Prefix(Character __instance, HitData __0)
{
Player player = __instance as Player;
if (player == null || __0 == null) return;
if (!AlfarVisuals.IsAlfarPlayer(player)) return;
// The shield belongs to whoever owns the body: ApplyDamage runs on the owner, and a
// remote copy must not spend eitr it does not hold.
ZNetView nview = player.GetComponent<ZNetView>();
if (nview == null || !nview.IsValid() || !nview.IsOwner()) return;
// The same early exits ApplyDamage has: nothing to absorb, nothing to spend.
if (player.IsDead() || player.IsTeleporting() || player.InCutscene() || player.InGodMode()) return;
// Just arrived by Heimkall: nothing hurts for a few seconds, or a burning death would
// simply repeat at the bed.
if (Time.time < AlfarHeimkall.InvulnerableUntil)
{
__0.m_damage = default(HitData.DamageTypes);
return;
}
// In the archon form the pool IS the defence: it takes every blow, drowning and the
// edge of the world included, and the eitr is already spent (AlfarArchon).
if (AlfarArchon.Active)
{
AlfarArchon.Absorb(player, __0);
return;
}
HitData.HitType type = __0.m_hitType;
if (type == HitData.HitType.Drowning || type == HitData.HitType.EdgeOfWorld) return;
float available = player.GetEitr();
if (type == HitData.HitType.Fall && AlfarConfig.SoftFall.Value)
{
// Soft fall: free while there is eitr, a normal fall once there is none.
if (available > 0f) __0.m_damage = default(HitData.DamageTypes);
return;
}
float cost = Cost(__0.m_damage);
if (cost <= 0f || available <= 0f) return;
if (available >= cost)
{
Spend(player, cost);
__0.m_damage = default(HitData.DamageTypes);
return;
}
// Shared out: the eitr absorbs the fraction it can pay for, the body takes the rest.
float covered = available / cost;
HitData.DamageTypes remaining = __0.m_damage;
remaining.Modify(1f - covered);
__0.m_damage = remaining;
Spend(player, available);
}
/// <summary>
/// The eitr a blow costs. Every damage type that wounds a person counts; chop and
/// pickaxe are tool damage (trees, rocks) and do not. Lightning and spirit are doubled.
/// </summary>
private static float Cost(HitData.DamageTypes damage)
{
float rate = AlfarConfig.ShieldRate.Value;
float conductive = AlfarConfig.ConductiveMultiplier.Value;
float ordinary = damage.m_damage + damage.m_blunt + damage.m_slash + damage.m_pierce +
damage.m_fire + damage.m_frost + damage.m_poison;
float double_ = damage.m_lightning + damage.m_spirit;
return (ordinary + double_ * conductive) * rate;
}
}
}
}

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,171 @@
using System.Globalization;
using HarmonyLib;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// HEIMKALL: a lethal blow does not kill an Alfr, it sends them to their bed with one hit point
/// (Alfar_Progettazione.txt sec. 6). Then a wait: 20 minutes, 15 after Yagluth, 10 after Fader.
/// Inside the wait a lethal blow kills like it does anyone.
///
/// HOW IT AVOIDS DEATH (read from the IL, doc sec. 16B V5):
/// Character.ApplyDamage ends with the health at zero, and the death itself is not decided
/// there but in Character.CheckDeath, which Character.CustomFixedUpdate calls on its next step.
/// So a POSTFIX on ApplyDamage that puts one hit point back, the same frame, means the check
/// finds a living body and there is no death routine, no tomb, no skill loss, no message.
///
/// The timer lives in m_customData as a world-time stamp, so it survives a logout.
/// </summary>
public static class AlfarHeimkall
{
private const string TimerKey = "Alfar_HeimkallAt";
/// <summary>Time.time until which nothing may hurt the local Alfr (the arrival grace).</summary>
public static float InvulnerableUntil;
// ─── The timer ───────────────────────────────────────────────────────
/// <summary>The cooldown for the current boss progress, in seconds.</summary>
public static float CooldownSeconds()
{
int state = BossProgressionManager.GetCurrentProgressionState();
float minutes = state >= 8 ? AlfarConfig.HeimkallMinutesAfterFader.Value
: state >= 6 ? AlfarConfig.HeimkallMinutesAfterYagluth.Value
: AlfarConfig.HeimkallMinutes.Value;
return minutes * 60f;
}
/// <summary>Seconds left before the next Heimkall; 0 when it is ready.</summary>
public static float Remaining(Player player)
{
if (player == null || player.m_customData == null || ZNet.instance == null) return 0f;
if (!player.m_customData.TryGetValue(TimerKey, out string stamp)) return 0f;
if (!double.TryParse(stamp, NumberStyles.Float, CultureInfo.InvariantCulture, out double at)) return 0f;
double elapsed = ZNet.instance.GetTimeSeconds() - at;
// A stamp from a different world (its clock is another clock) reads as the future, or as
// a wait longer than any cooldown. Either way the timer is not this world's: ready.
float cooldown = CooldownSeconds();
if (elapsed < 0d || elapsed > 1e9) return 0f;
return Mathf.Max(0f, cooldown - (float)elapsed);
}
public static bool IsReady(Player player) => Remaining(player) <= 0f;
public static void StartTimer(Player player)
{
if (player == null || ZNet.instance == null) return;
player.m_customData[TimerKey] =
ZNet.instance.GetTimeSeconds().ToString("R", CultureInfo.InvariantCulture);
}
public static void ResetTimer(Player player)
{
if (player != null && player.m_customData != null) player.m_customData.Remove(TimerKey);
AlfarStatusEffects.ClearTimer("heimkall");
}
private static float nextIconSync;
/// <summary>
/// Keeps the on-screen Heimkall countdown honest: status effects are not saved, so after a
/// reload the wait is put back on screen with what is really left of it, and removed when over.
/// </summary>
public static void SyncIcon(Player player)
{
if (Time.time < nextIconSync) return;
nextIconSync = Time.time + 2f;
float left = Remaining(player);
bool shown = AlfarStatusEffects.HasTimer("heimkall");
if (left > 0f && !shown) AlfarStatusEffects.ShowTimer("heimkall", left);
else if (left <= 0f && shown) AlfarStatusEffects.ClearTimer("heimkall");
}
// ─── The call home ───────────────────────────────────────────────────
/// <summary>
/// Teleports to the bed (or the world spawn when there is none) at one hit point, clears what
/// was killing the body, and starts the wait. Returns false when it is not ready.
/// </summary>
public static bool TryTrigger(Player player, string reason, bool force = false)
{
// force: the archon form ends with a Heimkall that it already paid for at the start.
if (player == null || (!force && !IsReady(player))) return false;
bool bed;
Vector3 destination = FindDestination(out bed);
// distantTeleport tells Valheim to stream the destination zone in first. Anything past a
// couple of zone-widths needs it.
bool distant = Vector3.Distance(player.transform.position, destination) > 100f;
bool teleported = player.TeleportTo(destination, player.transform.rotation, distant);
// Whether or not the teleport was accepted (it refuses for two seconds after another
// one), the body must not die this frame.
player.SetHealth(1f);
// What was killing the body goes with it: burning, poison, the cold, being wet. Cleared
// before the passive is put back, since RemoveAll takes that too.
player.GetSEMan().RemoveAllStatusEffects(true);
AlfarStatusEffects.Ensure(player);
InvulnerableUntil = Time.time + AlfarConfig.HeimkallInvulnerableSeconds.Value;
StartTimer(player);
AlfarStatusEffects.ShowTimer("heimkall", CooldownSeconds());
Jotunn.Logger.LogInfo($"[Alfar] Heimkall ({reason}): teleported={teleported} to {destination}; " +
$"next in {CooldownSeconds() / 60f:0} min.");
player.Message(MessageHud.MessageType.Center, ModText.Get(bed ? "rov_msg_alfar_heimkall" : "rov_msg_alfar_heimkall_nobed"));
return true;
}
/// <summary>
/// The bed the player set, else the world's original spawn. A bed point already has its height;
/// the world spawn is stored with a placeholder height (50), so its ground is worked out from the
/// world generator, which answers even when the zone there is not loaded yet - the first version
/// stood the Alfr at 50.5 m in the air or inside a hill. A bed counts only after the player has
/// SET it (sleeping in it, or interacting with it); an unused bed is not a spawn point.
/// </summary>
private static Vector3 FindDestination(out bool bed)
{
PlayerProfile profile = Game.instance != null ? Game.instance.GetPlayerProfile() : null;
bed = profile != null && profile.HaveCustomSpawnPoint();
if (bed) return profile.GetCustomSpawnPoint() + Vector3.up * 0.5f;
Vector3 point = PlayerProfile.m_originalSpawnPoint;
if (WorldGenerator.instance != null)
{
float ground = WorldGenerator.instance.GetHeight(point.x, point.z);
point.y = Mathf.Max(ground, 30f) + 1f; // 30 is the sea level: never under the water
}
return point;
}
// ─── The patch ───────────────────────────────────────────────────────
/// <summary>
/// After the blow has landed: if it left the body at zero, call it home instead. The shield
/// prefix has already taken what it could, so this only fires for the blow the eitr could
/// not cover (or a fall at eitr zero, a drowning, the edge of the world).
/// </summary>
[HarmonyPatch(typeof(Character), "ApplyDamage",
new[] { typeof(HitData), typeof(bool), typeof(bool), typeof(HitData.DamageModifier) })]
public static class Alfar_Heimkall_Patch
{
public static void Postfix(Character __instance)
{
Player player = __instance as Player;
if (player == null || player != Player.m_localPlayer) return;
if (!AlfarVisuals.IsAlfarPlayer(player)) return;
if (player.IsDead() || player.GetHealth() > 0f) return;
TryTrigger(player, "lethal blow");
}
}
}
}

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

@ -0,0 +1,126 @@
using HarmonyLib;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// LEVITATION (Alfar_Progettazione.txt sec. 4.6): in the air, hold the jump key and the Alfr rises
/// slowly, burning eitr slowly. Let go and the soft fall takes over.
///
/// There is no hover in vanilla. This pushes the rigidbody's vertical speed up toward a small
/// target while the key is held, and nothing else: no horizontal speed is added, so it is a way
/// over a ledge or out of a pit and not flight (the pool of an early Alfr lasts about half a
/// minute of it).
///
/// It runs on the owner's FixedUpdate, where the rigidbody is read, and the position syncs like
/// any other movement. The eitr is spent in small batches, not every physics step: each spend arms
/// the regeneration delay and goes through an RPC call.
/// </summary>
public static class AlfarLevitation
{
// A short moment in the air before it starts, so a normal jump (a tap) is just a jump.
private const float AirDelay = 0.2f;
private const float SpendInterval = 0.25f;
private static float airTime;
private static float owed;
private static float nextSpend;
public static bool Rising { get; private set; }
[HarmonyPatch(typeof(Player), "FixedUpdate")]
public static class Alfar_Levitation_Patch
{
public static void Postfix(Player __instance)
{
if (__instance == null || __instance != Player.m_localPlayer) return;
if (!AlfarVisuals.IsAlfarPlayer(__instance) || __instance.IsDead()) { Reset(); return; }
// THE ARCHON FLIES for as long as the form lasts: it hovers where it is, climbs while
// jump is held and sinks while crouch is held. The eitr is already gone, so nothing is
// spent. Horizontal movement stays the normal controls.
if (AlfarArchon.Active)
{
Rigidbody flyer = Traverse.Create(__instance).Field("m_body").GetValue<Rigidbody>();
if (flyer != null)
{
float speed = AlfarPowerConfig.LevitationRise.Value * 2f;
float target = 0f;
if (Time.time - AlfarArchon.StartedAt < 0.6f) target = 4f; // lift off
else if (RaceInput.Allowed && JumpHeld()) target = speed;
else if (RaceInput.Allowed && CrouchHeld()) target = -speed;
Vector3 velocity = flyer.linearVelocity;
velocity.y = Mathf.Lerp(velocity.y, target, 0.25f);
flyer.linearVelocity = velocity;
}
Traverse.Create(__instance).Field("m_maxAirAltitude").SetValue(__instance.transform.position.y);
Rising = true;
return;
}
bool wants = RaceInput.Allowed && JumpHeld();
bool airborne = !__instance.IsOnGround() && !__instance.IsSwimming() && !__instance.IsAttached() &&
!__instance.IsFlying();
airTime = airborne ? airTime + Time.fixedDeltaTime : 0f;
float cost = AlfarPowerConfig.LevitationCostPerSecond.Value;
bool canPay = AlfarArchon.Active || __instance.GetEitr() > 0f;
if (!wants || !airborne || airTime < AirDelay || !canPay)
{
Rising = false;
FlushSpend(__instance);
return;
}
Rising = true;
Rigidbody body = Traverse.Create(__instance).Field("m_body").GetValue<Rigidbody>();
if (body != null)
{
Vector3 velocity = body.linearVelocity;
velocity.y = Mathf.Lerp(velocity.y, AlfarPowerConfig.LevitationRise.Value, 0.25f);
body.linearVelocity = velocity;
}
// Rising resets the fall: the point of the soft fall is that the way down starts at
// the top, and a long climb must not count as a long drop at eitr zero.
Traverse.Create(__instance).Field("m_maxAirAltitude").SetValue(__instance.transform.position.y);
// In the archon form the eitr is already gone and the pool pays for nothing here.
if (!AlfarArchon.Active) owed += cost * Time.fixedDeltaTime;
if (Time.time >= nextSpend) FlushSpend(__instance);
}
}
private static bool JumpHeld()
{
// "Jump" is the keyboard binding only; the pad's button is a separate "JoyJump", read
// the way PlayerController reads it, kept off while a radial menu has the pad.
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)
{
nextSpend = Time.time + SpendInterval;
if (owed <= 0f) return;
AlfarEitr.Spend(player, owed);
owed = 0f;
}
private static void Reset()
{
airTime = 0f;
owed = 0f;
Rising = false;
}
}
}

View file

@ -0,0 +1,108 @@
using System.Collections.Generic;
using Jotunn.Configs;
using Jotunn.Entities;
using Jotunn.Managers;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// The LJOSGARD, the garden of light (Alfar_Progettazione.txt sec. 8.6 and 12): the module of the
/// Nexus that mixes the two mushrooms of the Mistlands into SAP, very slowly.
///
/// It is a clone of the stone furnace with its recipe turned: MAGECAP is the "ore" and JOTUN PUFFS
/// the "fuel", one of each per sap, so mixing the two is exactly what a smelter already does with
/// its two inputs. Being a Smelter it needs no new code to be served: the drones feed it (a
/// Smelter-family station) and carry the sap away, and the refinery (vanilla, sap as fuel and soft
/// tissue as ore) is served by them too. Output falls where a furnace's does.
/// </summary>
public static class AlfarLjosgard
{
public const string PieceName = "AlfarLjosgard";
public const string PieceDisplay = "$rov_piece_alfar_ljosgard_name";
public static void Register()
{
GameObject source = PrefabManager.Cache.GetPrefab<GameObject>("smelter");
ItemDrop magecap = PrefabManager.Cache.GetPrefab<ItemDrop>("MushroomMagecap");
ItemDrop puffs = PrefabManager.Cache.GetPrefab<ItemDrop>("MushroomJotunPuffs");
ItemDrop sap = PrefabManager.Cache.GetPrefab<ItemDrop>("Sap");
if (source == null || magecap == null || puffs == null || sap == null)
{
Jotunn.Logger.LogWarning("[Alfar] The Ljosgard needs the 'smelter' piece and the Magecap, Jotun Puffs and Sap items: not registered.");
return;
}
GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(PieceName, source);
if (prefab == null) return;
// The furnace's heat and its fire: the Ljosgard is cool to the touch (guide 5.1).
AswidBloodRefinery.StripOffensive(prefab, "Ljosgard");
Smelter smelter = prefab.GetComponent<Smelter>();
if (smelter == null)
{
Jotunn.Logger.LogWarning("[Alfar] The cloned smelter has no Smelter component: no Ljosgard.");
return;
}
smelter.m_name = PieceDisplay;
smelter.m_conversion = new List<Smelter.ItemConversion>
{
new Smelter.ItemConversion { m_from = magecap, m_to = sap },
};
smelter.m_fuelItem = puffs;
smelter.m_fuelPerProduct = 1;
smelter.m_maxOre = AlfarNexusConfig.GardCapacity.Value;
smelter.m_maxFuel = AlfarNexusConfig.GardCapacity.Value;
smelter.m_secPerProduct = AlfarNexusConfig.GardSecondsPerSap.Value;
smelter.m_requiresRoof = false;
smelter.m_spawnStack = false;
smelter.m_windmill = null;
AlfarConstructs.Tint(prefab, new Color(0.55f, 0.85f, 0.7f, 1f));
Piece piece = prefab.GetComponent<Piece>();
if (piece == null) { Jotunn.Logger.LogWarning("[Alfar] The cloned smelter has no Piece."); return; }
piece.m_craftingStation = null;
piece.m_name = PieceDisplay;
piece.m_description = "$rov_piece_alfar_ljosgard_desc";
PieceManager.Instance.AddPiece(new CustomPiece(prefab, fixReference: false, new PieceConfig
{
Name = PieceDisplay,
Description = "$rov_piece_alfar_ljosgard_desc",
PieceTable = PieceTables.Hammer,
Category = PieceCategories.Crafting,
Icon = piece.m_icon,
Requirements = new[]
{
new RequirementConfig("Bronze", AlfarNexusConfig.GardBronze.Value, 0, true),
new RequirementConfig("MushroomJotunPuffs", AlfarNexusConfig.GardMushrooms.Value, 0, true),
new RequirementConfig("MushroomMagecap", AlfarNexusConfig.GardMushrooms.Value, 0, true),
},
}));
// One per Ljoskjarne, inside its reach, and only for the Alfar.
PieceDensityLimit.Register(PieceName, AlfarNexusConfig.NexusRadius.Value, 1, "rov_msg_build_limit_alfar_ljosgard");
PieceDensityLimit.RegisterGate(PieceName, (player, position) =>
{
if (!AlfarRace.IsLocalAlfar())
{
if (player != null) player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_alfar_only_alfar"));
return false;
}
if (AlfarNexusBehaviour.Covering(position) == null)
{
if (player != null) player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_alfar_gard_needs_nexus"));
return false;
}
return true;
});
AlfarPieces.Extra.Add(PieceName);
}
}
}

View file

@ -0,0 +1,149 @@
using System.Collections.Generic;
using System.Reflection;
using HarmonyLib;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// Marks a creature or a piece as one of the Alfar's own: a construct, a drone or a tower.
///
/// What the mark does is decided in ONE place, the patches below, instead of editing every attack
/// of every cloned creature (Alfar_Progettazione.txt sec. 8.5 and 16C P4):
/// - everything the marked thing deals becomes LIGHTNING, with the same total; chop and pickaxe
/// are tool damage and are dropped;
/// - it never hurts an ally;
/// - it never hurts a building, a tree or a rock.
/// Intercepting the hit covers melee, projectiles and area attacks alike, whatever the vanilla
/// creature does with its weapons.
/// </summary>
public class AlfarMark : MonoBehaviour
{
/// <summary>"drone", "construct" or "tower": only for logs and the status command.</summary>
public string Role = "";
/// <summary>The attacker's mark, or null when the hit is not from one of ours.</summary>
public static AlfarMark Of(HitData hit)
{
if (hit == null) return null;
Character attacker = hit.GetAttacker();
return attacker != null ? attacker.GetComponent<AlfarMark>() : null;
}
/// <summary>All the damage that can wound a person, moved into lightning. Chop and pickaxe go.</summary>
public static void ConvertToLightning(HitData hit)
{
HitData.DamageTypes d = hit.m_damage;
float total = d.m_damage + d.m_blunt + d.m_slash + d.m_pierce + d.m_fire + d.m_frost +
d.m_poison + d.m_spirit + d.m_lightning;
HitData.DamageTypes converted = default(HitData.DamageTypes);
converted.m_lightning = total;
hit.m_damage = converted;
}
}
/// <summary>The blows of an Alfar creature: lightning only, and never on a friend.</summary>
[HarmonyPatch(typeof(Character), "Damage")]
public static class AlfarMark_CharacterDamage_Patch
{
public static bool Prefix(Character __instance, HitData __0)
{
AlfarMark mark = AlfarMark.Of(__0);
if (mark == null) return true;
Character attacker = __0.GetAttacker();
if (__instance == attacker) return false;
// Nobody on our side is ever hurt by us: players, their tames, the other constructs.
if (!BaseAI.IsEnemy(attacker, __instance)) return false;
AlfarMark.ConvertToLightning(__0);
return true;
}
}
/// <summary>
/// Buildings, trees and rocks take nothing from the Alfar's creatures: the golem that razed its
/// owner's base would be a bug. One prefix on every kind of thing that can be struck.
/// </summary>
[HarmonyPatch]
public static class AlfarMark_StructureDamage_Patch
{
public static IEnumerable<MethodBase> TargetMethods()
{
System.Type[] types =
{
typeof(WearNTear), typeof(Destructible), typeof(MineRock5), typeof(MineRock),
typeof(TreeBase), typeof(TreeLog),
};
foreach (System.Type type in types)
{
MethodBase method = AccessTools.Method(type, "Damage", new[] { typeof(HitData) });
if (method != null) yield return method;
else Jotunn.Logger.LogWarning($"[Alfar] {type.Name}.Damage(HitData) not found: that structure is not protected from the Alfar's creatures.");
}
}
public static bool Prefix(HitData __0)
{
return AlfarMark.Of(__0) == null;
}
}
/// <summary>
/// A shield equal to the creature's health that comes back by itself: 1% of it per second once it
/// has gone five seconds without being hit (design sec. 8.5 and 9.6). Health does NOT come back:
/// the damage to the body is permanent, which is why a construct is rebuilt and not repaired.
///
/// Its own absorption and not SE_Shield: the blow arrives at ApplyDamage, and what is left after
/// the shield is what reaches the health (the same stage the Alfr's own eitr shield uses).
/// </summary>
public class AlfarCreatureShield : MonoBehaviour
{
public float MaxShield;
public float Shield;
public float RegenPerSecondFraction = 0.01f;
public float QuietSeconds = 5f;
private float lastHit = -999f;
private void Awake()
{
if (Shield <= 0f) Shield = MaxShield;
}
private void Update()
{
if (Shield >= MaxShield || Time.time - lastHit < QuietSeconds) return;
Shield = Mathf.Min(MaxShield, Shield + MaxShield * RegenPerSecondFraction * Time.deltaTime);
}
public void Absorb(HitData hit)
{
float total = hit.m_damage.GetTotalDamage();
if (total <= 0f) return;
lastHit = Time.time;
float absorbed = Mathf.Min(Shield, total);
Shield -= absorbed;
HitData.DamageTypes rest = hit.m_damage;
rest.Modify((total - absorbed) / total);
hit.m_damage = rest;
}
[HarmonyPatch(typeof(Character), "ApplyDamage",
new[] { typeof(HitData), typeof(bool), typeof(bool), typeof(HitData.DamageModifier) })]
public static class Alfar_CreatureShield_Patch
{
public static void Prefix(Character __instance, HitData __0)
{
if (__0 == null || __instance is Player) return;
AlfarCreatureShield shield = __instance.GetComponent<AlfarCreatureShield>();
if (shield != null) shield.Absorb(__0);
}
}
}
}

View file

@ -0,0 +1,103 @@
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// GRAFVAETTIR, the mining grenade (Alfar_Progettazione.txt sec. 9.3): unlocked at Eikthyr, thrown
/// like a grenade at a point; five drones dig the precious ores around it for two minutes and
/// vanish. The ore falls where it stands, and nothing else limits it but its cost (eitr, a little
/// stone and flint) and a five minute wait.
///
/// The thrown part is only the spawn; the digging is AlfarMiner on the drones themselves.
/// </summary>
public static class AlfarMiners
{
private static float readyAt;
public static void Tick(Player player)
{
// Nothing to tick per frame: the miners run themselves. Kept so the power loop treats
// every power the same way.
}
public static void Throw(Player player)
{
if (Time.time < readyAt)
{
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;
Vector3 origin = aim.position;
Vector3 direction = aim.forward;
float range = AlfarPowerConfig.GrafRange.Value;
Vector3 point = origin + direction * range;
foreach (RaycastHit hit in Physics.RaycastAll(origin, direction, range, ~0, QueryTriggerInteraction.Ignore))
{
if (hit.collider.GetComponentInParent<Player>() == player) continue;
if (Vector3.Distance(origin, hit.point) < Vector3.Distance(origin, point)) point = hit.point;
}
// The price: a little eitr, a little stone, a little flint.
string stone = SharedName("Stone");
string flint = SharedName("Flint");
int needStone = AlfarPowerConfig.GrafStone.Value;
int needFlint = AlfarPowerConfig.GrafFlint.Value;
float eitr = AlfarPowerConfig.GrafEitr.Value;
Inventory inventory = player.GetInventory();
if (inventory.CountItems(stone, -1, false) < needStone || inventory.CountItems(flint, -1, false) < needFlint)
{
player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_alfar_graf_materials", needStone, needFlint));
return;
}
if (player.GetEitr() < eitr)
{
player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_alfar_no_eitr"));
return;
}
GameObject prefab = ZNetScene.instance != null ? ZNetScene.instance.GetPrefab(AlfarDrones.MinerName) : null;
if (prefab == null)
{
Jotunn.Logger.LogWarning($"[Alfar] No '{AlfarDrones.MinerName}' in ZNetScene: the mining drones cannot be thrown.");
return;
}
inventory.RemoveItem(stone, needStone, -1, false);
inventory.RemoveItem(flint, needFlint, -1, false);
AlfarEitr.Spend(player, eitr);
readyAt = Time.time + AlfarPowerConfig.GrafCooldown.Value;
AlfarStatusEffects.ShowTimer("graf", AlfarPowerConfig.GrafCooldown.Value);
int count = AlfarPowerConfig.GrafCount.Value;
for (int i = 0; i < count; i++)
{
Vector2 offset = Random.insideUnitCircle * 1.5f;
Vector3 where = point + new Vector3(offset.x, 1.5f + i * 0.2f, offset.y);
GameObject spawned = Object.Instantiate(prefab, where, Quaternion.identity);
AlfarMiner miner = spawned.GetComponent<AlfarMiner>();
if (miner != null) miner.Assign(point, AlfarPowerConfig.GrafRadius.Value, AlfarPowerConfig.GrafSeconds.Value);
// Tame at once so nothing flees them and they flee nothing; no anchor, no leash.
MonsterAI ai = spawned.GetComponent<MonsterAI>();
Character character = spawned.GetComponent<Character>();
if (ai != null) ai.MakeTame();
if (character != null) character.SetTamed(true);
}
AlfarFx.Spawn("fx_JotunWitch_LightningBolt_Explosion", point);
Jotunn.Logger.LogInfo($"[Alfar] Grafvaettir thrown: {count} at {point}.");
}
private static string SharedName(string prefabName)
{
GameObject prefab = ObjectDB.instance != null ? ObjectDB.instance.GetItemPrefab(prefabName) : null;
ItemDrop drop = prefab != null ? prefab.GetComponent<ItemDrop>() : null;
return drop != null ? drop.m_itemData.m_shared.m_name : prefabName;
}
}
}

View file

@ -0,0 +1,578 @@
using System.Collections.Generic;
using System.Text;
using HarmonyLib;
using Jotunn.Configs;
using Jotunn.Entities;
using Jotunn.Managers;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// The LJOSKJARNE, the Alfar's Nexus (Alfar_Progettazione.txt sec. 8): the one piece the whole
/// base hangs from. It makes the drones and the constructs, it keeps the crystals, and the towers
/// and the drones only work inside its radius. One per 1.6 km2 like the other races' stations.
///
/// ONE INTERACTION POINT (guide 4.7): E opens the vanilla merchant window with a row per product
/// (AlfarNexusStore), the way the Trol's war totem and the Dvergar's contract bank do. The first
/// version stepped through the products with Shift+E, which gave trouble in other races' tests, and
/// the player asked for the store. The prices are not coins: they come out of the pack, and the
/// row's tooltip lists them with how many exist and how many are allowed.
///
/// Everything is paid from the player's inventory. The crystals the Nexus makes (after the
/// Kristallvigsla) pile up inside it, a beehive's way - slowly, to a cap, and it stops when full
/// until somebody collects - and "collect" moves them to the pack.
/// </summary>
public static class AlfarNexus
{
public const string PieceName = "AlfarNexus";
public const string PieceDisplay = "$rov_piece_alfar_nexus_name";
public static void Register()
{
GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(PieceName, "piece_cartographytable");
if (prefab == null)
{
Jotunn.Logger.LogWarning("[Alfar] Could not clone piece_cartographytable; the Ljoskjarne is not registered.");
return;
}
// The MapTable trap (Butler 4.1): MapTable is Interactable AND Hoverable and takes the E
// key before our Switch sees it. Everything goes except what makes it a building.
foreach (MonoBehaviour behaviour in prefab.GetComponentsInChildren<MonoBehaviour>(true))
{
if (behaviour == null) continue;
if (behaviour is Piece || behaviour is ZNetView || behaviour is WearNTear) continue;
Object.DestroyImmediate(behaviour);
}
// 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>();
nexus.m_switch = prefab.AddComponent<Switch>();
nexus.m_switch.m_name = PieceDisplay;
// A Trader with an empty catalogue: StoreGui needs one to open at all, and the rows are drawn
// by AlfarNexusStore. Disabled and with every list filled, for the reasons the Trol's totem
// spells out (Trader.Update and Start assume an animator and a look-at rig that a nucleus
// does not have, and an unfilled list sends Trader.Interact into a null Say).
Trader trader = prefab.GetComponent<Trader>() ?? prefab.AddComponent<Trader>();
trader.m_name = PieceDisplay;
trader.enabled = false;
trader.m_items = new List<Trader.TradeItem>();
trader.m_useItems = new List<Trader.TraderUseItem>();
trader.m_randomTalk = new List<string>();
trader.m_randomGreets = new List<string>();
trader.m_randomGoodbye = new List<string>();
trader.m_randomStartTrade = new List<string>();
trader.m_randomBuy = new List<string>();
trader.m_randomSell = new List<string>();
trader.m_randomGiveItemNo = new List<string>();
trader.m_randomUseItemAlreadyRecieved = new List<string>();
trader.m_randomTalkConditionals = new List<Trader.ConditionalDialog>();
Sprite icon = (pyramid ? AlfarChests.IconFrom("AlfarNexus_icon.png") : null) ?? BorrowIcon("Eitr") ?? BorrowIcon("SurtlingCore");
Piece piece = prefab.GetComponent<Piece>() ?? prefab.AddComponent<Piece>();
piece.m_craftingStation = null;
piece.m_resources = new Piece.Requirement[0];
piece.m_name = PieceDisplay;
piece.m_canBeRemoved = true;
piece.m_groundPiece = false;
piece.m_groundOnly = false;
piece.m_icon = icon;
Piece template = PrefabManager.Cache.GetPrefab<Piece>("piece_workbench");
if (template != null && template.m_placeEffect != null) piece.m_placeEffect = template.m_placeEffect;
PieceManager.Instance.AddPiece(new CustomPiece(prefab, fixReference: false, new PieceConfig
{
Name = PieceDisplay,
Description = "$rov_piece_alfar_nexus_desc",
PieceTable = PieceTables.Hammer,
Category = PieceCategories.Crafting,
Icon = icon,
Requirements = new[]
{
new RequirementConfig("Bronze", AlfarNexusConfig.NexusBronze.Value, 0, true),
new RequirementConfig("Stone", AlfarNexusConfig.NexusStone.Value, 0, true),
},
}));
PieceDensityLimit.Register(PieceName, PieceDensityLimit.RadiusForArea(AlfarNexusConfig.NexusDensityKm2.Value),
1, "rov_msg_build_limit_alfar_nexus");
PieceDensityLimit.RegisterGate(PieceName, (player, position) =>
{
if (AlfarRace.IsLocalAlfar()) return true;
if (player != null) player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_alfar_only_alfar"));
return false;
});
}
public static Sprite BorrowIcon(string prefabName)
{
ItemDrop drop = PrefabManager.Cache.GetPrefab<ItemDrop>(prefabName);
Sprite[] icons = drop != null && drop.m_itemData != null && drop.m_itemData.m_shared != null
? drop.m_itemData.m_shared.m_icons
: null;
return icons != null && icons.Length > 0 ? icons[0] : null;
}
/// <summary>Teaches the player the Alfar's pieces: a piece registered after the learning pass does not reach its table alone (guide 4.4).</summary>
public static void EnsureKnown(Player player)
{
if (player == null || !AlfarVisuals.IsAlfarPlayer(player)) return;
Traverse traverse = Traverse.Create(player);
foreach (string name in AlfarPieces.AllNames())
{
GameObject prefab = PrefabManager.Instance.GetPrefab(name);
Piece piece = prefab != null ? prefab.GetComponent<Piece>() : null;
if (piece != null) traverse.Method("AddKnownPiece", piece).GetValue();
}
traverse.Method("UpdateAvailablePiecesList").GetValue();
}
}
/// <summary>The names of every piece the Alfar can build, in one place for the lock and for learning.</summary>
public static class AlfarPieces
{
public static readonly List<string> Extra = new List<string>();
public static IEnumerable<string> AllNames()
{
yield return AlfarNexus.PieceName;
foreach (string name in Extra) yield return name;
}
}
[HarmonyPatch(typeof(Player), "OnSpawned")]
public static class AlfarKnownPatch
{
public static void Postfix(Player __instance)
{
if (__instance != Player.m_localPlayer) return;
AlfarNexus.EnsureKnown(__instance);
}
}
public class AlfarNexusBehaviour : MonoBehaviour
{
public Switch m_switch;
public static readonly List<AlfarNexusBehaviour> All = new List<AlfarNexusBehaviour>();
private const string KeySelected = "RoV_alfarSel";
private const string KeyUpgrade = "RoV_alfarUp";
private const string KeyCrystals = "RoV_alfarCr";
private const string KeyCrystalAt = "RoV_alfarCrAt";
public enum Product { Drone = 0, Neistvordr = 1, Eldingvordr = 2, Steinvordr = 3, Upgrade = 4, Collect = 5 }
private static readonly int ProductCount = System.Enum.GetValues(typeof(Product)).Length;
private ZNetView m_nview;
private void Awake()
{
m_nview = GetComponent<ZNetView>();
All.Add(this);
RaisedThrall.RegisterStation(transform);
if (m_switch != null)
{
m_switch.m_onUse = OnUse;
m_switch.m_onHover = Hover;
}
}
private void OnDestroy()
{
All.Remove(this);
RaisedThrall.UnregisterStation(transform);
}
/// <summary>The nearest Ljoskjarne whose radius covers the point, or null.</summary>
public static AlfarNexusBehaviour Covering(Vector3 point)
{
AlfarNexusBehaviour best = null;
float bestDistance = float.MaxValue;
foreach (AlfarNexusBehaviour nexus in All)
{
if (nexus == null) continue;
float distance = Vector3.Distance(nexus.transform.position, point);
if (distance <= AlfarNexusConfig.NexusRadius.Value && distance < bestDistance)
{
best = nexus;
bestDistance = distance;
}
}
return best;
}
// ─── State ───────────────────────────────────────────────────────────
private bool Upgraded => m_nview != null && m_nview.IsValid() && m_nview.GetZDO().GetInt(KeyUpgrade, 0) == 1;
public int Crystals => m_nview != null && m_nview.IsValid() ? m_nview.GetZDO().GetInt(KeyCrystals, 0) : 0;
private Product Selected
{
get
{
int value = m_nview != null && m_nview.IsValid() ? m_nview.GetZDO().GetInt(KeySelected, 0) : 0;
return (Product)Mathf.Clamp(value, 0, ProductCount - 1);
}
}
private bool Available(Product product)
{
bool constructsOpen = Upgraded && BossProgressionManager.GetCurrentProgressionState() >= AlfarNexusConfig.ConstructState;
switch (product)
{
case Product.Drone: return true;
case Product.Neistvordr:
case Product.Eldingvordr:
case Product.Steinvordr: return constructsOpen;
case Product.Upgrade: return !Upgraded;
case Product.Collect: return Upgraded;
}
return false;
}
// ─── Crystals: a beehive's way ───────────────────────────────────────
/// <summary>
/// One crystal per Time Factor beehive-intervals of WORLD time, up to the cap, and nothing while
/// full: the clock restarts when somebody collects, like the honey. Only the owner counts.
/// The beehive's own interval is read, not copied (guide 3.2) - and only the INTERVAL, not its
/// daylight rule: the Alfar have no light mechanic (doc sec. 8.6).
/// </summary>
private void Update()
{
if (m_nview == null || !m_nview.IsValid() || !m_nview.IsOwner() || !Upgraded || ZNet.instance == null) return;
ZDO zdo = m_nview.GetZDO();
int cap = AlfarNexusConfig.CrystalCap.Value;
int stored = zdo.GetInt(KeyCrystals, 0);
double now = ZNet.instance.GetTimeSeconds();
if (stored >= cap) { zdo.Set(KeyCrystalAt, now.ToString("R", System.Globalization.CultureInfo.InvariantCulture)); return; }
string stamp = zdo.GetString(KeyCrystalAt, "");
if (!double.TryParse(stamp, System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out double at))
{
zdo.Set(KeyCrystalAt, now.ToString("R", System.Globalization.CultureInfo.InvariantCulture));
return;
}
float interval = CrystalInterval();
int made = Mathf.FloorToInt((float)((now - at) / interval));
if (made <= 0) return;
stored = Mathf.Min(cap, stored + made);
zdo.Set(KeyCrystals, stored);
zdo.Set(KeyCrystalAt, (at + made * interval).ToString("R", System.Globalization.CultureInfo.InvariantCulture));
}
/// <summary>Seconds per crystal: Time Factor times a vanilla beehive's seconds per honey.</summary>
public static float CrystalInterval()
{
Beehive hive = TrentaConfig.FindVanillaBeehive();
float honey = hive != null && hive.m_secPerUnit > 0f ? hive.m_secPerUnit : 1200f;
return honey * AlfarNexusConfig.CrystalTimeFactor.Value;
}
// ─── Costs ───────────────────────────────────────────────────────────
private struct Cost
{
public string Item;
public int Amount;
public Cost(string item, int amount) { Item = item; Amount = amount; }
}
private static List<Cost> CostOf(Product product)
{
switch (product)
{
case Product.Drone:
return new List<Cost> { new Cost("Bronze", AlfarNexusConfig.DroneBronze.Value) };
case Product.Neistvordr:
return new List<Cost>
{
new Cost("Bronze", AlfarNexusConfig.NeistMetal.Value),
new Cost("Crystal", AlfarNexusConfig.NeistCrystal.Value),
new Cost("Eitr", AlfarNexusConfig.NeistEitr.Value),
};
case Product.Eldingvordr:
return new List<Cost>
{
new Cost("Iron", AlfarNexusConfig.EldingMetal.Value),
new Cost("Crystal", AlfarNexusConfig.EldingCrystal.Value),
new Cost("Eitr", AlfarNexusConfig.EldingEitr.Value),
};
case Product.Steinvordr:
return new List<Cost>
{
new Cost("BlackMetal", AlfarNexusConfig.SteinMetal.Value),
new Cost("Crystal", AlfarNexusConfig.SteinCrystal.Value),
new Cost("Eitr", AlfarNexusConfig.SteinEitr.Value),
};
case Product.Upgrade:
return new List<Cost> { new Cost("Crystal", AlfarNexusConfig.UpgradeCrystals.Value) };
}
return new List<Cost>();
}
private static string SharedName(string prefabName)
{
GameObject prefab = ObjectDB.instance != null ? ObjectDB.instance.GetItemPrefab(prefabName) : null;
ItemDrop drop = prefab != null ? prefab.GetComponent<ItemDrop>() : null;
return drop != null ? drop.m_itemData.m_shared.m_name : prefabName;
}
private static bool CanPay(Player player, List<Cost> costs)
{
foreach (Cost cost in costs)
{
if (cost.Amount <= 0) continue;
if (player.GetInventory().CountItems(SharedName(cost.Item), -1, false) < cost.Amount) return false;
}
return true;
}
private static void Pay(Player player, List<Cost> costs)
{
foreach (Cost cost in costs)
{
if (cost.Amount > 0) player.GetInventory().RemoveItem(SharedName(cost.Item), cost.Amount, -1, false);
}
}
private static string CostText(List<Cost> costs)
{
var parts = new List<string>();
foreach (Cost cost in costs)
{
if (cost.Amount > 0) parts.Add($"{cost.Amount} {Localization.instance.Localize(SharedName(cost.Item))}");
}
return parts.Count == 0 ? "-" : string.Join(", ", parts);
}
// ─── Counts and caps ─────────────────────────────────────────────────
private int AliveOf(Product product)
{
Vector3 anchor = transform.position;
switch (product)
{
case Product.Drone: return AlfarDrones.CountAlive(anchor);
case Product.Neistvordr: return AlfarConstructs.CountAlive(anchor, AlfarConstructs.Neistvordr);
case Product.Eldingvordr: return AlfarConstructs.CountAlive(anchor, AlfarConstructs.Eldingvordr);
case Product.Steinvordr: return AlfarConstructs.CountAlive(anchor, AlfarConstructs.Steinvordr);
}
return 0;
}
private static int CapOf(Product product)
{
switch (product)
{
case Product.Drone: return AlfarNexusConfig.DroneCap.Value;
case Product.Neistvordr: return AlfarNexusConfig.NeistCap.Value;
case Product.Eldingvordr: return AlfarNexusConfig.EldingCap.Value;
case Product.Steinvordr: return AlfarNexusConfig.SteinCap.Value;
}
return int.MaxValue;
}
private static string NameOf(Product product) => ModText.Get("rov_alfar_product_" + product.ToString().ToLowerInvariant());
// ─── Interaction ─────────────────────────────────────────────────────
private string Hover()
{
var sb = new StringBuilder();
sb.AppendLine(Localization.instance.Localize(AlfarNexus.PieceDisplay));
sb.AppendLine($"[<color=yellow><b>$KEY_Use</b></color>] {ModText.Get("rov_alfar_nexus_open")}");
if (Upgraded) sb.AppendLine(ModText.Get("rov_alfar_nexus_crystals", Crystals, AlfarNexusConfig.CrystalCap.Value));
else sb.AppendLine(ModText.Get("rov_alfar_nexus_no_upgrade"));
return Localization.instance.Localize(sb.ToString());
}
private bool OnUse(Switch sw, Humanoid user, ItemDrop.ItemData item)
{
Player player = user as Player;
if (player == null || m_nview == null || !m_nview.IsValid()) return false;
if (!AlfarVisuals.IsAlfarPlayer(player))
{
player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_alfar_only_alfar"));
return item != null;
}
// Holding something is not a way to use the nucleus: it only opens the store.
if (item != null)
{
player.Message(MessageHud.MessageType.Center, "$msg_wontwork");
return true;
}
Trader trader = GetComponent<Trader>();
if (trader == null || StoreGui.instance == null)
{
player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_alfar_nexus_no_store"));
return false;
}
// The store reads the nucleus back out of StoreGui's own m_trader when it repaints.
StoreGui.instance.Show(trader);
return true;
}
// ─── What the store window uses ──────────────────────────────────────
/// <summary>The products on offer right now, in the order the rows are drawn.</summary>
public List<Product> OnOffer()
{
var list = new List<Product>();
foreach (Product product in System.Enum.GetValues(typeof(Product)))
{
if (Available(product)) list.Add(product);
}
return list;
}
/// <summary>Builds a product from the row the player clicked. Every check Build makes still applies.</summary>
public void BuildFromStore(Product product)
{
Player player = Player.m_localPlayer;
if (player == null || m_nview == null || !m_nview.IsValid() || !Available(product)) return;
m_nview.ClaimOwnership();
Build(player, product);
}
/// <summary>The short number on a row: the metal (or the crystals of the upgrade) it costs.</summary>
public static string PriceShort(Product product)
{
foreach (Cost cost in CostOf(product))
{
if (cost.Amount > 0) return cost.Amount.ToString();
}
return "-";
}
/// <summary>The full terms for the row's tooltip: the price, how many exist, how many are allowed.</summary>
public string Terms(Product product)
{
var sb = new StringBuilder();
sb.AppendLine(CostText(CostOf(product)));
int cap = CapOf(product);
if (cap != int.MaxValue) sb.AppendLine(ModText.Get("rov_alfar_store_count", AliveOf(product), cap));
if (product == Product.Collect) sb.AppendLine(ModText.Get("rov_alfar_nexus_crystals", Crystals, AlfarNexusConfig.CrystalCap.Value));
sb.Append(ModText.Get("rov_alfar_store_terms"));
return sb.ToString();
}
public static string ProductName(Product product) => NameOf(product);
private void Build(Player player, Product product)
{
List<Cost> costs = CostOf(product);
if (product == Product.Collect)
{
Collect(player);
return;
}
if (AliveOf(product) >= CapOf(product))
{
player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_alfar_nexus_cap"));
return;
}
if (!CanPay(player, costs))
{
player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_alfar_nexus_cannot_pay", CostText(costs)));
return;
}
bool done;
switch (product)
{
case Product.Drone: done = AlfarDrones.Spawn(transform.position); break;
case Product.Neistvordr: done = AlfarConstructs.Spawn(transform.position, AlfarConstructs.Neistvordr); break;
case Product.Eldingvordr: done = AlfarConstructs.Spawn(transform.position, AlfarConstructs.Eldingvordr); break;
case Product.Steinvordr: done = AlfarConstructs.Spawn(transform.position, AlfarConstructs.Steinvordr); break;
case Product.Upgrade: done = true; break;
default: done = false; break;
}
if (!done) return;
Pay(player, costs);
if (product == Product.Upgrade)
{
ZDO zdo = m_nview.GetZDO();
zdo.Set(KeyUpgrade, 1);
zdo.Set(KeyCrystalAt, ZNet.instance.GetTimeSeconds().ToString("R", System.Globalization.CultureInfo.InvariantCulture));
player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_alfar_nexus_upgraded"));
}
else
{
player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_alfar_nexus_built", NameOf(product)));
}
}
private void Collect(Player player)
{
int stored = Crystals;
if (stored <= 0)
{
player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_alfar_nexus_no_crystals"));
return;
}
GameObject prefab = ObjectDB.instance != null ? ObjectDB.instance.GetItemPrefab("Crystal") : null;
if (prefab == null) return;
// Whatever fits goes in the pack; the rest stays in the Nexus.
int taken = 0;
for (int i = 0; i < stored; i++)
{
if (!player.GetInventory().CanAddItem(prefab, 1)) break;
if (!player.GetInventory().AddItem(prefab, 1)) break;
taken++;
}
if (taken > 0)
{
ZDO zdo = m_nview.GetZDO();
zdo.Set(KeyCrystals, stored - taken);
// Collecting restarts the clock, like emptying a hive.
zdo.Set(KeyCrystalAt, ZNet.instance.GetTimeSeconds().ToString("R", System.Globalization.CultureInfo.InvariantCulture));
}
player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_alfar_nexus_collected", taken));
}
/// <summary>Crystals a drone may carry away from the Nexus, and the call that does it (used by the drone's work).</summary>
public int TakeCrystals(int wanted)
{
if (m_nview == null || !m_nview.IsValid() || !m_nview.IsOwner()) return 0;
int stored = Crystals;
int taken = Mathf.Min(stored, wanted);
if (taken <= 0) return 0;
ZDO zdo = m_nview.GetZDO();
zdo.Set(KeyCrystals, stored - taken);
zdo.Set(KeyCrystalAt, ZNet.instance.GetTimeSeconds().ToString("R", System.Globalization.CultureInfo.InvariantCulture));
return taken;
}
}
}

View file

@ -0,0 +1,149 @@
using BepInEx.Configuration;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// The numbers of the Alfar's base: the Nexus, its drones, the constructs, the towers and the
/// crystals (Alfar_Progettazione.txt sec. 8, 9 and 19). All starting values, all to be corrected
/// in play, none in the logic files.
/// </summary>
public static class AlfarNexusConfig
{
// The progression state the constructs open at (BossProgressionManager: 6 = Yagluth down).
public const int ConstructState = 6;
// ─── The Nexus ───────────────────────────────────────────────────────
public static ConfigEntry<float> NexusRadius;
public static ConfigEntry<float> NexusDensityKm2;
public static ConfigEntry<int> NexusBronze;
public static ConfigEntry<int> NexusStone;
// ─── Drones ──────────────────────────────────────────────────────────
public static ConfigEntry<int> DroneBronze;
public static ConfigEntry<int> DroneCap;
public static ConfigEntry<float> DroneHealth;
public static ConfigEntry<float> DroneZapDamage;
public static ConfigEntry<float> DroneZapInterval;
// ─── Mining drones ───────────────────────────────────────────────────
public static ConfigEntry<string> MinerDeposits;
public static ConfigEntry<float> MinerDamage;
public static ConfigEntry<string> WildPickables;
// ─── Constructs ──────────────────────────────────────────────────────
public static ConfigEntry<int> NeistMetal;
public static ConfigEntry<int> NeistCrystal;
public static ConfigEntry<int> NeistEitr;
public static ConfigEntry<int> NeistCap;
public static ConfigEntry<int> EldingMetal;
public static ConfigEntry<int> EldingCrystal;
public static ConfigEntry<int> EldingEitr;
public static ConfigEntry<int> EldingCap;
public static ConfigEntry<int> SteinMetal;
public static ConfigEntry<int> SteinCrystal;
public static ConfigEntry<int> SteinEitr;
public static ConfigEntry<int> SteinCap;
public static ConfigEntry<float> ConstructLeash;
public static ConfigEntry<float> ConstructAlertRange;
public static ConfigEntry<float> WitherSeconds;
public static ConfigEntry<float> SphereDamage;
public static ConfigEntry<float> SphereIntervalSeconds;
public static ConfigEntry<float> SphereRange;
// ─── Crystals ────────────────────────────────────────────────────────
public static ConfigEntry<int> UpgradeCrystals;
public static ConfigEntry<int> CrystalCap;
public static ConfigEntry<float> CrystalTimeFactor;
// ─── Towers ──────────────────────────────────────────────────────────
public static ConfigEntry<int> TowerBronze;
public static ConfigEntry<int> TowerCrystal;
public static ConfigEntry<float> TowerHealthFactor;
public static ConfigEntry<float> TowerDamage;
public static ConfigEntry<float> TowerScale;
// ─── Ljosgard (sap) and chests ───────────────────────────────────────
public static ConfigEntry<int> GardBronze;
public static ConfigEntry<int> GardMushrooms;
public static ConfigEntry<float> GardSecondsPerSap;
public static ConfigEntry<int> GardCapacity;
public static ConfigEntry<int> ChestEyes;
public static void Bind(ConfigFile config)
{
const string nexus = "Alfar - Nexus";
NexusRadius = config.Bind(nexus, "Radius", 40f, new ConfigDescription("Metres around a Ljoskjarne where its drones work and its towers run.", new AcceptableValueRange<float>(10f, 150f)));
NexusDensityKm2 = config.Bind(nexus, "Density Km2", 1.6f, new ConfigDescription("At most one Ljoskjarne per this many square kilometres.", new AcceptableValueRange<float>(0.1f, 20f)));
NexusBronze = config.Bind(nexus, "Bronze Cost", 40, new ConfigDescription("Bronze to build a Ljoskjarne.", new AcceptableValueRange<int>(0, 500)));
NexusStone = config.Bind(nexus, "Stone Cost", 30, new ConfigDescription("Stone to build a Ljoskjarne.", new AcceptableValueRange<int>(0, 500)));
const string drone = "Alfar - Drones";
DroneBronze = config.Bind(drone, "Bronze Cost", 8, new ConfigDescription("Bronze for each Ljosvaettir.", new AcceptableValueRange<int>(0, 200)));
DroneCap = config.Bind(drone, "Cap Per Nexus", 6, new ConfigDescription("Most drones one Ljoskjarne keeps.", new AcceptableValueRange<int>(0, 50)));
DroneHealth = config.Bind(drone, "Health", 25f, new ConfigDescription("A drone's health and shield (a Deathsquito has 10).", new AcceptableValueRange<float>(1f, 1000f)));
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)));
// 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."));
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)));
WildPickables = config.Bind(drone, "Wild Plants Harvested", "Pickable_Mushroom,Pickable_Dandelion,Pickable_Thistle,RaspberryBush,BlueberryBush,CloudberryBush",
new ConfigDescription("Comma separated parts of prefab names of WILD plants the drones pick without replanting (mushrooms, berry bushes, flowers). Trees are never touched. Cultivated crops are always replanted."));
const string construct = "Alfar - Constructs";
NeistMetal = config.Bind(construct, "Neistvordr Bronze", 20, new ConfigDescription("Bronze for a Neistvordr.", new AcceptableValueRange<int>(0, 500)));
NeistCrystal = config.Bind(construct, "Neistvordr Crystal", 3, new ConfigDescription("Crystals for a Neistvordr.", new AcceptableValueRange<int>(0, 50)));
NeistEitr = config.Bind(construct, "Neistvordr Refined Eitr", 3, new ConfigDescription("Refined eitr for a Neistvordr.", new AcceptableValueRange<int>(0, 50)));
NeistCap = config.Bind(construct, "Neistvordr Cap", 4, new ConfigDescription("Most Neistvordr one Ljoskjarne keeps.", new AcceptableValueRange<int>(0, 50)));
EldingMetal = config.Bind(construct, "Eldingvordr Iron", 20, new ConfigDescription("Iron for an Eldingvordr.", new AcceptableValueRange<int>(0, 500)));
EldingCrystal = config.Bind(construct, "Eldingvordr Crystal", 5, new ConfigDescription("Crystals for an Eldingvordr.", new AcceptableValueRange<int>(0, 50)));
EldingEitr = config.Bind(construct, "Eldingvordr Refined Eitr", 4, new ConfigDescription("Refined eitr for an Eldingvordr.", new AcceptableValueRange<int>(0, 50)));
EldingCap = config.Bind(construct, "Eldingvordr Cap", 4, new ConfigDescription("Most Eldingvordr one Ljoskjarne keeps.", new AcceptableValueRange<int>(0, 50)));
SteinMetal = config.Bind(construct, "Steinvordr Black Metal", 20, new ConfigDescription("Black metal for a Steinvordr.", new AcceptableValueRange<int>(0, 500)));
SteinCrystal = config.Bind(construct, "Steinvordr Crystal", 8, new ConfigDescription("Crystals for a Steinvordr.", new AcceptableValueRange<int>(0, 50)));
SteinEitr = config.Bind(construct, "Steinvordr Refined Eitr", 6, new ConfigDescription("Refined eitr for a Steinvordr.", new AcceptableValueRange<int>(0, 50)));
SteinCap = config.Bind(construct, "Steinvordr Cap", 1, new ConfigDescription("Most Steinvordr one Ljoskjarne keeps.", new AcceptableValueRange<int>(0, 50)));
ConstructLeash = config.Bind(construct, "Leash Range", 12f, new ConfigDescription("How far a construct wanders from its Ljoskjarne when not following.", new AcceptableValueRange<float>(2f, 80f)));
ConstructAlertRange = config.Bind(construct, "Alert Range", 25f, new ConfigDescription("How far a construct notices and chases enemies.", new AcceptableValueRange<float>(5f, 100f)));
WitherSeconds = config.Bind(construct, "Wither Seconds", 60f, new ConfigDescription("How long creatures last after their Ljoskjarne falls.", new AcceptableValueRange<float>(0f, 600f)));
SphereDamage = config.Bind(construct, "Sphere Damage", 80f, new ConfigDescription("Lightning damage of the Eldingvordr's sphere.", new AcceptableValueRange<float>(1f, 1000f)));
SphereIntervalSeconds = config.Bind(construct, "Sphere Interval", 8f, new ConfigDescription("Seconds between the Eldingvordr's shots.", new AcceptableValueRange<float>(0.5f, 60f)));
SphereRange = config.Bind(construct, "Sphere Range", 30f, new ConfigDescription("How far the Eldingvordr shoots.", new AcceptableValueRange<float>(5f, 80f)));
const string crystal = "Alfar - Crystals";
UpgradeCrystals = config.Bind(crystal, "Upgrade Cost", 20, new ConfigDescription("Crystals the player must find for the Kristallvigsla.", new AcceptableValueRange<int>(0, 200)));
CrystalCap = config.Bind(crystal, "Stored Cap", 20, new ConfigDescription("Most crystals the Ljoskjarne holds before it stops making them.", new AcceptableValueRange<int>(1, 200)));
CrystalTimeFactor = config.Bind(crystal, "Time Factor", 2f, new ConfigDescription("A crystal takes this many times a vanilla beehive's time for one honey.", new AcceptableValueRange<float>(0.1f, 20f)));
const string tower = "Alfar - Towers";
TowerBronze = config.Bind(tower, "Bronze Cost", 25, new ConfigDescription("Bronze for a Prismavard.", new AcceptableValueRange<int>(0, 500)));
TowerCrystal = config.Bind(tower, "Crystal Cost", 2, new ConfigDescription("Crystals for a Prismavard.", new AcceptableValueRange<int>(0, 50)));
TowerHealthFactor = config.Bind(tower, "Health Factor", 0.5f, new ConfigDescription("A Prismavard's health against the charred ballista's 400.", new AcceptableValueRange<float>(0.05f, 3f)));
TowerDamage = config.Bind(tower, "Bolt Damage", 40f, new ConfigDescription("Lightning damage of a Prismavard's bolt.", new AcceptableValueRange<float>(1f, 1000f)));
TowerScale = config.Bind(tower, "Scale", 0.6f, new ConfigDescription("Size of a Prismavard against the charred ballista.", new AcceptableValueRange<float>(0.2f, 2f)));
const string gard = "Alfar - Ljosgard";
GardBronze = config.Bind(gard, "Bronze Cost", 40, new ConfigDescription("Bronze for a Ljosgard.", new AcceptableValueRange<int>(0, 500)));
GardMushrooms = config.Bind(gard, "Mushrooms Cost", 10, new ConfigDescription("Jotun Puffs AND Magecap, this many of each, to build a Ljosgard.", new AcceptableValueRange<int>(0, 100)));
GardSecondsPerSap = config.Bind(gard, "Seconds Per Sap", 600f, new ConfigDescription("Seconds to turn one Jotun Puffs and one Magecap into a Sap.", new AcceptableValueRange<float>(10f, 7200f)));
GardCapacity = config.Bind(gard, "Sap Capacity", 10, new ConfigDescription("Sap the Ljosgard holds before it stops.", new AcceptableValueRange<int>(1, 200)));
ChestEyes = config.Bind(gard, "Chest Greydwarf Eyes", 3, new ConfigDescription("Greydwarf eyes in the price of the entry chest and the wood chest.", new AcceptableValueRange<int>(0, 50)));
}
}
}

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

@ -0,0 +1,171 @@
using System.Collections.Generic;
using HarmonyLib;
using TMPro;
using UnityEngine;
using UnityEngine.UI;
namespace RacesOfValheim
{
/// <summary>
/// The Ljoskjarne's window: the merchant's own store with a column of products in it - the drone,
/// the three constructs, the crystal upgrade, and the crystals to collect.
///
/// It is the Trol war totem's window (TrolTotemStore) cloned for another trader, and for the same
/// reasons: same three patch points (Awake to build, FillList to repaint, Hide to clear), same trick
/// of instantiating StoreGui.m_listElement for the rows. The empty-catalogue guard that keeps vanilla
/// FillList from throwing is already on every trader with no wares (StoreGuiEmptyCatalogueGuardPatch),
/// so this one needs none of its own.
///
/// What is different from the totem: a row's price is a number out of the pack and not coins, so the
/// short figure on the row is the metal or the crystals, and the tooltip carries the whole price.
/// </summary>
public static class AlfarNexusStore
{
private static RectTransform _list;
private static readonly List<GameObject> _rows = new List<GameObject>();
public static AlfarNexusBehaviour ActiveNexus(StoreGui gui)
{
Trader trader = FactionMerchantRuntime.GetActiveTrader(gui);
return trader != null ? trader.GetComponent<AlfarNexusBehaviour>() : null;
}
// ─── build ───────────────────────────────────────────────────────────
public static void Create(StoreGui gui)
{
if (gui == null || gui.m_listRoot == null || _list != null) return;
GameObject clone = Object.Instantiate(gui.m_listRoot.gameObject, gui.m_listRoot.parent);
clone.name = "AlfarProductList";
_list = clone.GetComponent<RectTransform>();
_list.anchoredPosition = gui.m_listRoot.anchoredPosition;
// The clone carries whatever rows the vanilla list held at Awake: it starts empty.
foreach (Transform child in _list) Object.Destroy(child.gameObject);
_list.gameObject.SetActive(false);
}
public static void Clear()
{
foreach (GameObject row in _rows) if (row != null) Object.Destroy(row);
_rows.Clear();
if (_list != null) _list.gameObject.SetActive(false);
}
// ─── fill ────────────────────────────────────────────────────────────
public static void Refresh(StoreGui gui)
{
Clear();
AlfarNexusBehaviour nexus = ActiveNexus(gui);
if (nexus == null) return; // an ordinary merchant: not ours
if (_list == null)
{
Jotunn.Logger.LogWarning("[Alfar] The Ljoskjarne's column was never built (did the patch on StoreGui.Awake fail?).");
return;
}
_list.gameObject.SetActive(true);
int row = 0;
foreach (AlfarNexusBehaviour.Product product in nexus.OnOffer())
{
BuildRow(gui, nexus, product, row++);
}
float baseSize = Traverse.Create(gui).Field("m_itemlistBaseSize").GetValue<float>();
_list.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, Mathf.Max(baseSize, row * gui.m_itemSpacing));
}
private static string IconOf(AlfarNexusBehaviour.Product product)
{
switch (product)
{
case AlfarNexusBehaviour.Product.Drone: return "TrophyDeathsquito";
case AlfarNexusBehaviour.Product.Neistvordr: return "TrophySurtling";
case AlfarNexusBehaviour.Product.Eldingvordr: return "TrophyAbomination";
case AlfarNexusBehaviour.Product.Steinvordr: return "TrophySGolem";
default: return "Crystal";
}
}
private static void BuildRow(StoreGui gui, AlfarNexusBehaviour nexus, AlfarNexusBehaviour.Product product, int rowIndex)
{
GameObject element = Object.Instantiate(gui.m_listElement, _list);
element.SetActive(true);
RectTransform rt = (RectTransform)element.transform;
float offset = (_list.rect.width - rt.rect.width) / 2f;
rt.anchoredPosition = new Vector2(offset, rowIndex * -gui.m_itemSpacing - offset);
Sprite icon = Icon(IconOf(product));
Image iconImage = element.transform.Find("icon").GetComponent<Image>();
if (icon != null) iconImage.sprite = icon;
string name = AlfarNexusBehaviour.ProductName(product);
element.transform.Find("name").GetComponent<TMP_Text>().text = Localization.instance.Localize(name);
TMP_Text price = FindDescendant<TMP_Text>(element.transform, "price");
if (price != null) price.text = AlfarNexusBehaviour.PriceShort(product);
// The coin that sits beside the number on a vanilla row is the wrong picture here.
foreach (Image image in element.GetComponentsInChildren<Image>(true))
{
if (image != null && image.gameObject.name.ToLowerInvariant().Contains("coin")) image.gameObject.SetActive(false);
}
UITooltip tooltip = element.GetComponent<UITooltip>();
if (tooltip != null) tooltip.Set(Localization.instance.Localize(name), nexus.Terms(product), gui.m_tooltipAnchor, default(Vector2));
AlfarNexusBehaviour.Product chosen = product;
element.GetComponent<Button>().onClick.AddListener(() =>
{
nexus.BuildFromStore(chosen);
Traverse.Create(gui).Method("FillList").GetValue(); // repaints the column
});
_rows.Add(element);
}
// ─── helpers ─────────────────────────────────────────────────────────
private static Sprite Icon(string prefabName)
{
ItemDrop drop = Jotunn.Managers.PrefabManager.Cache.GetPrefab<ItemDrop>(prefabName);
Sprite[] icons = drop != null && drop.m_itemData != null && drop.m_itemData.m_shared != null
? drop.m_itemData.m_shared.m_icons
: null;
return icons != null && icons.Length > 0 ? icons[0] : null;
}
private static T FindDescendant<T>(Transform root, string childName) where T : Component
{
foreach (T candidate in root.GetComponentsInChildren<T>(true))
{
if (candidate.gameObject.name == childName) return candidate;
}
return null;
}
}
[HarmonyPatch(typeof(StoreGui), "Awake")]
public static class AlfarNexusStoreSetupPatch
{
public static void Postfix(StoreGui __instance) => AlfarNexusStore.Create(__instance);
}
[HarmonyPatch(typeof(StoreGui), "FillList")]
public static class AlfarNexusStoreFillPatch
{
public static void Postfix(StoreGui __instance) => AlfarNexusStore.Refresh(__instance);
}
[HarmonyPatch(typeof(StoreGui), "Hide")]
public static class AlfarNexusStoreHidePatch
{
public static void Postfix() => AlfarNexusStore.Clear();
}
}

View file

@ -0,0 +1,180 @@
using System.Collections.Generic;
using HarmonyLib;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// The hooks that keep an Alfr looking like one. Only the look so far; the shield, the death
/// timer and the powers add their own patches as they are written.
/// </summary>
public static class AlfarPatches
{
/// <summary>
/// The only thing that actually colours a player.
///
/// SetSkinColor followed by UpdateColors does nothing, because UpdateColors is what REBUILDS
/// the body material from Valheim's own values and throws any earlier write away
/// (DvergarPatches documents the dead end). Writing _SkinColor here, after it has run, is the
/// only order that survives.
/// </summary>
[HarmonyPatch(typeof(VisEquipment), "UpdateColors")]
public static class Alfar_UpdateColors_Patch
{
public static void Postfix(VisEquipment __instance)
{
if (__instance == null || __instance.m_bodyModel == null) return;
Player player = __instance.GetComponent<Player>();
if (player == null || !AlfarVisuals.IsAlfarPlayer(player)) return;
AlfarVisuals.ApplyGreyTexture(__instance, true);
Material material = __instance.m_bodyModel.material;
if (material != null && material.HasProperty("_SkinColor"))
{
material.SetColor("_SkinColor", AlfarVisuals.SkinFor(player));
}
}
}
/// <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>
/// 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,
/// scale and eyes, twice a second, for as long as the preview exists. The existing menu hook only
/// pushes ONE colour refresh and knows nothing of eyes or texture.
/// </summary>
public class AlfarPreviewDriver : MonoBehaviour
{
private Player player;
private float next;
private void Awake() { player = GetComponent<Player>(); }
private void Update()
{
if (player == null || Time.time < next) return;
next = Time.time + 0.5f;
bool isAlfar = AlfarVisuals.IsAlfarPlayer(player);
AlfarVisuals.ApplyScale(player, isAlfar);
AlfarVisuals.ApplyEyes(player);
if (isAlfar) AlfarVisuals.ApplyHairless(player);
AlfarVisuals.SyncSkin(player, isAlfar);
}
}
public static void AttachPreviewDriver(FejdStartup instance)
{
Player preview = instance.GetType()
.GetMethod("GetPreviewPlayer",
System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic |
System.Reflection.BindingFlags.Public)
?.Invoke(instance, null) as Player;
if (preview != null && preview.GetComponent<AlfarPreviewDriver>() == null)
{
preview.gameObject.AddComponent<AlfarPreviewDriver>();
}
}
[HarmonyPatch(typeof(FejdStartup), "SetupCharacterPreview")]
public static class Alfar_Preview_Setup_Patch
{
[HarmonyPriority(Priority.Last)]
public static void Postfix(FejdStartup __instance) => AttachPreviewDriver(__instance);
}
[HarmonyPatch(typeof(FejdStartup), "SetSelectedProfile")]
public static class Alfar_Preview_Profile_Patch
{
[HarmonyPriority(Priority.Last)]
public static void Postfix(FejdStartup __instance) => AttachPreviewDriver(__instance);
}
/// <summary>
/// Scale every frame, the cosmetics on a throttle.
///
/// On Player.Update because that is the one place body scale survives: the Trol's postfix
/// forces every other player's visual back to 1 on the same frame, so a scale written
/// anywhere else is simply overwritten. RaceScale keeps the two from undoing each other.
/// This runs for every player in range, not just the local one, so other clients see an
/// Alfr as one.
/// </summary>
[HarmonyPatch(typeof(Player), "Update")]
public static class Alfar_PlayerUpdate_Patch
{
private static readonly Dictionary<Player, float> nextCosmeticPass = new Dictionary<Player, float>();
private const float CosmeticInterval = 0.5f;
public static void Postfix(Player __instance)
{
if (__instance == null) return;
bool isAlfar = AlfarVisuals.IsAlfarPlayer(__instance);
AlfarVisuals.ApplyScale(__instance, isAlfar);
// The passive carrier belongs to the local body only; status effects are re-added
// because they do not survive a reload or a death.
if (__instance == Player.m_localPlayer)
{
if (isAlfar && !__instance.IsDead())
{
AlfarStatusEffects.Ensure(__instance);
AlfarPowers.Tick(__instance);
}
else
{
AlfarStatusEffects.Remove(__instance);
if (AlfarArchon.Active) AlfarArchon.ForceClear(__instance);
}
}
if (!nextCosmeticPass.TryGetValue(__instance, out float due) || Time.time >= due)
{
nextCosmeticPass[__instance] = Time.time + CosmeticInterval;
// Unconditional, like the other races': the eyes have to be able to remove
// themselves from whoever stops being an Alfr, and they cannot do that from
// behind an `if (isAlfar)`.
AlfarVisuals.ApplyEyes(__instance);
AlfarVisuals.ApplyArchonGlow(__instance);
if (isAlfar) AlfarVisuals.ApplyHairless(__instance);
AlfarVisuals.SyncSkin(__instance, isAlfar);
}
}
}
}
}

View file

@ -0,0 +1,170 @@
using BepInEx.Configuration;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// The numbers and the keys of the Alfar's powers (Alfar_Progettazione.txt sec. 13 and 19.6).
/// Every value is a STARTING value to be corrected in play. Nothing numeric lives in the logic.
///
/// Keys follow the mod's habit: letters the other races also use (G, H, I, J, K, O, U), because a
/// character has exactly one race, so the same letter never means two things at once.
/// </summary>
public static class AlfarPowerConfig
{
// Progression states a power unlocks at (BossProgressionManager: 2 Eikthyr ... 8 Fader).
public const int SkridState = 2;
public const int GrafvaettirState = 2;
public const int UtsogState = 3;
public const int KallState = 4;
public const int LjosstormState = 5;
public const int GeisliState = 6;
public const int KyrrState = 7;
public const int SameiningState = 8;
// ─── Keys ────────────────────────────────────────────────────────────
public static ConfigEntry<KeyboardShortcut> SkridKey;
public static ConfigEntry<KeyboardShortcut> GrafvaettirKey;
public static ConfigEntry<KeyboardShortcut> KallKey;
public static ConfigEntry<KeyboardShortcut> LjosstormKey;
public static ConfigEntry<KeyboardShortcut> GeisliKey;
public static ConfigEntry<KeyboardShortcut> KyrrKey;
public static ConfigEntry<KeyboardShortcut> SameiningKey;
// ─── Skrid: the blink ────────────────────────────────────────────────
public static ConfigEntry<float> SkridDistance;
public static ConfigEntry<float> SkridCost;
public static ConfigEntry<float> SkridCooldown;
// ─── Utsog: damage dealt comes back as eitr ──────────────────────────
public static ConfigEntry<float> UtsogPercent;
// ─── Kall: telekinesis ───────────────────────────────────────────────
public static ConfigEntry<float> KallRadius;
public static ConfigEntry<float> KallSpeed;
public static ConfigEntry<float> KallCost;
public static ConfigEntry<float> KallCooldown;
// ─── Ljosstorm: the psionic storm ────────────────────────────────────
public static ConfigEntry<float> StormRange;
public static ConfigEntry<float> StormRadius;
public static ConfigEntry<float> StormSeconds;
public static ConfigEntry<float> StormDps;
public static ConfigEntry<float> StormCost;
public static ConfigEntry<float> StormCooldown;
// ─── Geisli: the beam ────────────────────────────────────────────────
public static ConfigEntry<float> BeamRange;
public static ConfigEntry<float> BeamDps;
public static ConfigEntry<float> BeamCostPerSecond;
public static ConfigEntry<float> BeamMaxSeconds;
public static ConfigEntry<float> BeamCooldown;
// ─── Kyrr: stasis ────────────────────────────────────────────────────
public static ConfigEntry<float> StasisRange;
public static ConfigEntry<float> StasisSeconds;
public static ConfigEntry<float> StasisBossSeconds;
public static ConfigEntry<float> StasisCost;
public static ConfigEntry<float> StasisCooldown;
// ─── Sameining: the archon ───────────────────────────────────────────
public static ConfigEntry<float> ArchonThreshold;
public static ConfigEntry<float> ArchonSeconds;
public static ConfigEntry<float> ArchonScale;
public static ConfigEntry<float> ArchonSpeedBonus;
public static ConfigEntry<float> ArchonPoolPerEitr;
public static ConfigEntry<float> ArchonPulseRadius;
public static ConfigEntry<float> ArchonPulseDamage;
public static ConfigEntry<float> ArchonPulseInterval;
public static ConfigEntry<float> ArchonFreePowerCooldown;
public static ConfigEntry<Color> ArchonColor;
// ─── Grafvaettir: the mining grenade ─────────────────────────────────
public static ConfigEntry<float> GrafRange;
public static ConfigEntry<float> GrafRadius;
public static ConfigEntry<float> GrafSeconds;
public static ConfigEntry<int> GrafCount;
public static ConfigEntry<float> GrafEitr;
public static ConfigEntry<int> GrafStone;
public static ConfigEntry<int> GrafFlint;
public static ConfigEntry<float> GrafCooldown;
// ─── Levitation ──────────────────────────────────────────────────────
public static ConfigEntry<float> LevitationRise;
public static ConfigEntry<float> LevitationCostPerSecond;
public static void Bind(ConfigFile config)
{
const string keys = "Alfar - Keybinds";
SkridKey = config.Bind(keys, "Skrid (Blink)", new KeyboardShortcut(KeyCode.G));
GrafvaettirKey = config.Bind(keys, "Grafvaettir (Mining Drones)", new KeyboardShortcut(KeyCode.H));
KallKey = config.Bind(keys, "Kall (Telekinesis)", new KeyboardShortcut(KeyCode.J));
LjosstormKey = config.Bind(keys, "Ljosstorm (Psionic Storm)", new KeyboardShortcut(KeyCode.K));
GeisliKey = config.Bind(keys, "Geisli (Beam, hold)", new KeyboardShortcut(KeyCode.O));
KyrrKey = config.Bind(keys, "Kyrr (Stasis)", new KeyboardShortcut(KeyCode.U));
SameiningKey = config.Bind(keys, "Sameining (Archon)", new KeyboardShortcut(KeyCode.I));
const string skrid = "Alfar - Skrid";
SkridDistance = config.Bind(skrid, "Distance", 8f, new ConfigDescription("Blink length in metres.", new AcceptableValueRange<float>(1f, 30f)));
SkridCost = config.Bind(skrid, "Eitr Cost", 10f, new ConfigDescription("Eitr spent per blink.", new AcceptableValueRange<float>(0f, 200f)));
SkridCooldown = config.Bind(skrid, "Cooldown", 3f, new ConfigDescription("Seconds between blinks.", new AcceptableValueRange<float>(0f, 120f)));
const string utsog = "Alfar - Utsog";
UtsogPercent = config.Bind(utsog, "Return Percent", 15f, new ConfigDescription("Percent of the damage you deal that comes back as eitr.", new AcceptableValueRange<float>(0f, 100f)));
const string kall = "Alfar - Kall";
KallRadius = config.Bind(kall, "Radius", 15f, new ConfigDescription("Metres around you whose dropped items are pulled in.", new AcceptableValueRange<float>(1f, 60f)));
KallSpeed = config.Bind(kall, "Pull Speed", 12f, new ConfigDescription("Speed items fly toward you, in metres per second.", new AcceptableValueRange<float>(1f, 40f)));
KallCost = config.Bind(kall, "Eitr Cost", 5f, new ConfigDescription("Eitr spent per pull.", new AcceptableValueRange<float>(0f, 200f)));
KallCooldown = config.Bind(kall, "Cooldown", 2f, new ConfigDescription("Seconds between pulls.", new AcceptableValueRange<float>(0f, 120f)));
const string storm = "Alfar - Ljosstorm";
StormRange = config.Bind(storm, "Range", 30f, new ConfigDescription("How far you can place the storm.", new AcceptableValueRange<float>(5f, 80f)));
StormRadius = config.Bind(storm, "Radius", 6f, new ConfigDescription("Radius of the storm in metres.", new AcceptableValueRange<float>(1f, 30f)));
StormSeconds = config.Bind(storm, "Duration", 6f, new ConfigDescription("Seconds the storm lasts.", new AcceptableValueRange<float>(1f, 60f)));
StormDps = config.Bind(storm, "Damage Per Second", 20f, new ConfigDescription("Lightning damage per second to each enemy inside.", new AcceptableValueRange<float>(1f, 500f)));
StormCost = config.Bind(storm, "Eitr Cost", 40f, new ConfigDescription("Eitr spent per cast.", new AcceptableValueRange<float>(0f, 400f)));
StormCooldown = config.Bind(storm, "Cooldown", 20f, new ConfigDescription("Seconds between casts.", new AcceptableValueRange<float>(0f, 300f)));
const string beam = "Alfar - Geisli";
BeamRange = config.Bind(beam, "Range", 30f, new ConfigDescription("Beam length in metres.", new AcceptableValueRange<float>(5f, 80f)));
BeamDps = config.Bind(beam, "Damage Per Second", 35f, new ConfigDescription("Lightning damage per second to the target.", new AcceptableValueRange<float>(1f, 500f)));
BeamCostPerSecond = config.Bind(beam, "Eitr Per Second", 8f, new ConfigDescription("Eitr burned each second the beam is held.", new AcceptableValueRange<float>(0f, 100f)));
BeamMaxSeconds = config.Bind(beam, "Max Continuous Seconds", 8f, new ConfigDescription("The beam cuts off after this long.", new AcceptableValueRange<float>(1f, 60f)));
BeamCooldown = config.Bind(beam, "Cooldown After Release", 2f, new ConfigDescription("Seconds before the beam can start again.", new AcceptableValueRange<float>(0f, 60f)));
const string stasis = "Alfar - Kyrr";
StasisRange = config.Bind(stasis, "Range", 25f, new ConfigDescription("How far the stasis reaches.", new AcceptableValueRange<float>(5f, 80f)));
StasisSeconds = config.Bind(stasis, "Seconds", 4f, new ConfigDescription("How long an ordinary enemy is held.", new AcceptableValueRange<float>(0.5f, 30f)));
StasisBossSeconds = config.Bind(stasis, "Boss Seconds", 1.5f, new ConfigDescription("How long a boss is held.", new AcceptableValueRange<float>(0.5f, 30f)));
StasisCost = config.Bind(stasis, "Eitr Cost", 50f, new ConfigDescription("Eitr spent per cast.", new AcceptableValueRange<float>(0f, 400f)));
StasisCooldown = config.Bind(stasis, "Cooldown", 45f, new ConfigDescription("Seconds between casts.", new AcceptableValueRange<float>(0f, 600f)));
const string archon = "Alfar - Sameining";
ArchonThreshold = config.Bind(archon, "Activation Threshold", 0.75f, new ConfigDescription("Fraction of the maximum eitr needed to begin. All of it is spent.", new AcceptableValueRange<float>(0f, 1f)));
ArchonSeconds = config.Bind(archon, "Duration", 180f, new ConfigDescription("Seconds the form lasts at most.", new AcceptableValueRange<float>(5f, 900f)));
ArchonScale = config.Bind(archon, "Scale", 1.5f, new ConfigDescription("Body size multiplier in the form.", new AcceptableValueRange<float>(1f, 3f)));
ArchonSpeedBonus = config.Bind(archon, "Speed Bonus", 0.2f, new ConfigDescription("Movement speed bonus in the form (0.2 = +20%).", new AcceptableValueRange<float>(0f, 1f)));
ArchonPoolPerEitr = config.Bind(archon, "Pool Per Eitr", 3f, new ConfigDescription("Points of protection per point of eitr spent to enter.", new AcceptableValueRange<float>(0.1f, 20f)));
ArchonPulseRadius = config.Bind(archon, "Pulse Radius", 4f, new ConfigDescription("Radius of the psionic pulse around you.", new AcceptableValueRange<float>(1f, 20f)));
ArchonPulseDamage = config.Bind(archon, "Pulse Damage", 60f, new ConfigDescription("Lightning damage of each pulse.", new AcceptableValueRange<float>(1f, 1000f)));
ArchonPulseInterval = config.Bind(archon, "Pulse Interval", 1f, new ConfigDescription("Seconds between pulses.", new AcceptableValueRange<float>(0.2f, 10f)));
ArchonFreePowerCooldown = config.Bind(archon, "Free Power Cooldown", 5f, new ConfigDescription("In the form, Ljosstorm and Geisli cost no eitr but wait this long.", new AcceptableValueRange<float>(0f, 60f)));
ArchonColor = config.Bind(archon, "Glow Color", new Color(0.55f, 0.85f, 1f, 1f), new ConfigDescription("Skin and light colour while in the form."));
const string graf = "Alfar - Grafvaettir";
GrafRange = config.Bind(graf, "Throw Range", 25f, new ConfigDescription("How far the drones can be thrown.", new AcceptableValueRange<float>(5f, 80f)));
GrafRadius = config.Bind(graf, "Dig Radius", 12f, new ConfigDescription("Radius around the landing point where they dig.", new AcceptableValueRange<float>(2f, 60f)));
GrafSeconds = config.Bind(graf, "Duration", 120f, new ConfigDescription("Seconds the drones dig before vanishing.", new AcceptableValueRange<float>(5f, 900f)));
GrafCount = config.Bind(graf, "Drones Per Throw", 5, new ConfigDescription("How many mining drones one throw makes.", new AcceptableValueRange<int>(1, 30)));
GrafEitr = config.Bind(graf, "Eitr Cost", 25f, new ConfigDescription("Eitr spent per throw.", new AcceptableValueRange<float>(0f, 400f)));
GrafStone = config.Bind(graf, "Stone Cost", 10, new ConfigDescription("Stone spent per throw.", new AcceptableValueRange<int>(0, 200)));
GrafFlint = config.Bind(graf, "Flint Cost", 5, new ConfigDescription("Flint spent per throw.", new AcceptableValueRange<int>(0, 200)));
GrafCooldown = config.Bind(graf, "Cooldown", 300f, new ConfigDescription("Seconds between throws; keep it well above the duration or they are permanent.", new AcceptableValueRange<float>(0f, 3600f)));
const string lev = "Alfar - Levitation";
LevitationRise = config.Bind(lev, "Rise Speed", 2f, new ConfigDescription("Climb speed (m/s) while the jump key is held in the air.", new AcceptableValueRange<float>(0.2f, 10f)));
LevitationCostPerSecond = config.Bind(lev, "Eitr Per Second", 2f, new ConfigDescription("Eitr burned each second of levitation.", new AcceptableValueRange<float>(0f, 50f)));
}
}
}

View file

@ -0,0 +1,687 @@
using System.Collections.Generic;
using System.Linq;
using HarmonyLib;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// The Alfar's powers (Alfar_Progettazione.txt sec. 13): caster tools, one per boss from Eikthyr.
///
/// Skrid Eikthyr blink
/// Grafvaettir Eikthyr mining drones thrown like a grenade (AlfarMiners)
/// Utsog Elder damage dealt returns as eitr (passive, below)
/// Kall Bonemass telekinesis
/// Ljosstorm Moder psionic storm on the ground
/// Geisli Yagluth continuous beam (hold the key)
/// Kyrr Queen stasis
/// Sameining Fader the archon (AlfarArchon)
///
/// Every power costs eitr from the SAME pool as the shield, which is the whole tension of the race
/// (doc sec. 4.4). Eitr is spent through AlfarEitr.Spend so the vanilla regeneration delay arms.
/// </summary>
public static class AlfarPowers
{
private static readonly Dictionary<string, float> cooldownUntil = new Dictionary<string, float>();
public static void ResetCooldowns(Player player)
{
cooldownUntil.Clear();
StopBeam();
AlfarArchon.ForceClear(player);
foreach (string id in AlfarStatusEffects.TimerIds) AlfarStatusEffects.ClearTimer(id);
}
private static bool Ready(string id) => !cooldownUntil.TryGetValue(id, out float until) || Time.time >= until;
private static void StartCooldown(string id, float seconds)
{
cooldownUntil[id] = Time.time + seconds;
AlfarStatusEffects.ShowTimer(id, seconds);
}
private static bool Unlocked(int need) => BossProgressionManager.GetCurrentProgressionState() >= need;
/// <summary>
/// The eitr a power costs: nothing for Ljosstorm and Geisli inside the archon form.
/// </summary>
private static float CostOf(float cost, bool freeInArchon) =>
freeInArchon && AlfarArchon.Active ? 0f : cost;
private static float CooldownOf(float cooldown, bool freeInArchon) =>
freeInArchon && AlfarArchon.Active ? AlfarArchon.FreePowerCooldown : cooldown;
/// <summary>Pays for a power, or says so and returns false.</summary>
private static bool Pay(Player player, float cost)
{
if (cost <= 0f) return true;
if (player.GetEitr() < cost)
{
player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_alfar_no_eitr"));
return false;
}
AlfarEitr.Spend(player, cost);
return true;
}
// ─── The loop ────────────────────────────────────────────────────────
/// <summary>Called every frame for the LOCAL Alfr, from the Player.Update postfix.</summary>
public static void Tick(Player player)
{
AlfarArchon.Tick(player);
AlfarHeimkall.SyncIcon(player);
AlfarMiners.Tick(player);
TickBeam(player);
if (!RaceInput.Allowed || player.IsDead()) return;
if (Unlocked(AlfarPowerConfig.SkridState) && AlfarPowerConfig.SkridKey.Value.IsDownIgnoringHeldKeys()) Skrid(player);
if (Unlocked(AlfarPowerConfig.GrafvaettirState) && AlfarPowerConfig.GrafvaettirKey.Value.IsDownIgnoringHeldKeys()) AlfarMiners.Throw(player);
if (Unlocked(AlfarPowerConfig.KallState) && AlfarPowerConfig.KallKey.Value.IsDownIgnoringHeldKeys()) Kall(player);
if (Unlocked(AlfarPowerConfig.LjosstormState) && AlfarPowerConfig.LjosstormKey.Value.IsDownIgnoringHeldKeys()) Ljosstorm(player);
if (Unlocked(AlfarPowerConfig.KyrrState) && AlfarPowerConfig.KyrrKey.Value.IsDownIgnoringHeldKeys()) Kyrr(player);
if (Unlocked(AlfarPowerConfig.SameiningState) && AlfarPowerConfig.SameiningKey.Value.IsDownIgnoringHeldKeys()) AlfarArchon.TryActivate(player);
}
// ─── Aim ─────────────────────────────────────────────────────────────
private static Transform AimTransform(Player player)
{
return GameCamera.instance != null ? GameCamera.instance.transform : player.transform;
}
/// <summary>
/// What the crosshair is on: the first thing the ray hits that is not the Alfr, with the
/// character under it if there is one. Triggers are ignored. With nothing hit, the point is at
/// the end of the range.
/// </summary>
private static bool Aim(Player player, float range, out Vector3 point, out Character target)
{
Transform aim = AimTransform(player);
Vector3 origin = aim.position;
Vector3 direction = aim.forward;
target = null;
point = origin + direction * range;
RaycastHit[] hits = Physics.RaycastAll(origin, direction, range, ~0, QueryTriggerInteraction.Ignore);
System.Array.Sort(hits, (a, b) => a.distance.CompareTo(b.distance));
foreach (RaycastHit hit in hits)
{
if (hit.collider == null) continue;
if (hit.collider.GetComponentInParent<Player>() == player) continue;
point = hit.point;
target = hit.collider.GetComponentInParent<Character>();
return true;
}
return false;
}
private static bool IsHostile(Player player, Character other)
{
return other != null && other != player && !other.IsDead() && !other.IsTamed() &&
BaseAI.IsEnemy(player, other);
}
// ─── Damage ──────────────────────────────────────────────────────────
/// <summary>
/// One lightning strike on a character. Not blockable and not dodgeable: a power that can be
/// blocked is a weapon, and these are not.
/// </summary>
public static void Strike(Player attacker, Character target, float lightning, Vector3 point)
{
if (target == null || lightning <= 0f) return;
HitData hit = new HitData();
hit.m_damage.m_lightning = lightning;
hit.m_point = point;
hit.m_dir = (target.transform.position - attacker.transform.position).normalized;
hit.m_dodgeable = false;
hit.m_blockable = false;
hit.m_hitType = HitData.HitType.PlayerHit;
hit.SetAttacker(attacker);
target.Damage(hit);
}
/// <summary>A pulse of lightning on every hostile creature within a radius of the Alfr.</summary>
/// <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))
{
if (!IsHostile(player, character)) continue;
Strike(player, character, damage, character.GetCenterPoint());
struck = true;
}
return struck;
}
private static IEnumerable<Character> CharactersIn(Vector3 center, float radius)
{
var seen = new HashSet<Character>();
foreach (Collider collider in Physics.OverlapSphere(center, radius, ~0, QueryTriggerInteraction.Ignore))
{
Character character = collider.GetComponentInParent<Character>();
if (character != null && seen.Add(character)) yield return character;
}
}
// ─── Skrid: blink ────────────────────────────────────────────────────
private static void Skrid(Player player)
{
if (!Ready("skrid")) return;
Transform aim = AimTransform(player);
Vector3 origin = player.transform.position + Vector3.up * 1.0f;
Vector3 direction = aim.forward;
float distance = AlfarPowerConfig.SkridDistance.Value;
// Stop short of whatever is in the way, so the blink never ends inside a wall.
Vector3 destination = origin + direction * distance;
if (NearestHit(player, origin, direction, distance, out RaycastHit wall))
{
destination = wall.point - direction * 0.6f;
}
// 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;
if (ZoneSystem.instance != null)
{
// 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 (!Pay(player, AlfarPowerConfig.SkridCost.Value)) return;
Teleport(player, destination);
StartCooldown("skrid", AlfarPowerConfig.SkridCooldown.Value);
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>
/// 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.
/// </summary>
private static void Teleport(Player player, Vector3 destination)
{
Rigidbody body = Traverse.Create(player).Field("m_body").GetValue<Rigidbody>();
player.transform.position = destination;
if (body != null)
{
body.position = destination;
body.linearVelocity = Vector3.zero;
}
Traverse.Create(player).Field("m_maxAirAltitude").SetValue(destination.y);
}
// ─── Utsog: damage dealt returns as eitr ─────────────────────────────
/// <summary>
/// After a blow lands on something that is not a player: if the local Alfr struck it, a share
/// of the damage comes back as eitr. Runs only where the victim is owned, which is here for
/// anything this client owns (singleplayer and the host in practice): a monster owned by
/// another client feeds no eitr. Known limit, doc sec. 17.
/// </summary>
[HarmonyPatch(typeof(Character), "ApplyDamage",
new[] { typeof(HitData), typeof(bool), typeof(bool), typeof(HitData.DamageModifier) })]
public static class Alfar_Utsog_Patch
{
public static void Postfix(Character __instance, HitData __0)
{
if (__instance == null || __0 == null || __instance is Player) return;
Player local = Player.m_localPlayer;
if (local == null || __0.GetAttacker() != local) return;
if (!AlfarVisuals.IsAlfarPlayer(local) || !Unlocked(AlfarPowerConfig.UtsogState)) return;
if (__instance.IsTamed()) return;
float returned = __0.GetTotalDamage() * AlfarPowerConfig.UtsogPercent.Value / 100f;
if (returned > 0f) local.AddEitr(returned);
}
}
// ─── Kall: telekinesis ───────────────────────────────────────────────
private static void Kall(Player player)
{
if (!Ready("kall")) return;
if (!Pay(player, AlfarPowerConfig.KallCost.Value)) return;
Vector3 target = player.GetCenterPoint();
int pulled = 0;
var seen = new HashSet<ItemDrop>();
foreach (Collider collider in Physics.OverlapSphere(player.transform.position, AlfarPowerConfig.KallRadius.Value,
~0, QueryTriggerInteraction.Ignore))
{
ItemDrop item = collider.GetComponentInParent<ItemDrop>();
if (item == null || !seen.Add(item)) continue;
Rigidbody body = item.GetComponent<Rigidbody>();
ZNetView nview = item.GetComponent<ZNetView>();
if (body == null || nview == null || !nview.IsValid()) continue;
// The item's physics belong to whoever owns it; take it so the pull is not undone.
nview.ClaimOwnership();
Vector3 direction = (target - item.transform.position).normalized;
body.WakeUp();
body.linearVelocity = direction * AlfarPowerConfig.KallSpeed.Value;
pulled++;
}
StartCooldown("kall", AlfarPowerConfig.KallCooldown.Value);
Jotunn.Logger.LogInfo($"[Alfar] Kall pulled {pulled} item(s).");
}
// ─── Ljosstorm: the psionic storm ────────────────────────────────────
private static void Ljosstorm(Player player)
{
if (!Ready("storm")) return;
float cost = CostOf(AlfarPowerConfig.StormCost.Value, true);
if (!Pay(player, cost)) return;
Aim(player, AlfarPowerConfig.StormRange.Value, out Vector3 point, out Character _);
GameObject storm = new GameObject("AlfarStorm");
storm.transform.position = point;
AlfarStormZone zone = storm.AddComponent<AlfarStormZone>();
zone.Owner = player;
zone.Radius = AlfarPowerConfig.StormRadius.Value;
zone.Seconds = AlfarPowerConfig.StormSeconds.Value;
zone.DamagePerSecond = AlfarPowerConfig.StormDps.Value;
StartCooldown("storm", CooldownOf(AlfarPowerConfig.StormCooldown.Value, true));
}
// ─── 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 readonly List<LineRenderer> beamArcs = new List<LineRenderer>();
private static GameObject beamFx;
private static bool beamOn;
private static float beamStarted;
private static float beamNextTick;
private static float beamNextAnim;
private static float beamNextArcs;
/// <summary>
/// The beam leaves the RIGHT HAND, raised with the palm open: the borrowed "gpower" gesture (the
/// arms-raised cast the other races use too, with the real Guardian Power swallowed for a moment),
/// repeated while the key is held so the arm stays up. A quiet electric hum comes from the
/// vanilla lightning staff's charge effect hung on the hand, turned down, and a few jagged arcs
/// flicker round the line.
/// </summary>
private static void TickBeam(Player player)
{
bool wanted = RaceInput.Allowed && !player.IsDead() && Unlocked(AlfarPowerConfig.GeisliState) &&
(AlfarPowerConfig.GeisliKey.Value.IsPressedIgnoringHeldKeys() || PadBeamHeld(player));
if (!wanted)
{
if (beamOn) StopBeam(startCooldown: true);
return;
}
if (!beamOn)
{
if (!Ready("beam")) return;
if (player.GetEitr() <= 0f && !AlfarArchon.Active) { Pay(player, 1f); return; }
beamOn = true;
beamStarted = Time.time;
beamNextTick = Time.time;
beamNextAnim = 0f;
StartBeamFx(player);
}
if (Time.time - beamStarted > AlfarPowerConfig.BeamMaxSeconds.Value) { StopBeam(startCooldown: true); return; }
if (Time.time >= beamNextAnim)
{
beamNextAnim = Time.time + 1.6f;
RaiseHand(player);
}
Transform aim = AimTransform(player);
Transform hand = AlfarVisuals.RightHand(player);
Vector3 start = hand != null ? hand.position : player.GetEyePoint() + Vector3.down * 0.35f + aim.forward * 0.5f;
Aim(player, AlfarPowerConfig.BeamRange.Value, out Vector3 end, out Character target);
DrawBeam(start, end);
if (Time.time < beamNextTick) return;
const float tick = 0.2f;
beamNextTick = Time.time + tick;
float cost = CostOf(AlfarPowerConfig.BeamCostPerSecond.Value * tick, true);
if (cost > 0f)
{
if (player.GetEitr() < cost) { StopBeam(startCooldown: true); return; }
AlfarEitr.Spend(player, cost);
}
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)
{
ZSyncAnimation animation = player.GetComponent<ZSyncAnimation>();
if (animation == null) return;
RaceInput.SuppressGuardianPowerBriefly(3f);
animation.SetTrigger("gpower");
}
private static void StartBeamFx(Player player)
{
Transform hand = AlfarVisuals.RightHand(player);
if (hand == null || ZNetScene.instance == null) return;
GameObject prefab = ZNetScene.instance.GetPrefab("fx_lightningstaff_charge");
if (prefab == null) return;
beamFx = Object.Instantiate(prefab, hand.position, hand.rotation, hand);
// Not too loud: a hum, not a thunderclap.
foreach (AudioSource source in beamFx.GetComponentsInChildren<AudioSource>(true))
{
source.volume *= 0.35f;
}
}
private static LineRenderer NewLine(string name, float width)
{
GameObject go = new GameObject(name);
LineRenderer line = go.AddComponent<LineRenderer>();
line.material = new Material(Shader.Find("Sprites/Default"));
line.startWidth = width;
line.endWidth = width * 0.5f;
line.useWorldSpace = true;
return line;
}
private static void DrawBeam(Vector3 start, Vector3 end)
{
Color color = AlfarPowerConfig.ArchonColor.Value;
if (beamLine == null)
{
beamLine = NewLine("AlfarBeam", 0.12f);
beamLine.positionCount = 2;
}
beamLine.startColor = color;
beamLine.endColor = new Color(color.r, color.g, color.b, 0.4f);
beamLine.SetPosition(0, start);
beamLine.SetPosition(1, end);
// A few jagged arcs round the line, redrawn about twenty times a second.
if (beamArcs.Count == 0)
{
for (int i = 0; i < 3; i++)
{
LineRenderer arc = NewLine("AlfarBeamArc" + i, 0.04f);
arc.positionCount = 9;
beamArcs.Add(arc);
}
}
if (Time.time >= beamNextArcs)
{
beamNextArcs = Time.time + 0.05f;
Vector3 direction = end - start;
foreach (LineRenderer arc in beamArcs)
{
arc.startColor = new Color(1f, 1f, 1f, 0.9f);
arc.endColor = new Color(color.r, color.g, color.b, 0.2f);
for (int i = 0; i < arc.positionCount; i++)
{
float t = i / (float)(arc.positionCount - 1);
Vector3 point = start + direction * t;
if (i > 0 && i < arc.positionCount - 1) point += Random.insideUnitSphere * 0.35f;
arc.SetPosition(i, point);
}
}
}
}
private static void StopBeam(bool startCooldown = false)
{
if (beamLine != null) { Object.Destroy(beamLine.gameObject); beamLine = null; }
foreach (LineRenderer arc in beamArcs) if (arc != null) Object.Destroy(arc.gameObject);
beamArcs.Clear();
if (beamFx != null) { Object.Destroy(beamFx); beamFx = null; }
if (beamOn && startCooldown) StartCooldown("beam", CooldownOf(AlfarPowerConfig.BeamCooldown.Value, true));
beamOn = false;
}
// ─── Kyrr: stasis ────────────────────────────────────────────────────
private static void Kyrr(Player player)
{
if (!Ready("kyrr")) return;
Transform aim = AimTransform(player);
Character best = null;
float bestDistance = float.MaxValue;
foreach (RaycastHit hit in Physics.SphereCastAll(aim.position, 0.8f, aim.forward,
AlfarPowerConfig.StasisRange.Value, ~0, QueryTriggerInteraction.Ignore))
{
Character character = hit.collider.GetComponentInParent<Character>();
if (!IsHostile(player, character) || hit.distance >= bestDistance) continue;
best = character;
bestDistance = hit.distance;
}
if (best == null) return;
if (!Pay(player, AlfarPowerConfig.StasisCost.Value)) return;
float seconds = best.IsBoss() ? AlfarPowerConfig.StasisBossSeconds.Value : AlfarPowerConfig.StasisSeconds.Value;
AlfarStasis.Apply(best, seconds);
StartCooldown("kyrr", AlfarPowerConfig.StasisCooldown.Value);
AlfarFx.Spawn("fx_JotunWitch_LightningBolt_Explosion", best.GetCenterPoint());
}
}
/// <summary>A storm on the ground that strikes every hostile creature inside it, twice a second.</summary>
public class AlfarStormZone : MonoBehaviour
{
public Player Owner;
public float Radius;
public float Seconds;
public float DamagePerSecond;
private float born;
private float nextTick;
private Light glow;
private void Start()
{
born = Time.time;
glow = gameObject.AddComponent<Light>();
glow.color = AlfarPowerConfig.ArchonColor.Value;
glow.range = Radius * 1.5f;
glow.intensity = 2f;
}
private void Update()
{
if (Owner == null || Time.time - born >= Seconds) { Destroy(gameObject); return; }
if (Time.time < nextTick) return;
const float tick = 0.5f;
nextTick = Time.time + tick;
bool struck = false;
foreach (Collider collider in Physics.OverlapSphere(transform.position, Radius, ~0, QueryTriggerInteraction.Ignore))
{
Character character = collider.GetComponentInParent<Character>();
if (character == null || character == Owner || character.IsDead() || character.IsTamed()) continue;
if (!BaseAI.IsEnemy(Owner, character)) continue;
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;
AlfarFx.Spawn("fx_JotunWitch_LightningBolt_Explosion", transform.position + new Vector3(offset.x, 0f, offset.y));
}
}
/// <summary>
/// Holds a creature still and untouchable for a few seconds (Kyrr). Frozen means the AI is off, the
/// animator stopped and the body locked; untouchable is the prefix at the bottom, which cancels
/// every blow on a creature that carries this. Everything is put back when it runs out.
/// </summary>
public class AlfarStasis : MonoBehaviour
{
private float until;
private Animator animator;
private float animatorSpeed;
private MonoBehaviour ai;
private Rigidbody body;
private RigidbodyConstraints constraints;
public static void Apply(Character target, float seconds)
{
AlfarStasis existing = target.GetComponent<AlfarStasis>();
if (existing != null) { existing.until = Time.time + seconds; return; }
ZNetView nview = target.GetComponent<ZNetView>();
if (nview != null && nview.IsValid()) nview.ClaimOwnership();
AlfarStasis stasis = target.gameObject.AddComponent<AlfarStasis>();
stasis.until = Time.time + seconds;
}
private void Awake()
{
animator = GetComponentInChildren<Animator>();
if (animator != null) { animatorSpeed = animator.speed; animator.speed = 0f; }
ai = GetComponent<BaseAI>();
if (ai != null) ai.enabled = false;
body = GetComponent<Rigidbody>();
if (body != null)
{
constraints = body.constraints;
body.linearVelocity = Vector3.zero;
body.constraints = RigidbodyConstraints.FreezeAll;
}
}
private void Update()
{
if (Time.time >= until) Destroy(this);
}
private void OnDestroy()
{
if (animator != null) animator.speed = animatorSpeed;
if (ai != null) ai.enabled = true;
if (body != null) body.constraints = constraints;
}
[HarmonyPatch(typeof(Character), "ApplyDamage",
new[] { typeof(HitData), typeof(bool), typeof(bool), typeof(HitData.DamageModifier) })]
public static class Alfar_Stasis_Patch
{
public static void Prefix(Character __instance, HitData __0)
{
if (__0 != null && __instance != null && __instance.GetComponent<AlfarStasis>() != null)
{
__0.m_damage = default(HitData.DamageTypes);
}
}
}
}
/// <summary>Spawns a vanilla effect prefab by name, and says nothing if the name is not there.</summary>
public static class AlfarFx
{
public static void Spawn(string prefabName, Vector3 position)
{
if (ZNetScene.instance == null) return;
GameObject prefab = ZNetScene.instance.GetPrefab(prefabName);
if (prefab == null) return;
Object.Instantiate(prefab, position, Quaternion.identity);
}
}
}

View file

@ -0,0 +1,434 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using Jotunn.Entities;
using Jotunn.Managers;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// The Alfar probe: reads the live prefabs the design leans on, because Mono.Cecil only shows
/// field NAMES and never the values baked into a prefab (Alfar_Progettazione.txt, sec. 16B V11).
///
/// Nothing here instantiates a prefab, so no AI or Awake logic runs. Everything goes to the
/// BepInEx log under an [AlfarProbe] prefix; the console only says it finished.
///
/// alfarprobe EVERYTHING: every default target, the lightning table, and who
/// references Softtissue and Crystal
/// alfarprobe <prefab> just that prefab (names are the manifest's, case sensitive)
/// alfarprobe lightning just the table of how every creature takes lightning damage
///
/// WHAT EACH TARGET ANSWERS, so the log can be read against the design rather than around it:
/// Deathsquito are the legs and stinger separate objects (they are meant to be removed),
/// where the buzz lives, which materials the eyes and wings use
/// Surtling whether it is particles and lights or textures (decides how to recolour it)
/// StoneGolem attacks, area attacks, hp: the numbers the construct copies
/// Abomination whether it is a Humanoid with item attacks, and its hp and damage
/// piece_Charred_Balista whether it is a Piece with WearNTear and a Turret, and what it
/// needs to be built (sec. 8.6: it may only be the ballista a camp spawns)
/// ancient_skull what it is (MineRock5, Destructible...) and what it drops (soft tissue?)
/// eitrrefinery its conversion list: what really turns sap into refined eitr
/// Beehive m_secPerUnit and m_maxHoney, which the crystal timer is defined from
/// Dverger staffs the projectile the Abomination's sphere will be cloned from
/// </summary>
public class AlfarProbeCommand : ConsoleCommand
{
public override string Name => "alfarprobe";
public override string Help =>
"[DEBUG] alfarprobe [prefab|lightning] - logs the live prefab data the Alfar design needs " +
"(hierarchy, components, drops, attacks, lightning resistances) to the BepInEx log.";
private static readonly string[] DefaultTargets =
{
"Deathsquito", "Deathsquito_sting",
"Surtling", "StoneGolem", "Abomination",
"piece_Charred_Balista", "ancient_skull", "giant_skull",
"eitrrefinery", "Beehive", "piece_beehive", "piece_sapcollector",
"giant_skull_frac", "rock4_forest_frac", "giant_brain", "giant_brain_frac",
"DvergerStaffFire_fireball_projectile", "DvergerStaffIce_projectile",
"Pickable_Mushroom_Magecap", "Pickable_Mushroom_JotunPuffs", "sapling_magecap",
};
// Components whose public fields are worth printing in full. Anything else is only listed by name.
private static readonly HashSet<string> Interesting = new HashSet<string>
{
"Character", "Humanoid", "MonsterAI", "BaseAI", "CharacterDrop", "Tameable",
"Piece", "WearNTear", "Turret", "ZNetView",
"Destructible", "MineRock5", "MineRock", "DropOnDestroyed", "Pickable", "Plant",
"Beehive", "Smelter", "CookingStation", "Fermenter", "Container",
"Projectile", "Aoe", "ItemDrop", "ZSyncAnimation", "CharacterAnimEvent",
};
// For these the private fields are printed as well, because the interesting data (default
// items, attack timings) is private. Only fields declared on the type itself, to skip noise.
private static readonly HashSet<string> WithPrivate = new HashSet<string>
{
"Humanoid", "MonsterAI", "BaseAI", "Character",
};
public override void Run(string[] args)
{
if (args.Length > 0 && args[0].ToLower() == "lightning")
{
DumpLightningTable();
Console.instance.Print("[AlfarProbe] lightning table written to the BepInEx log.");
return;
}
if (args.Length > 1 && args[0].ToLower() == "whodrops")
{
WhoDrops(args[1]);
Console.instance.Print($"[AlfarProbe] whodrops {args[1]} written to the BepInEx log.");
return;
}
string[] targets = args.Length > 0 ? args : DefaultTargets;
foreach (string name in targets)
{
DumpPrefab(name);
}
if (args.Length == 0)
{
// The no-argument form is the WHOLE probe in one go: every default prefab, the
// lightning table, and who references soft tissue and crystals (the two drops the
// design could not place from the prefabs alone).
DumpLightningTable();
WhoDrops("Softtissue");
WhoDrops("Crystal");
}
Console.instance.Print($"[AlfarProbe] done, {targets.Length} prefab(s). Read BepInEx/LogOutput.log.");
}
private static void Log(string line) => Jotunn.Logger.LogInfo("[AlfarProbe] " + line);
private static GameObject Find(string name)
{
GameObject found = ZNetScene.instance != null ? ZNetScene.instance.GetPrefab(name) : null;
if (found != null) return found;
return PrefabManager.Cache.GetPrefab<GameObject>(name);
}
// ─── One prefab ──────────────────────────────────────────────────────
private static void DumpPrefab(string name)
{
GameObject prefab = Find(name);
Log($"==================== {name} ====================");
if (prefab == null)
{
Log("NOT FOUND by ZNetScene or the prefab cache. Check the spelling against the manifest, " +
"and note an _res/ prefab may not be registered at all (Alfar doc sec. 8.6).");
return;
}
Log($"root '{prefab.name}' scale={prefab.transform.localScale}");
DumpHierarchy(prefab.transform, "", 0);
foreach (Component component in prefab.GetComponentsInChildren<Component>(true))
{
if (component == null) continue;
string typeName = component.GetType().Name;
if (!Interesting.Contains(typeName)) continue;
Log($"--- {typeName} on '{PathOf(component.transform, prefab.transform)}'");
DumpFields(component, WithPrivate.Contains(typeName));
}
DumpDefaultItems(prefab);
}
private static void DumpHierarchy(Transform node, string indent, int depth)
{
if (depth > 9) { Log($"{indent}... (deeper than 9 levels)"); return; }
var parts = new List<string>();
foreach (Component c in node.GetComponents<Component>())
{
if (c == null || c is Transform) continue;
parts.Add(c.GetType().Name);
}
string pos = node.localPosition == Vector3.zero ? "" : $" pos={node.localPosition}";
string scale = node.localScale == Vector3.one ? "" : $" scale={node.localScale}";
Log($"{indent}{node.name}{(node.gameObject.activeSelf ? "" : " [INACTIVE]")}{pos}{scale}" +
(parts.Count > 0 ? " <" + string.Join(", ", parts) + ">" : ""));
Renderer renderer = node.GetComponent<Renderer>();
if (renderer != null)
{
foreach (Material m in renderer.sharedMaterials)
{
if (m == null) continue;
Log($"{indent} material '{m.name}' shader='{(m.shader != null ? m.shader.name : "null")}'" +
$" color={(m.HasProperty("_Color") ? m.GetColor("_Color").ToString() : "-")}" +
$" emission={(m.HasProperty("_EmissionColor") ? m.GetColor("_EmissionColor").ToString() : "-")}");
}
}
foreach (Transform child in node)
{
DumpHierarchy(child, indent + " ", depth + 1);
}
}
// ─── Generic field reader ────────────────────────────────────────────
private static void DumpFields(object target, bool includePrivate)
{
Type type = target.GetType();
// The first probe printed only the fields DECLARED on Humanoid and MonsterAI and so never
// showed Character's (hp, faction, flying, damage modifiers) or BaseAI's. Walk up the
// chain and print the public fields of every base too, private ones only on the leaf.
for (Type level = type; level != null && level != typeof(MonoBehaviour) && level != typeof(Behaviour); level = level.BaseType)
{
bool leaf = level == type;
BindingFlags flags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly;
if (includePrivate && leaf) flags |= BindingFlags.NonPublic;
if (!leaf) Log($" -- inherited from {level.Name}");
DumpLevel(target, level, flags);
}
}
private static void DumpLevel(object target, Type type, BindingFlags flags)
{
foreach (FieldInfo field in type.GetFields(flags))
{
// Runtime state, not prefab data: nothing there to learn and lots of it.
if (field.FieldType == typeof(ZNetView) && field.IsPrivate) continue;
object value;
try { value = field.GetValue(target); }
catch (Exception) { continue; }
string text = Describe(value, 0);
if (text == null) continue;
Log($" {field.Name} = {text}");
}
}
/// <summary>
/// A short readable form of a field value, or null when it is not worth a line (null, empty,
/// zero). Objects are shown by name only: this is a probe, not a serialiser.
/// </summary>
private static string Describe(object value, int depth)
{
if (value == null) return null;
if (value is UnityEngine.Object unityObject)
{
return unityObject == null ? null : $"'{unityObject.name}' ({unityObject.GetType().Name})";
}
if (value is string s) return s.Length == 0 ? null : "'" + s + "'";
Type t = value.GetType();
if (t.IsEnum) return value.ToString();
if (t.IsPrimitive)
{
if (value is bool b) return b ? "true" : "false";
string number = value.ToString();
return number == "0" ? null : number;
}
if (value is Vector2 || value is Vector3 || value is Color || value is Quaternion || value is Vector4)
{
return value.ToString();
}
if (depth >= 2) return $"({t.Name})";
if (value is IList list)
{
if (list.Count == 0) return null;
var items = new List<string>();
foreach (object item in list.Cast<object>().Take(24))
{
string d = Describe(item, depth + 1);
if (d != null) items.Add(d);
}
return $"[{list.Count}] " + string.Join("; ", items);
}
// A plain struct or class: print the fields that carry something.
var inner = new List<string>();
foreach (FieldInfo f in t.GetFields(BindingFlags.Instance | BindingFlags.Public))
{
object fv;
try { fv = f.GetValue(value); }
catch (Exception) { continue; }
string d = Describe(fv, depth + 1);
if (d != null) inner.Add($"{f.Name}={d}");
}
return inner.Count == 0 ? null : "{" + string.Join(", ", inner) + "}";
}
// ─── What a creature actually attacks with ───────────────────────────
private static void DumpDefaultItems(GameObject prefab)
{
Humanoid humanoid = prefab.GetComponent<Humanoid>();
if (humanoid == null) return;
Log("--- DEFAULT ITEMS (Humanoid.m_defaultItems / m_randomWeapon / m_unarmedWeapon)");
var items = new List<GameObject>();
AddAll(items, Read<GameObject[]>(humanoid, "m_defaultItems"));
AddAll(items, Read<GameObject[]>(humanoid, "m_randomWeapon"));
ItemDrop unarmed = Read<ItemDrop>(humanoid, "m_unarmedWeapon");
if (unarmed != null) items.Add(unarmed.gameObject);
// The StoneGolem carries its weapons in random SETS (Spike, Sledge), which the first probe
// never looked at: m_defaultItems was empty and it said "none".
IList sets = Read<IList>(humanoid, "m_randomSets");
if (sets != null)
{
foreach (object set in sets)
{
GameObject[] setItems = Read<GameObject[]>(set, "m_items");
AddAll(items, setItems);
}
}
if (items.Count == 0) { Log(" (none)"); return; }
foreach (GameObject item in items.Distinct())
{
ItemDrop drop = item.GetComponent<ItemDrop>();
if (drop == null || drop.m_itemData == null || drop.m_itemData.m_shared == null) continue;
ItemDrop.ItemData.SharedData shared = drop.m_itemData.m_shared;
Log($" weapon '{item.name}' ({shared.m_name}) damages={shared.m_damages}");
LogAttack("primary", shared.m_attack);
LogAttack("secondary", shared.m_secondaryAttack);
}
}
private static void LogAttack(string label, Attack attack)
{
if (attack == null) return;
Log($" {label}: {Describe(attack, 0)}");
}
private static T Read<T>(object target, string field) where T : class
{
FieldInfo info = target.GetType().GetField(field,
BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
return info != null ? info.GetValue(target) as T : null;
}
private static void AddAll(List<GameObject> into, GameObject[] source)
{
if (source == null) return;
foreach (GameObject go in source) if (go != null) into.Add(go);
}
private static string PathOf(Transform node, Transform root)
{
if (node == root) return node.name;
var names = new List<string>();
for (Transform t = node; t != null && t != root; t = t.parent) names.Add(t.name);
names.Reverse();
return root.name + "/" + string.Join("/", names);
}
// ─── Who drops an item ───────────────────────────────────────────────
/// <summary>
/// Finds every prefab with a component that REFERENCES the named item: a drop table, a pickable,
/// a destructible, a creature's loot. Written for soft tissue, which the design says comes from
/// the Mistlands ancient skulls while the skull prefab itself drops nothing (probe 1): the drop
/// has to be somewhere else, probably in the fragments the skull spawns when destroyed.
/// </summary>
private static void WhoDrops(string itemName)
{
Log($"==================== WHO REFERENCES '{itemName}' ====================");
if (ZNetScene.instance == null)
{
Log("ZNetScene is not up: load a world and run it again.");
return;
}
int hits = 0;
foreach (GameObject prefab in ZNetScene.instance.m_prefabs)
{
if (prefab == null || prefab.name == itemName) continue;
foreach (Component component in prefab.GetComponentsInChildren<Component>(true))
{
if (component == null || component is Transform || component is ItemDrop) continue;
if (References(component, itemName, 0)) { Log($"{prefab.name} :: {component.GetType().Name} on '{component.name}'"); hits++; }
}
}
Log($"{hits} reference(s) to '{itemName}'.");
}
private static bool References(object value, string itemName, int depth)
{
if (value == null || depth > 3) return false;
foreach (FieldInfo field in value.GetType().GetFields(BindingFlags.Instance | BindingFlags.Public))
{
object fieldValue;
try { fieldValue = field.GetValue(value); }
catch (Exception) { continue; }
if (fieldValue == null) continue;
if (fieldValue is UnityEngine.Object unityObject)
{
if (unityObject != null && unityObject.name == itemName) return true;
continue;
}
Type t = fieldValue.GetType();
if (t.IsPrimitive || t.IsEnum || fieldValue is string) continue;
if (fieldValue is IList list)
{
foreach (object item in list)
{
if (item is UnityEngine.Object o) { if (o != null && o.name == itemName) return true; }
else if (item != null && !item.GetType().IsPrimitive && References(item, itemName, depth + 1)) return true;
}
}
else if (!t.IsAbstract && t.Namespace == null && References(fieldValue, itemName, depth + 1))
{
return true;
}
}
return false;
}
// ─── How every creature takes lightning ──────────────────────────────
/// <summary>
/// The constructs deal lightning, so a creature that resists or is immune to it resists the
/// constructs (Alfar doc sec. 17.13). This is the table to read before pricing them.
/// </summary>
private static void DumpLightningTable()
{
Log("==================== LIGHTNING TABLE ====================");
if (ZNetScene.instance == null)
{
Log("ZNetScene is not up (you are in the menu): load a world and run `alfarprobe lightning`.");
return;
}
var rows = new List<string>();
foreach (GameObject prefab in ZNetScene.instance.m_prefabs)
{
if (prefab == null) continue;
Character character = prefab.GetComponent<Character>();
if (character == null) continue;
rows.Add($"{prefab.name,-28} faction={character.m_faction,-12} hp={character.m_health,7:0} " +
$"boss={(character.m_boss ? "Y" : "n")} lightning={character.m_damageModifiers.m_lightning} " +
$"fire={character.m_damageModifiers.m_fire} spirit={character.m_damageModifiers.m_spirit}");
}
rows.Sort(StringComparer.Ordinal);
foreach (string row in rows) Log(row);
Log($"{rows.Count} creatures. Anything not 'Normal' under lightning is resistant, weak or immune.");
}
}
}

View file

@ -0,0 +1,40 @@
namespace RacesOfValheim
{
/// <summary>
/// The Alfar: light-bodied casters whose one resource is eitr (Alfar_Progettazione.txt).
///
/// Only the race check lives here for now. The shield, the death timer, the powers and the
/// Nexus each get their own file as they are written; the look is AlfarVisuals and its patches.
/// </summary>
public static class AlfarRace
{
/// <summary>
/// Everything the race registers with Jotunn. Called from RacesOfValheim.CreateAllModAssets,
/// which runs on PrefabManager.OnVanillaPrefabsAvailable: the one moment Jotunn takes new
/// status effects, items and prefabs into ObjectDB. Registered later, nothing can spawn.
/// </summary>
public static void CreateModAssets()
{
AlfarStatusEffects.Register();
AlfarDrones.Register();
AlfarConstructs.Register();
AlfarSigil.Register();
AlfarNexus.Register();
AlfarChests.Register();
AlfarLjosgard.Register();
AlfarTowers.Register();
}
/// <summary>
/// The local player's race, read from m_customData like every other race's IsXxx() (guide
/// 5.4: never from the body model index, which is not a race).
/// </summary>
public static bool IsLocalAlfar()
{
Player player = Player.m_localPlayer;
return player != null &&
player.m_customData.TryGetValue("Race", out string race) &&
race == AlfarConfig.RaceId;
}
}
}

View file

@ -0,0 +1,169 @@
using Jotunn.Entities;
using Jotunn.Managers;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// The Alfar's passive carrier. For now it holds only the FEATHER FALL: with eitr in the pool the
/// body is lowered instead of dropped.
///
/// Valheim already has the mechanism (the Feather Cape): SE_Stats.m_maxMaxFallSpeed makes
/// StatusEffect.ModifyWalkVelocity clamp the downward speed (verified in the IL, doc sec. 16B).
/// So the effect is an SE_Stats with that field switched on while there is eitr and off when
/// there is none - and a fall at eitr zero is a normal, fast, damaging fall.
///
/// The fall DAMAGE is a separate matter, handled by the shield prefix (AlfarEitr): a fall is free
/// while there is eitr. This effect is what makes it look like falling softly.
///
/// Rebuilt every tick for the same reason the Sverm's is: Setup runs once, at spawn, so anything
/// written there is frozen.
/// </summary>
public class SE_AlfarStats : SE_Stats
{
public const string EffectName = "SE_AlfarStats";
public override void Setup(Character character)
{
base.Setup(character);
name = EffectName;
m_name = "$rov_se_alfar_stats_name";
m_tooltip = "$rov_se_alfar_stats_tooltip";
Rebuild();
}
public override void UpdateStatusEffect(float dt)
{
base.UpdateStatusEffect(dt);
Rebuild();
}
private void Rebuild()
{
Player player = m_character as Player;
bool charged = player != null && player.GetEitr() > 0f;
// Written on the LIVE effect, not on the registered template: SEMan clones what it is
// given, so a template edited afterwards reaches nobody.
m_maxMaxFallSpeed = charged && AlfarConfig.SoftFall.Value ? AlfarConfig.FeatherFallSpeed.Value : 0f;
// The archon form is faster. SE_Stats.m_speedModifier is added to the body's speed factor.
m_speedModifier = AlfarArchon.Active ? AlfarPowerConfig.ArchonSpeedBonus.Value : 0f;
}
}
/// <summary>
/// A marker with a countdown: the HUD prints the remaining time of any effect that has a m_ttl, so
/// the cooldowns of the powers, the Heimkall wait and the archon form all show on screen without a
/// line of UI code (the Dvergar's cooldown icons do the same).
/// </summary>
public class SE_AlfarTimer : StatusEffect
{
}
public static class AlfarStatusEffects
{
public static readonly string[] TimerIds = { "skrid", "graf", "kall", "storm", "beam", "kyrr", "heimkall", "archon" };
public static string TimerName(string id) { return "SE_AlfarTimer_" + id; }
private static string TimerIcon(string id)
{
switch (id)
{
case "graf": return "TrophyDeathsquito";
case "kall": return "Thunderstone";
case "storm": return "OrbThunderBlood";
case "beam": return "Crystal";
case "kyrr": return "FreezeGland";
case "archon": return "TrophyFader";
default: return "Eitr";
}
}
/// <summary>Starts (or restarts) the on-screen countdown of a power, the Heimkall wait or the form.</summary>
public static void ShowTimer(string id, float seconds)
{
Player player = Player.m_localPlayer;
if (player == null || seconds <= 0f) return;
int hash = TimerName(id).GetStableHashCode();
SEMan seman = player.GetSEMan();
seman.RemoveStatusEffect(hash, true);
seman.AddStatusEffect(hash, true);
StatusEffect effect = seman.GetStatusEffect(hash);
if (effect != null) effect.m_ttl = seconds;
}
public static void ClearTimer(string id)
{
Player player = Player.m_localPlayer;
if (player != null) player.GetSEMan().RemoveStatusEffect(TimerName(id).GetStableHashCode(), true);
}
public static bool HasTimer(string id)
{
Player player = Player.m_localPlayer;
return player != null && player.GetSEMan().HaveStatusEffect(TimerName(id).GetStableHashCode());
}
public static void Register()
{
foreach (string id in TimerIds)
{
Sprite timerIcon = null;
GameObject source = PrefabManager.Cache.GetPrefab<GameObject>(TimerIcon(id));
ItemDrop sourceDrop = source != null ? source.GetComponent<ItemDrop>() : null;
if (sourceDrop != null && sourceDrop.m_itemData != null && sourceDrop.m_itemData.m_shared != null &&
sourceDrop.m_itemData.m_shared.m_icons != null && sourceDrop.m_itemData.m_shared.m_icons.Length > 0)
{
timerIcon = sourceDrop.m_itemData.m_shared.m_icons[0];
}
var timer = ScriptableObject.CreateInstance<SE_AlfarTimer>();
timer.name = TimerName(id);
timer.m_name = "$rov_se_alfar_timer_" + id + "_name";
timer.m_icon = timerIcon;
ItemManager.Instance.AddStatusEffect(new CustomStatusEffect(timer, fixReference: false));
}
Sprite icon = null;
GameObject prefab = PrefabManager.Cache.GetPrefab<GameObject>("Eitr");
ItemDrop drop = prefab != null ? prefab.GetComponent<ItemDrop>() : null;
if (drop != null && drop.m_itemData != null && drop.m_itemData.m_shared != null &&
drop.m_itemData.m_shared.m_icons != null && drop.m_itemData.m_shared.m_icons.Length > 0)
{
icon = drop.m_itemData.m_shared.m_icons[0];
}
var stats = ScriptableObject.CreateInstance<SE_AlfarStats>();
stats.name = SE_AlfarStats.EffectName;
stats.m_name = "$rov_se_alfar_stats_name";
stats.m_icon = icon;
ItemManager.Instance.AddStatusEffect(new CustomStatusEffect(stats, fixReference: false));
}
/// <summary>Adds the passive to a player that lacks it: status effects do not survive death or a reload.</summary>
public static void Ensure(Player player)
{
if (player == null) return;
int hash = SE_AlfarStats.EffectName.GetStableHashCode();
if (!player.GetSEMan().HaveStatusEffect(hash))
{
player.GetSEMan().AddStatusEffect(hash, true);
}
}
/// <summary>Takes the passive off a player who stopped being an Alfr.</summary>
public static void Remove(Player player)
{
if (player == null) return;
int hash = SE_AlfarStats.EffectName.GetStableHashCode();
if (player.GetSEMan().HaveStatusEffect(hash))
{
player.GetSEMan().RemoveStatusEffect(hash, true);
}
}
}
}

View file

@ -0,0 +1,239 @@
using HarmonyLib;
using Jotunn.Configs;
using Jotunn.Entities;
using Jotunn.Managers;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// The PRISMAVARD, the Alfar's towers (Alfar_Progettazione.txt sec. 8.6): the charred ballista of the
/// Ashlands, smaller and bronze, turned around to defend. Read from the live prefab (doc 16C P5):
///
/// - it is NOT a Piece: it has Turret, WearNTear and DropOnDestroyed and nothing that lets the
/// hammer place it, so a Piece is added here;
/// - it is an ENEMY tower: it targets players and tamed creatures and not enemies, so the three
/// flags are turned round;
/// - m_maxAmmo is 0 and HasAmmo() is true when it is 0 (read in the IL): the vanilla tower has
/// infinite ammunition, so "consumes nothing" is free; what is changed is the AMMO, a bolt that
/// does lightning, so the shot is ours.
///
/// It only works inside a Ljoskjarne's radius (AlfarTower switches the Turret off outside it), has a
/// shield equal to its health that returns by itself, and is repaired with the hammer and by the
/// drones like any building.
/// </summary>
public static class AlfarTowers
{
public const string PieceName = "AlfarPrismavard";
public const string PieceDisplay = "$rov_piece_alfar_prismavard_name";
public const string AmmoName = "AlfarPrismBolt";
public const string ProjectileName = "AlfarPrismProjectile";
public static void Register()
{
GameObject source = PrefabManager.Cache.GetPrefab<GameObject>("piece_Charred_Balista");
if (source == null)
{
Jotunn.Logger.LogWarning("[Alfar] No 'piece_Charred_Balista': the Prismavard is not registered.");
return;
}
GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(PieceName, source);
if (prefab == null) return;
Turret turret = prefab.GetComponent<Turret>();
if (turret == null)
{
Jotunn.Logger.LogWarning("[Alfar] The charred ballista has no Turret component: no Prismavard.");
return;
}
// Turned around: it defends the base against enemies and never at players or their tames.
turret.m_targetPlayers = false;
turret.m_targetTamed = false;
turret.m_targetEnemies = true;
turret.m_returnAmmoOnDestroy = false;
// The ammunition: a bolt that does lightning, shot from a projectile that spares friends
// and buildings. m_maxAmmo stays 0, which means infinite.
GameObject ammo = RegisterAmmo(turret);
if (ammo != null)
{
ItemDrop ammoDrop = ammo.GetComponent<ItemDrop>();
turret.m_defaultAmmo = ammoDrop;
if (turret.m_allowedAmmo != null && turret.m_allowedAmmo.Count > 0)
{
var allowed = turret.m_allowedAmmo[0];
allowed.m_ammo = ammoDrop;
turret.m_allowedAmmo[0] = allowed;
}
}
WearNTear wear = prefab.GetComponent<WearNTear>();
if (wear != null) wear.m_health *= AlfarNexusConfig.TowerHealthFactor.Value;
// The loot of an enemy ballista: a tower of ours must not be a way to farm it.
foreach (DropOnDestroyed drop in prefab.GetComponentsInChildren<DropOnDestroyed>(true))
{
if (drop != null) Object.DestroyImmediate(drop);
}
prefab.transform.localScale = Vector3.one * AlfarNexusConfig.TowerScale.Value;
ZNetView nview = prefab.GetComponent<ZNetView>();
if (nview != null) nview.m_syncInitialScale = true;
AlfarConstructs.Tint(prefab, new Color(0.85f, 0.58f, 0.28f, 1f));
AlfarMark mark = prefab.AddComponent<AlfarMark>();
mark.Role = "tower";
AlfarPieceShield shield = prefab.AddComponent<AlfarPieceShield>();
shield.Max = wear != null ? wear.m_health : 100f;
shield.Shield = shield.Max;
prefab.AddComponent<AlfarTower>();
Sprite icon = AlfarNexus.BorrowIcon("Crystal") ?? AlfarNexus.BorrowIcon("Bronze");
Piece piece = prefab.GetComponent<Piece>() ?? prefab.AddComponent<Piece>();
piece.m_craftingStation = null;
piece.m_resources = new Piece.Requirement[0];
piece.m_name = PieceDisplay;
piece.m_canBeRemoved = true;
piece.m_icon = icon;
piece.m_groundOnly = false;
piece.m_groundPiece = false;
Piece template = PrefabManager.Cache.GetPrefab<Piece>("piece_workbench");
if (template != null && template.m_placeEffect != null) piece.m_placeEffect = template.m_placeEffect;
PieceManager.Instance.AddPiece(new CustomPiece(prefab, fixReference: false, new PieceConfig
{
Name = PieceDisplay,
Description = "$rov_piece_alfar_prismavard_desc",
PieceTable = PieceTables.Hammer,
Category = PieceCategories.Misc,
Icon = icon,
Requirements = new[]
{
new RequirementConfig("Bronze", AlfarNexusConfig.TowerBronze.Value, 0, true),
new RequirementConfig("Crystal", AlfarNexusConfig.TowerCrystal.Value, 0, true),
},
}));
// No cap on how many (the user said so), but one rule: inside a Ljoskjarne's radius.
PieceDensityLimit.RegisterGate(PieceName, (player, position) =>
{
if (!AlfarRace.IsLocalAlfar())
{
if (player != null) player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_alfar_only_alfar"));
return false;
}
if (AlfarNexusBehaviour.Covering(position) == null)
{
if (player != null) player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_alfar_tower_needs_nexus"));
return false;
}
return true;
});
AlfarPieces.Extra.Add(PieceName);
}
private static GameObject RegisterAmmo(Turret turret)
{
ItemDrop original = turret.m_defaultAmmo;
if (original == null)
{
Jotunn.Logger.LogWarning("[Alfar] The ballista has no default ammo to copy.");
return null;
}
GameObject ammo = PrefabManager.Instance.CreateClonedPrefab(AmmoName, original.gameObject);
if (ammo == null) return null;
ItemDrop drop = ammo.GetComponent<ItemDrop>();
ItemDrop.ItemData.SharedData shared = drop.m_itemData.m_shared;
shared.m_name = "$rov_item_alfar_prismbolt_name";
HitData.DamageTypes damage = default(HitData.DamageTypes);
damage.m_lightning = AlfarNexusConfig.TowerDamage.Value;
shared.m_damages = damage;
// The projectile it flies as: a copy that spares friends and buildings.
GameObject originalProjectile = shared.m_attack != null ? shared.m_attack.m_attackProjectile : null;
if (originalProjectile != null)
{
GameObject projectile = PrefabManager.Instance.CreateClonedPrefab(ProjectileName, originalProjectile);
Projectile settings = projectile != null ? projectile.GetComponent<Projectile>() : null;
if (settings != null)
{
settings.m_hitFriendly = false;
settings.m_noDamageFriendly = true;
settings.m_aoeSkipWearNTear = true;
PrefabManager.Instance.AddPrefab(projectile);
shared.m_attack.m_attackProjectile = projectile;
}
}
ItemManager.Instance.AddItem(new CustomItem(ammo, fixReference: false));
return ammo;
}
}
/// <summary>The tower runs only while a Ljoskjarne's radius covers it: outside, the Turret is off.</summary>
public class AlfarTower : MonoBehaviour
{
private Turret turret;
private float nextCheck;
private void Awake() { turret = GetComponent<Turret>(); }
private void Update()
{
if (turret == null || Time.time < nextCheck) return;
nextCheck = Time.time + 2f;
bool powered = AlfarNexusBehaviour.Covering(transform.position) != null;
if (turret.enabled != powered) turret.enabled = powered;
}
}
/// <summary>
/// A building's shield: equal to its health, back at 1% a second after five quiet seconds. Its own
/// absorption on WearNTear.ApplyDamage, the stage every blow on a building ends in; the hammer and
/// the drones repair the HEALTH, the shield returns by itself.
/// </summary>
public class AlfarPieceShield : MonoBehaviour
{
public float Max;
public float Shield;
private float lastHit = -999f;
private void Update()
{
if (Shield >= Max || Time.time - lastHit < 5f) return;
Shield = Mathf.Min(Max, Shield + Max * 0.01f * Time.deltaTime);
}
public float Absorb(float damage)
{
if (damage <= 0f) return damage;
lastHit = Time.time;
float absorbed = Mathf.Min(Shield, damage);
Shield -= absorbed;
return damage - absorbed;
}
[HarmonyPatch(typeof(WearNTear), "ApplyDamage")]
public static class Alfar_PieceShield_Patch
{
public static void Prefix(WearNTear __instance, ref float __0)
{
AlfarPieceShield shield = __instance != null ? __instance.GetComponent<AlfarPieceShield>() : null;
if (shield != null) __0 = shield.Absorb(__0);
}
}
}
}

View file

@ -0,0 +1,525 @@
using System.Collections.Generic;
using HarmonyLib;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// What an Alfr looks like (Alfar_Progettazione.txt sec. 7): ash-grey skin, five percent taller
/// and a little thinner than a Viking, no hair, no beard, and two completely black eyes.
///
/// Everything here is written the way the Sverm and the Dvergar already write theirs, because
/// each of those shapes cost somebody a test session:
/// - the race is read off the ZDO, so remote players render right, falling back to
/// m_customData for the menu preview (same shape as SvermVisuals.GetPlayerRace);
/// - the skin is written AFTER Valheim rebuilds the body material (see AlfarPatches);
/// - the scale goes on the "Visual" child and never the root, and only ever undoes its own;
/// - the eyes are spheres on the head bone with every offset divided by lossyScale, because
/// the player armature is authored at scale 100.
///
/// The eyes are the Sverm's spheres with the glow taken out: same geometry, a matte black
/// material, no emission at all.
/// </summary>
public static class AlfarVisuals
{
private const string EyesName = "AlfarEyes";
private const string HeadBoneName = "Head";
// ─── Race check ──────────────────────────────────────────────────────
public static string GetPlayerRace(Player player)
{
if (player == null) return "Human";
ZNetView nview = player.GetComponent<ZNetView>();
if (nview != null && nview.IsValid())
{
string race = nview.GetZDO().GetString("RacesOfValheim_Race", "");
if (!string.IsNullOrEmpty(race)) return race;
}
if (player.m_customData != null && player.m_customData.TryGetValue("Race", out string custom))
{
return custom;
}
return "Human";
}
public static bool IsAlfarPlayer(Player player) => GetPlayerRace(player) == AlfarConfig.RaceId;
// ─── Scale ───────────────────────────────────────────────────────────
/// <summary>
/// +5% in height and a little less wide. NON-uniform, so the scale is a Vector3 and not the
/// single float the other races write.
///
/// The reset only ever undoes a scale that looks like ours: another race (the Trol, the
/// Dvergar) may be sizing this player and RaceScale exists so the two do not fight.
/// </summary>
public static void ApplyScale(Player player, bool isAlfar)
{
if (player == null) return;
GameObject visual = Traverse.Create(player).Field("m_visual").GetValue<GameObject>();
if (visual == null) return;
Vector3 ours = new Vector3(AlfarConfig.WidthScale.Value, AlfarConfig.HeightScale.Value, AlfarConfig.WidthScale.Value);
// The archon form is bigger: published in the ZDO, so every client sizes it the same.
Vector3 archon = ours * AlfarPowerConfig.ArchonScale.Value;
bool inArchon = isAlfar && AlfarArchon.IsArchon(player);
Vector3 current = visual.transform.localScale;
Vector3 target = inArchon ? archon : ours;
if (!isAlfar)
{
// Undo only a scale that is one of ours, the normal one or the archon's.
if (!LooksLike(current, ours) && !LooksLike(current, archon)) return;
target = Vector3.one;
}
if (!LooksLike(current, target))
{
visual.transform.localScale = target;
}
}
private static bool LooksLike(Vector3 a, Vector3 b)
{
return Mathf.Abs(a.x - b.x) < 0.001f && Mathf.Abs(a.y - b.y) < 0.001f && Mathf.Abs(a.z - b.z) < 0.001f;
}
// ─── Hair and beard ──────────────────────────────────────────────────
/// <summary>
/// Takes the hair and the beard off the VISUAL only. The Skeleton also rewrites the saved
/// profile, which makes the loss permanent; the Alfar do not, so a reset to Human gets the
/// hair back the next time the game rebuilds the equipment visuals.
///
/// Since Valheim 1.0 these take an item hash and not a name: 0 is the empty slot.
/// </summary>
public static void ApplyHairless(Player player)
{
if (player == null) return;
VisEquipment vis = player.GetComponent<VisEquipment>();
if (vis == null) return;
vis.SetHairItem(0);
vis.SetBeardItem(0);
}
// ─── Eyes ────────────────────────────────────────────────────────────
/// <summary>
/// Which way the skull faces, measured once when the eyes are built and kept for as long as
/// they exist (RigBindPose explains why it is read from the bind pose and not live).
/// </summary>
private class EyeFrame : MonoBehaviour
{
public Vector3 LocalForward = Vector3.forward;
public Vector3 LocalUp = Vector3.up;
public Vector3 LocalRight = Vector3.right;
}
private static Shader cachedShader;
private static bool shaderResolved;
public static void ApplyEyes(Player player)
{
if (player == null) return;
Transform headBone = FindBone(player, HeadBoneName);
if (headBone == null) return; // rig not up yet; try again next pass
Transform eyes = headBone.Find(EyesName);
if (!IsAlfarPlayer(player) || player.IsDead())
{
if (eyes != null)
{
// Renamed first: Destroy is deferred to the end of the frame, and every call
// until then would otherwise find it again.
eyes.name = EyesName + "_Removed";
Object.Destroy(eyes.gameObject);
}
return;
}
if (eyes == null)
{
// Sitting, attached, mid-attack or asleep the head can be turned away from the
// body's forward at the instant the frame is measured, which puts the eyes behind
// the skull. Wait for a neutral moment (the same guard as the Sverm's).
if (player.IsAttached() || player.IsAttachedToShip() || player.InAttack() || player.IsSleeping())
{
return;
}
eyes = BuildEyes(player, headBone);
}
if (eyes == null) return;
PlaceEyes(player, eyes);
}
/// <summary>
/// A grey's eyes: wide black almonds, outer corners raised, wrapping round the sides of the
/// face. Each is a sphere squashed to an ellipsoid and turned in the skull's own frame.
///
/// FIXED HEAD-LOCAL UNITS, never headBone.lossyScale. The Alfar Visual is scaled
/// non-uniformly, so the head's lossyScale is only an approximation that changes as the
/// head turns; recomputed on the 0.5s cosmetic pass it made the eyes trail the face. The
/// face is skinned to the same bone through the same matrices, so a constant local offset
/// stays glued to it at any body scale, and PlaceEyes only has to run when the eyes change.
/// </summary>
private static void PlaceEyes(Player player, Transform holder)
{
EyeFrame frame = holder.GetComponent<EyeFrame>();
if (frame == null) return;
const float toLocal = PlayerFace.MetresToHeadLocal;
float height = AlfarConfig.EyeHeight;
float separation = AlfarConfig.EyeSeparation;
float size = AlfarConfig.EyeSizeMultiplier.Value;
PlayerFace.AdjustEyes(player, ref height, ref separation, ref size);
Quaternion facing = Quaternion.LookRotation(frame.LocalForward, frame.LocalUp);
for (int i = 0; i < holder.childCount; i++)
{
Transform eye = holder.GetChild(i);
// Index 0 is offset against the right axis, so it is the model's left eye. The
// slant and the wrap are mirrored so both outer corners go up and back.
float side = i == 0 ? -1f : 1f;
// This eye's hand corrections (RaceEyeTuning).
float forward = AlfarConfig.EyeForward;
float eyeHeight = height;
float eyeSeparation = separation;
float eyeSize = size;
float wrap = AlfarConfig.EyeWrap;
float slant = AlfarConfig.EyeSlant;
float tilt = 0f;
RaceEyeTuning.Eye tuning = RaceEyeTuning.For(AlfarConfig.RaceId, player, side);
if (tuning != null)
{
forward += tuning.Forward;
eyeHeight += tuning.Height;
eyeSeparation += tuning.Separation;
eyeSize *= tuning.Size;
tilt = tuning.RotX;
wrap += tuning.RotY;
slant += tuning.RotZ;
}
Vector3 offset = frame.LocalForward * forward + frame.LocalUp * eyeHeight
+ frame.LocalRight * (side * eyeSeparation);
eye.localPosition = offset * toLocal;
eye.localRotation = facing * Quaternion.Euler(tilt, wrap * side, slant * side);
eye.localScale = AlfarConfig.EyeExtent * (eyeSize * toLocal);
}
}
private static Transform BuildEyes(Player player, Transform headBone)
{
Shader shader = ResolveShader(player);
if (shader == null) return null;
GameObject holder = new GameObject(EyesName);
holder.transform.SetParent(headBone, false);
holder.transform.localPosition = Vector3.zero;
holder.transform.localRotation = Quaternion.identity;
holder.transform.localScale = Vector3.one;
EyeFrame frame = holder.AddComponent<EyeFrame>();
RigBindPose.MeasureHeadFrame(player, headBone, "Alfar",
out frame.LocalForward, out frame.LocalUp, out frame.LocalRight);
for (int i = 0; i < 2; i++)
{
// Spheres, not quads: a quad seen edge-on is a line and vanishes.
GameObject eye = GameObject.CreatePrimitive(PrimitiveType.Sphere);
eye.name = "Eye" + i;
foreach (Collider collider in eye.GetComponents<Collider>())
{
Object.Destroy(collider);
}
eye.transform.SetParent(holder.transform, false);
eye.transform.localPosition = Vector3.zero;
eye.transform.localRotation = Quaternion.identity;
eye.transform.localScale = Vector3.zero; // PlaceEyes runs immediately after this
Renderer renderer = eye.GetComponent<Renderer>();
renderer.material = BlackMaterial(shader);
renderer.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off;
renderer.receiveShadows = false;
}
return holder.transform;
}
/// <summary>
/// Black with a wet sheen: no emission, but smooth enough to catch a highlight, which is
/// what makes a grey's eyes read as eyes and not as two holes punched in the face.
/// </summary>
private static Material BlackMaterial(Shader shader)
{
Material material = new Material(shader);
material.color = Color.black;
if (material.HasProperty("_EmissionColor")) material.SetColor("_EmissionColor", Color.black);
if (material.HasProperty("_Glossiness")) material.SetFloat("_Glossiness", 0.8f);
if (material.HasProperty("_Smoothness")) material.SetFloat("_Smoothness", 0.8f);
if (material.HasProperty("_Metallic")) material.SetFloat("_Metallic", 0f);
return material;
}
/// <summary>
/// Custom/Creature first, for the reason the Sverm's own resolver gives: Valheim dithers the
/// player away when the camera gets inside them, and only the game's own shaders know about
/// it, so eyes on an unlit shader would hang in the air while the face dissolved.
/// </summary>
private static Shader ResolveShader(Player player)
{
if (shaderResolved) return cachedShader;
// CUSTOM/CREATURE, found the one way that works in play. Two earlier attempts failed in
// opposite directions and both are on record in the log:
// 1. Shader.Find("Custom/Creature") returns null in the main-menu preview (Valheim's
// shaders are not all loaded by name until something has used them), so the code
// fell to Sprites/Default and CACHED it for the whole session;
// 2. taking the player's own body shader gave 'Custom/Player', the SKIN shader: it
// paints the skin texture, so the eyes came out white.
// So: ask Shader.Find, and failing that read the shader off a real creature's material
// (the Deathsquito's, the very prefab the drones are cloned from) once the world is up.
// A failure is never cached, and in the menu preview there are simply no eyes yet.
Shader shader = Shader.Find("Custom/Creature");
if (shader == null && ZNetScene.instance != null)
{
GameObject creature = ZNetScene.instance.GetPrefab("Deathsquito");
Renderer renderer = creature != null ? creature.GetComponentInChildren<Renderer>(true) : null;
if (renderer != null && renderer.sharedMaterial != null) shader = renderer.sharedMaterial.shader;
}
if (shader == null)
{
// The main-menu preview has no world and so no creature to read a shader from. Its eyes
// are only for show and are thrown away with the preview, so a plain unlit black will do
// there - and it is NOT cached, so the world gets the real one.
ZNetView preview = player != null ? player.GetComponent<ZNetView>() : null;
if (preview == null || !preview.IsValid()) return Shader.Find("Sprites/Default");
return null;
}
Jotunn.Logger.LogInfo($"[Alfar] Eye shader resolved to '{shader.name}'.");
shaderResolved = true;
cachedShader = shader;
return cachedShader;
}
// ─── Skin ────────────────────────────────────────────────────────────
/// <summary>Ash grey, or the glow colour while the archon form is up.</summary>
public static Color SkinFor(Player player)
{
return AlfarArchon.IsArchon(player) ? AlfarPowerConfig.ArchonColor.Value : AlfarConfig.SkinColor.Value;
}
private const string GlowName = "AlfarArchonGlow";
/// <summary>
/// A blue light on the body while the archon form is up, taken off when it is not. Every
/// client runs this for every Alfr in range, so the glow is seen by everyone.
/// </summary>
public static void ApplyArchonGlow(Player player)
{
if (player == null) return;
Transform existing = player.transform.Find(GlowName);
bool want = IsAlfarPlayer(player) && AlfarArchon.IsArchon(player) && !player.IsDead();
if (!want)
{
if (existing != null) Object.Destroy(existing.gameObject);
return;
}
if (existing == null)
{
GameObject holder = new GameObject(GlowName);
holder.transform.SetParent(player.transform, false);
holder.transform.localPosition = Vector3.up * 1.2f;
existing = holder.transform;
Light light = holder.AddComponent<Light>();
light.type = LightType.Point;
light.range = 9f;
light.intensity = 3f;
light.shadows = LightShadows.None;
}
Light glow = existing.GetComponent<Light>();
if (glow != null) glow.color = AlfarPowerConfig.ArchonColor.Value;
}
/// <summary>
/// The grey, for real. A tint on _SkinColor only MULTIPLIES the skin texture, and that texture is
/// pink: multiplied by a grey it comes out as a darker human skin, not as grey skin (the second
/// test: "the skin is the normal colour"). So the body's texture is replaced by a DESATURATED
/// copy, made once on the GPU and read back, and _SkinColor then only sets how light the grey is.
/// The original texture is remembered per material so a reset to human puts it back.
/// </summary>
private static readonly Dictionary<Texture, Texture2D> greyOf = new Dictionary<Texture, Texture2D>();
private static readonly Dictionary<Material, Texture> originalTexture = new Dictionary<Material, Texture>();
private static Texture2D Desaturated(Texture source)
{
Texture2D grey;
if (greyOf.TryGetValue(source, out grey) && grey != null) return grey;
RenderTexture target = RenderTexture.GetTemporary(source.width, source.height, 0,
RenderTextureFormat.ARGB32, RenderTextureReadWrite.sRGB);
RenderTexture previous = RenderTexture.active;
try
{
Graphics.Blit(source, target);
RenderTexture.active = target;
grey = new Texture2D(source.width, source.height, TextureFormat.RGBA32, true);
grey.ReadPixels(new Rect(0, 0, source.width, source.height), 0, 0);
Color32[] pixels = grey.GetPixels32();
for (int i = 0; i < pixels.Length; i++)
{
Color32 c = pixels[i];
byte luma = (byte)(c.r * 0.299f + c.g * 0.587f + c.b * 0.114f);
pixels[i] = new Color32(luma, luma, luma, c.a);
}
grey.SetPixels32(pixels);
grey.Apply(true);
grey.name = source.name + "_AlfarGrey";
}
catch (System.Exception e)
{
Jotunn.Logger.LogWarning("[Alfar] Could not make the grey skin texture: " + e.Message);
grey = null;
}
finally
{
RenderTexture.active = previous;
RenderTexture.ReleaseTemporary(target);
}
if (grey != null) greyOf[source] = grey;
return grey;
}
/// <summary>
/// Puts the grey texture on every skin material of the body (or takes it off again). Runs from the
/// UpdateColors postfix, so it covers the main-menu preview and every client, and from the
/// cosmetic pass, so it survives anything that rebuilds the body.
/// </summary>
public static void ApplyGreyTexture(VisEquipment vis, bool on)
{
if (vis == null || vis.m_bodyModel == null) return;
foreach (Material material in vis.m_bodyModel.materials)
{
if (material == null || !material.HasProperty("_SkinColor") || !material.HasProperty("_MainTex")) continue;
Texture current = material.GetTexture("_MainTex");
if (on)
{
if (current == null) continue;
bool ours = false;
foreach (Texture2D grey in greyOf.Values) if (grey == current) { ours = true; break; }
if (ours) continue;
Texture2D desaturated = Desaturated(current);
if (desaturated == null) continue;
originalTexture[material] = current;
material.SetTexture("_MainTex", desaturated);
}
else
{
Texture original;
if (originalTexture.TryGetValue(material, out original) && original != null)
{
material.SetTexture("_MainTex", original);
}
originalTexture.Remove(material);
}
}
}
/// <summary>
/// Keeps the skin right for whoever it is: the grey and its tint for an Alfr, the original for
/// anyone who stopped being one. The tint is only written when it differs, and UpdateColors is
/// pushed only then, so it costs a colour compare.
/// </summary>
public static void SyncSkin(Player player, bool isAlfar)
{
if (player == null) return;
VisEquipment vis = player.GetComponent<VisEquipment>();
if (vis == null || vis.m_bodyModel == null) return;
if (!isAlfar)
{
if (originalTexture.Count > 0) ApplyGreyTexture(vis, false);
return;
}
ApplyGreyTexture(vis, true);
Material material = vis.m_bodyModel.material;
if (material == null || !material.HasProperty("_SkinColor")) return;
Color wanted = SkinFor(player);
Color current = material.GetColor("_SkinColor");
if (Mathf.Abs(current.r - wanted.r) < 0.01f && Mathf.Abs(current.g - wanted.g) < 0.01f &&
Mathf.Abs(current.b - wanted.b) < 0.01f) return;
Traverse.Create(vis).Method("UpdateColors").GetValue();
}
// ─── Hands ───────────────────────────────────────────────────────────
/// <summary>The right hand bone: where the beam leaves from.</summary>
public static Transform RightHand(Player player)
{
return player != null ? FindBone(player, "RightHand") : null;
}
private static Transform FindBone(Player player, string boneName)
{
VisEquipment visEq = player.GetComponent<VisEquipment>();
if (visEq == null || visEq.m_bodyModel == null || visEq.m_bodyModel.bones == null) return null;
foreach (Transform bone in visEq.m_bodyModel.bones)
{
if (bone != null && bone.name == boneName) return bone;
}
// Loose match, because rigs are not consistent about capitalisation or prefixes.
string wanted = boneName.ToLowerInvariant();
foreach (Transform bone in visEq.m_bodyModel.bones)
{
if (bone != null && bone.name.ToLowerInvariant().Contains(wanted)) return bone;
}
return null;
}
}
}

View file

@ -0,0 +1,303 @@
using System.Collections.Generic;
using Jotunn.Entities;
using Jotunn.Managers;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// Reads out a creature's animator, because guessing at animation has cost this mod real time:
/// a howl that was looked for under three wrong names, a taunt animation nobody knew played, and
/// a sound prefab that killed the process when spawned on its own.
///
/// WHAT UNITY LETS US SEE AT RUNTIME, and what it does not, because the line matters:
///
/// Readable. Every parameter with its type. Every layer. Every CLIP in the controller with its
/// name and length, through RuntimeAnimatorController.animationClips - so a creature's whole
/// vocabulary can be listed without ever wearing it. And every AnimationEvent on every clip:
/// the instant, the method name it calls, and its parameters. That last one is where a sound
/// fired by an animation lives, which is the thing this was written to find.
///
/// Not readable. The state machine. States and transitions live in AnimatorController, which is
/// an editor-only type, and GetCurrentAnimatorStateInfo hands back hashes with no names. States
/// can only be guessed and then confirmed: AnimatorStateInfo.IsName("Layer.Name") answers yes or
/// no, and Animator.Play takes a state name we can try and then verify by reading back which
/// clip actually started.
///
/// So "catch the howl and trigger just that stretch" is possible, in this order: list the clips
/// here, find the one that looks like a howl, look at its events to see whether the sound is
/// wired into the animation, then Play the state and CrossFade back to idle at the point wanted.
/// Worth knowing before starting: if the sound is an animation event, playing the clip alone will
/// not make it, because events are dispatched to a component on the animated object and Valheim's
/// dispatcher is CharacterAnimEvent. The animation is the prize; the audio we already play
/// ourselves.
/// </summary>
public class DumpAnimCommand : ConsoleCommand
{
public override string Name => "dumpanim";
public override string Help =>
"[DEBUG] dumpanim <prefab> - lists a creature's animator parameters, layers, clips and " +
"every animation event on them. dumpanim live - logs which clip each animator under you " +
"starts playing, as it happens; run it again to stop.";
public override void Run(string[] args)
{
if (args.Length == 0)
{
Console.instance.Print("dumpanim <prefab> | dumpanim live");
return;
}
if (args[0].ToLower() == "live")
{
ToggleWatcher();
return;
}
DumpPrefab(args[0]);
}
/// <summary>
/// Everything the controller of <paramref name="prefabName"/> can play. Reads a prefab in
/// memory, so it needs no transformation and cannot disturb a live one.
/// </summary>
private static void DumpPrefab(string prefabName)
{
GameObject prefab = PrefabManager.Cache.GetPrefab<GameObject>(prefabName);
if (prefab == null)
{
Report($"[Anim] '{prefabName}' is not in the prefab cache.");
return;
}
Animator[] animators = prefab.GetComponentsInChildren<Animator>(true);
if (animators.Length == 0)
{
// Not a creature. Say what it is anyway: this is also how a sound prefab gets looked
// at without being spawned, which matters for the ones that cannot safely be spawned.
Report($"[Anim] '{prefabName}' has no Animator. Contents:");
foreach (Transform t in prefab.GetComponentsInChildren<Transform>(true))
{
Jotunn.Logger.LogInfo($"[Anim] '{PathOf(t)}' [{ComponentsOf(t.gameObject)}]");
DescribeAudio(t.gameObject);
}
return;
}
Report($"[Anim] '{prefabName}': {animators.Length} animator(s).");
foreach (Animator animator in animators)
{
RuntimeAnimatorController controller = animator.runtimeAnimatorController;
Report($"[Anim] on '{PathOf(animator.transform)}' controller " +
$"'{(controller != null ? controller.name : "none")}'");
// What else lives on that object, because an animation event is delivered to THESE
// components and nowhere else. CharacterAnimEvent showing up here is the game's own
// receiver; a form that carries it is a form where vanilla is already handling - or
// already failing to handle - every event the clips fire.
Jotunn.Logger.LogInfo($"[Anim] receivers: [{ComponentsOf(animator.gameObject)}]");
if (controller == null) continue;
foreach (AnimatorControllerParameter p in animator.parameters)
{
Jotunn.Logger.LogInfo($"[Anim] param {p.name} ({p.type})");
}
for (int i = 0; i < animator.layerCount; i++)
{
Jotunn.Logger.LogInfo($"[Anim] layer {i} '{animator.GetLayerName(i)}'");
}
AnimationClip[] clips = controller.animationClips;
Report($"[Anim] {clips.Length} clip(s):");
foreach (AnimationClip clip in clips)
{
if (clip == null) continue;
AnimationEvent[] events = clip.events;
Jotunn.Logger.LogInfo(
$"[Anim] '{clip.name}' {clip.length:F2}s loop={clip.isLooping} " +
$"events={events.Length}");
foreach (AnimationEvent e in events)
{
// The object reference is the interesting one: a sound wired into an
// animation arrives here as the asset itself, name included.
string reference = e.objectReferenceParameter != null
? $" ref='{e.objectReferenceParameter.name}' ({e.objectReferenceParameter.GetType().Name})"
: "";
Jotunn.Logger.LogInfo(
$"[Anim] @{e.time:F2}s {e.functionName}(" +
$"string='{e.stringParameter}' float={e.floatParameter:F2} " +
$"int={e.intParameter}){reference}");
}
}
}
}
private static void ToggleWatcher()
{
if (Player.m_localPlayer == null)
{
Console.instance.Print("dumpanim live needs you to be in the world.");
return;
}
AnimatorWatcher existing = Player.m_localPlayer.GetComponent<AnimatorWatcher>();
if (existing != null)
{
Object.Destroy(existing);
Report("[Anim] live watch off.");
return;
}
Player.m_localPlayer.gameObject.AddComponent<AnimatorWatcher>();
Report("[Anim] live watch on: every clip change under you, as it happens.");
}
/// <summary>
/// Why a sound prefab is or is not audible when it is simply instantiated.
///
/// The AudioSource settings say whether anything starts by itself, and ZSFX's own fields say
/// what it would play if asked - it keeps a LIST of clips and chooses at play time, so a
/// prefab whose AudioSource has no clip is normal rather than broken. Read through reflection
/// because these are the game's private serialized fields.
/// </summary>
private static void DescribeAudio(GameObject go)
{
AudioSource audio = go.GetComponent<AudioSource>();
if (audio != null)
{
Jotunn.Logger.LogInfo(
$"[Anim] AudioSource playOnAwake={audio.playOnAwake} " +
$"clip='{(audio.clip != null ? audio.clip.name : "none")}' " +
$"volume={audio.volume:F2} spatialBlend={audio.spatialBlend:F2} " +
$"range={audio.minDistance:F1}-{audio.maxDistance:F1} loop={audio.loop} " +
$"mixer='{(audio.outputAudioMixerGroup != null ? audio.outputAudioMixerGroup.name : "none")}'");
}
foreach (Component comp in go.GetComponents<Component>())
{
if (comp == null || comp.GetType().Name != "ZSFX") continue;
List<string> fields = new List<string>();
foreach (System.Reflection.FieldInfo f in comp.GetType().GetFields(
System.Reflection.BindingFlags.Instance |
System.Reflection.BindingFlags.Public |
System.Reflection.BindingFlags.NonPublic))
{
object value = f.GetValue(comp);
System.Array array = value as System.Array;
if (array == null)
{
fields.Add($"{f.Name}={value}");
continue;
}
// The elements, not just the count. m_audioClips is where a sound's actual clips
// live, and whether they are AudioClips or unloaded soft references is the whole
// question when a sound spawns and stays silent.
List<string> elements = new List<string>();
for (int e = 0; e < array.Length && e < 4; e++)
{
object item = array.GetValue(e);
Object asObject = item as Object;
elements.Add(item == null
? "null"
: $"{item.GetType().Name}:'{(asObject != null ? asObject.name : item.ToString())}'");
}
fields.Add($"{f.Name}[{array.Length}]={{{string.Join(", ", elements.ToArray())}}}");
}
Jotunn.Logger.LogInfo($"[Anim] ZSFX {string.Join(" ", fields.ToArray())}");
Jotunn.Logger.LogInfo(
$"[Anim] ZSFX methods: {string.Join(", ", MethodNamesOf(comp))}");
}
}
private static string[] MethodNamesOf(Component comp)
{
List<string> names = new List<string>();
foreach (System.Reflection.MethodInfo m in comp.GetType().GetMethods(
System.Reflection.BindingFlags.Instance |
System.Reflection.BindingFlags.Public |
System.Reflection.BindingFlags.DeclaredOnly))
{
names.Add(m.Name + "(" + m.GetParameters().Length + ")");
}
return names.ToArray();
}
/// <summary>The component type names on one object, Transform left out as noise.</summary>
private static string ComponentsOf(GameObject go)
{
List<string> names = new List<string>();
foreach (Component comp in go.GetComponents<Component>())
{
if (comp != null && !(comp is Transform)) names.Add(comp.GetType().Name);
}
return string.Join(", ", names.ToArray());
}
private static string PathOf(Transform t)
{
string path = t.name;
for (Transform p = t.parent; p != null; p = p.parent) path = p.name + "/" + path;
return path;
}
/// <summary>To the log and to the console both, since one of the two is always the wrong one.</summary>
private static void Report(string line)
{
Jotunn.Logger.LogInfo(line);
if (Console.instance != null) Console.instance.Print(line);
}
/// <summary>
/// Watches every animator under the player and says when one starts a different clip.
///
/// Only the change is logged, not the state: an animator asked every frame would fill the log
/// with the idle it is already playing. The heaviest clip is the one reported, because during
/// a transition two are live at once and the heavier one is the one being watched on screen.
/// </summary>
private class AnimatorWatcher : MonoBehaviour
{
private readonly Dictionary<Animator, string> last = new Dictionary<Animator, string>();
private void Update()
{
foreach (Animator animator in GetComponentsInChildren<Animator>(true))
{
if (animator == null || animator.runtimeAnimatorController == null) continue;
AnimatorClipInfo[] playing = animator.GetCurrentAnimatorClipInfo(0);
if (playing.Length == 0) continue;
AnimationClip heaviest = null;
float weight = -1f;
foreach (AnimatorClipInfo info in playing)
{
if (info.clip != null && info.weight > weight)
{
heaviest = info.clip;
weight = info.weight;
}
}
if (heaviest == null) continue;
string previous;
if (last.TryGetValue(animator, out previous) && previous == heaviest.name) continue;
last[animator] = heaviest.name;
Jotunn.Logger.LogInfo(
$"[Anim] live: '{PathOf(animator.transform)}' -> '{heaviest.name}' " +
$"{heaviest.length:F2}s weight={weight:F2} events={heaviest.events.Length}");
}
}
}
}
}

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

@ -0,0 +1,170 @@
using HarmonyLib;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// Whether a player is a bat, on any client.
///
/// Stamina Flight flies on m_flying (DirectedFlight.cs), which vanilla's AI and damage never
/// look at, so monsters notice and hurt that bat with no help.
///
/// Free Flight flies on vanilla's debug-fly flag, and vanilla reads that flag as "this player
/// 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>
public static class AswidBatForm
{
/// <summary>
/// The ZDO flag AswidRace writes when the form goes up. Replicated, so it answers for
/// remote players too.
/// </summary>
public const string BatZdoKey = "Aswid_IsBatForm";
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>
/// 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
/// transform where the ZDO write has not landed yet.
/// </summary>
public static bool IsBat(Player player)
{
if (player == null) return false;
ZNetView nview = player.GetComponent<ZNetView>();
if (nview != null && nview.IsValid() && nview.GetZDO().GetBool(BatZdoKey, false)) return true;
return player == Player.m_localPlayer &&
player.GetSEMan() != null &&
player.GetSEMan().HaveStatusEffect(BatFormHash);
}
}
/// <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>
/// 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
/// the ZDO would stay true, which is a respawned player floating over the ground with a bat
/// drawn on them.
/// </summary>
[HarmonyPatch(typeof(Player), "OnDeath")]
public static class Aswid_BatDiesAsBat_Patch
{
public static void Prefix(Player __instance)
{
if (__instance != Player.m_localPlayer) return;
if (AswidRace.Instance == null) return;
AswidRace.Instance.HardResetBatForm();
}
}
}

View file

@ -27,8 +27,8 @@ namespace RacesOfValheim
public const string SuperiorBaseName = "MeadBaseSuperiorBloodPotion"; public const string SuperiorBaseName = "MeadBaseSuperiorBloodPotion";
public const string SuperiorPotionName = "MeadSuperiorBloodPotion"; public const string SuperiorPotionName = "MeadSuperiorBloodPotion";
private const string PotionDisplayName = "Blood Potion"; private const string PotionDisplayName = "$rov_item_aswid_bloodpotion_name";
private const string SuperiorPotionDisplayName = "Superior Blood Potion"; private const string SuperiorPotionDisplayName = "$rov_item_aswid_superiorbloodpotion_name";
private const float HealDuration = 8f; private const float HealDuration = 8f;
private const float HealFraction = 0.05f; private const float HealFraction = 0.05f;
@ -54,15 +54,14 @@ namespace RacesOfValheim
SE_BloodPotion superiorDrink = CreateEffect("SE_SuperiorBloodPotion", SuperiorPotionDisplayName, SE_BloodPotion superiorDrink = CreateEffect("SE_SuperiorBloodPotion", SuperiorPotionDisplayName,
SuperiorHealFraction, AswidBloodRefinery.SuperiorEssenceName, "MoltenCore"); SuperiorHealFraction, AswidBloodRefinery.SuperiorEssenceName, "MoltenCore");
GameObject meadBase = CloneItem(BaseName, "MeadBaseHealthMinor", "Blood Potion Mead Base", GameObject meadBase = CloneItem(BaseName, "MeadBaseHealthMinor", "$rov_item_aswid_bloodpotionbase_name",
"Blood, berries and crypt light, waiting on a barrel."); "$rov_item_aswid_bloodpotionbase_desc");
GameObject potion = CloneItem(PotionName, "MeadHealthMinor", PotionDisplayName, GameObject potion = CloneItem(PotionName, "MeadHealthMinor", PotionDisplayName,
"Drink and the hunger stops mattering for a while. Fills every stomach with blood essence, " + "$rov_item_aswid_bloodpotion_desc");
"full or not, and knits the flesh back together."); GameObject superiorBase = CloneItem(SuperiorBaseName, "MeadBaseHealthMedium", "$rov_item_aswid_superiorbloodpotionbase_name",
GameObject superiorBase = CloneItem(SuperiorBaseName, "MeadBaseHealthMedium", "Superior Blood Potion Mead Base", "$rov_item_aswid_superiorbloodpotionbase_desc");
"The twice-rendered draught, still raw.");
GameObject superiorPotion = CloneItem(SuperiorPotionName, "MeadHealthMedium", SuperiorPotionDisplayName, GameObject superiorPotion = CloneItem(SuperiorPotionName, "MeadHealthMedium", SuperiorPotionDisplayName,
"The same mercy, twice as deep."); "$rov_item_aswid_superiorbloodpotion_desc");
AttachEffect(potion, drink); AttachEffect(potion, drink);
AttachEffect(superiorPotion, superiorDrink); AttachEffect(superiorPotion, superiorDrink);
@ -176,7 +175,7 @@ namespace RacesOfValheim
SE_BloodPotion effect = ScriptableObject.CreateInstance<SE_BloodPotion>(); SE_BloodPotion effect = ScriptableObject.CreateInstance<SE_BloodPotion>();
effect.name = name; effect.name = name;
effect.m_name = displayName; effect.m_name = displayName;
effect.m_tooltip = $"Stomachs filled with blood. Healing {Mathf.RoundToInt(fraction * 100f)}% over {HealDuration:0} seconds."; effect.m_tooltip = "$rov_se_aswid_bloodpotion_tooltip"; // numbers go in at display, see GetTooltipString
effect.m_ttl = HealDuration; effect.m_ttl = HealDuration;
effect.m_healFraction = fraction; effect.m_healFraction = fraction;
effect.m_essencePrefab = essencePrefab; effect.m_essencePrefab = essencePrefab;
@ -234,8 +233,11 @@ namespace RacesOfValheim
{ {
if (fermenter == null || GetContentMethod == null) return false; if (fermenter == null || GetContentMethod == null) return false;
string content = GetContentMethod.Invoke(fermenter, null) as string; // Valheim 1.0: GetContent returns the stable hash of the prefab name, not the name. The old
return content == BaseName || content == SuperiorBaseName; // "as string" read null for every barrel and the speed-up silently stopped.
int content = System.Convert.ToInt32(GetContentMethod.Invoke(fermenter, null));
return content != 0
&& (content == BaseName.GetStableHashCode() || content == SuperiorBaseName.GetStableHashCode());
} }
private static Player.Food MakeFood(ItemDrop drop, GameObject prefab, string prefabName) private static Player.Food MakeFood(ItemDrop drop, GameObject prefab, string prefabName)
@ -284,6 +286,19 @@ namespace RacesOfValheim
public float m_healFraction = 0.05f; public float m_healFraction = 0.05f;
public string m_essencePrefab = ""; public string m_essencePrefab = "";
/// <summary>
/// The tooltip's $1 and $2 are the heal share and the duration. Filled in here, at display
/// time, because a translation can only be looked up once the language is loaded, and the
/// game localizes this string after us in a single pass that would leave $1 as it is.
/// </summary>
public override string GetTooltipString()
{
string text = base.GetTooltipString();
if (Localization.instance == null) return text;
return Localization.instance.Localize(text,
Mathf.RoundToInt(m_healFraction * 100f).ToString(), m_ttl.ToString("0"));
}
public override void Setup(Character character) public override void Setup(Character character)
{ {
// SEMan clones the effect before setting it up, so writing the resolved amount here // SEMan clones the effect before setting it up, so writing the resolved amount here

View file

@ -30,10 +30,10 @@ namespace RacesOfValheim
// The Aswid food patches recognise a meal by its display name, so these strings are part // The Aswid food patches recognise a meal by its display name, so these strings are part
// of the contract with AswidPatches - see IsAswidMeal. // of the contract with AswidPatches - see IsAswidMeal.
public const string EssenceDisplayName = "Blood Essence"; public const string EssenceDisplayName = "$rov_item_aswid_bloodessence_name";
public const string SuperiorEssenceDisplayName = "Superior Blood Essence"; public const string SuperiorEssenceDisplayName = "$rov_item_aswid_superiorbloodessence_name";
public const string CoreDisplayName = "Blood Core"; public const string CoreDisplayName = "$rov_item_aswid_bloodcore_name";
public const string PieceDisplayName = "Blood Refinery"; public const string PieceDisplayName = "$rov_piece_aswid_bloodrefinery_name";
// Regeneration is tied to the health value rather than set per tier, so 60 hp gives 5 and // Regeneration is tied to the health value rather than set per tier, so 60 hp gives 5 and
// 80 hp gives 6.67 without a second number to keep in sync. // 80 hp gives 6.67 without a second number to keep in sync.
@ -68,6 +68,7 @@ namespace RacesOfValheim
{ "AsksvinCarrionRibcage", 3 }, { "AsksvinCarrionRibcage", 3 },
{ "AsksvinCarrionSkull", 3 }, { "AsksvinCarrionSkull", 3 },
{ "UndeadBjornRibcage", 3 }, // Deep North { "UndeadBjornRibcage", 3 }, // Deep North
{ "ElakingHairBundle", 20 }, // Deep North, dropped by the Elaking
}; };
// Vanilla grills. Anything they cook counts as raw flesh, which keeps modded meat working. // Vanilla grills. Anything they cook counts as raw flesh, which keeps modded meat working.
@ -94,7 +95,7 @@ namespace RacesOfValheim
public static bool IsAswidMeal(ItemDrop.ItemData item) public static bool IsAswidMeal(ItemDrop.ItemData item)
{ {
if (item == null || item.m_shared == null || item.m_shared.m_name == null) return false; if (item == null || item.m_shared == null || item.m_shared.m_name == null) return false;
return item.m_shared.m_name.StartsWith("Aswid Food:") return item.m_shared.m_name.StartsWith(AswidRace.AswidFoodNamePrefix)
|| item.m_shared.m_name == EssenceDisplayName || item.m_shared.m_name == EssenceDisplayName
|| IsEssence(item); || IsEssence(item);
} }
@ -122,8 +123,7 @@ namespace RacesOfValheim
ItemDrop.ItemData.SharedData shared = drop.m_itemData.m_shared; ItemDrop.ItemData.SharedData shared = drop.m_itemData.m_shared;
shared.m_name = CoreDisplayName; shared.m_name = CoreDisplayName;
shared.m_description = "A knot of clotted blood kept beating by something that is not a heart. " + shared.m_description = "$rov_item_aswid_bloodcore_desc";
"The dead trade them; only the dead know how they are made.";
shared.m_itemType = ItemDrop.ItemData.ItemType.Material; shared.m_itemType = ItemDrop.ItemData.ItemType.Material;
shared.m_food = 0f; shared.m_food = 0f;
shared.m_foodStamina = 0f; shared.m_foodStamina = 0f;
@ -142,8 +142,7 @@ namespace RacesOfValheim
EssencePrefab = BuildEssence( EssencePrefab = BuildEssence(
EssenceName, EssenceName,
EssenceDisplayName, EssenceDisplayName,
"Blood rendered down to what it actually is. The only real food an Aswid can " + "$rov_item_aswid_bloodessence_desc",
"still chew, and the base of every draught worth brewing.",
food: 60f, food: 60f,
tint: EssenceTint, tint: EssenceTint,
iconSource: "GemstoneRed"); iconSource: "GemstoneRed");
@ -151,7 +150,7 @@ namespace RacesOfValheim
SuperiorEssencePrefab = BuildEssence( SuperiorEssencePrefab = BuildEssence(
SuperiorEssenceName, SuperiorEssenceName,
SuperiorEssenceDisplayName, SuperiorEssenceDisplayName,
"The same blood, rendered twice. Darker, thicker, and worth five of the first pass.", "$rov_item_aswid_superiorbloodessence_desc",
food: 80f, food: 80f,
tint: SuperiorEssenceTint, tint: SuperiorEssenceTint,
iconSource: "MoltenCore"); iconSource: "MoltenCore");
@ -234,8 +233,11 @@ namespace RacesOfValheim
refinery.m_haveMeatObject = smelter.m_haveOreObject; refinery.m_haveMeatObject = smelter.m_haveOreObject;
refinery.m_noMeatObject = smelter.m_noOreObject; refinery.m_noMeatObject = smelter.m_noOreObject;
refinery.m_animators = smelter.m_animators; refinery.m_animators = smelter.m_animators;
refinery.m_meatAddedEffects = smelter.m_oreAddedEffects; // Crossed on purpose: the sounds sit the other way round from the slots. The ore
refinery.m_boneAddedEffects = smelter.m_fuelAddedEffects; // effect is the dry clatter and the fuel effect the wet slap, so flesh takes the
// fuel one and bone the ore one.
refinery.m_meatAddedEffects = smelter.m_fuelAddedEffects;
refinery.m_boneAddedEffects = smelter.m_oreAddedEffects;
refinery.m_produceEffects = smelter.m_produceEffects; refinery.m_produceEffects = smelter.m_produceEffects;
refinery.m_smokeSpawner = smelter.m_smokeSpawner; refinery.m_smokeSpawner = smelter.m_smokeSpawner;
@ -243,8 +245,8 @@ namespace RacesOfValheim
// Two Radiators under _enabled are what shot the tester: see IsOffensive. // Two Radiators under _enabled are what shot the tester: see IsOffensive.
StripOffensive(prefab, PieceName); StripOffensive(prefab, PieceName);
SanitiseEffects(refinery.m_meatAddedEffects, PieceName + ".oreAdded"); SanitiseEffects(refinery.m_meatAddedEffects, PieceName + ".fuelAdded");
SanitiseEffects(refinery.m_boneAddedEffects, PieceName + ".fuelAdded"); SanitiseEffects(refinery.m_boneAddedEffects, PieceName + ".oreAdded");
SanitiseEffects(refinery.m_produceEffects, PieceName + ".produce"); SanitiseEffects(refinery.m_produceEffects, PieceName + ".produce");
prefab.transform.localScale = Vector3.one * ModelScale; prefab.transform.localScale = Vector3.one * ModelScale;
@ -264,7 +266,7 @@ namespace RacesOfValheim
PieceConfig config = new PieceConfig PieceConfig config = new PieceConfig
{ {
Name = PieceDisplayName, Name = PieceDisplayName,
Description = "Flesh goes in, bone goes in, and what is left of both comes out red.", Description = "$rov_piece_aswid_bloodrefinery_desc",
PieceTable = PieceTables.Hammer, PieceTable = PieceTables.Hammer,
Category = PieceCategories.Crafting, Category = PieceCategories.Crafting,
Requirements = new[] Requirements = new[]
@ -336,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)
{ {
@ -566,7 +566,7 @@ namespace RacesOfValheim
if (!AswidBloodRefinery.IsEssence(item)) return true; if (!AswidBloodRefinery.IsEssence(item)) return true;
if (AswidRace.IsAswid()) return true; if (AswidRace.IsAswid()) return true;
player.Message(MessageHud.MessageType.Center, "Living blood curdles in a living throat."); player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_aswid_living_blood_curdles_living_throat"));
return false; return false;
} }
} }

View file

@ -20,8 +20,8 @@ namespace RacesOfValheim
public override string RaceId => "Aswid"; public override string RaceId => "Aswid";
public override string ItemName => "AswidBeastClaws"; public override string ItemName => "AswidBeastClaws";
public override string DisplayName => "Claws of the Beast"; public override string DisplayName => "$rov_item_aswid_claws_name";
public override string Description => "Grown in the dark, and darker for it. They do not come off."; public override string Description => "$rov_item_aswid_claws_desc";
// The Bjorn claw first, by name, because that is the one this race is meant to wear. The // The Bjorn claw first, by name, because that is the one this race is meant to wear. The
// rest are the near-identical ids the manifest also carries - see SvermConfig's own // rest are the near-identical ids the manifest also carries - see SvermConfig's own

View file

@ -33,6 +33,82 @@ namespace RacesOfValheim
public static ConfigEntry<float> BloodMagicSkillGainMultiplier; public static ConfigEntry<float> BloodMagicSkillGainMultiplier;
public static ConfigEntry<float> SurtlingFormDamageBonus; public static ConfigEntry<float> SurtlingFormDamageBonus;
// ─── Stamina ─────────────────────────────────────────────────────────────
// The race used to have infinite stamina. Now it has a large pool that grows with each
// boss, on top of what its devoured food gives - added, never assigned, so stamina mods
// still stack.
public static ConfigEntry<float> BaseStaminaBonus;
public static ConfigEntry<float> StaminaBonusPerState;
public static ConfigEntry<float> StaminaCostMultiplier;
// ─── Weaknesses ──────────────────────────────────────────────────────────
// The Discord reports said the race had no real downsides. Each weakness has its own
// switch, so a single player can drop one; on a server the host's values win.
public static ConfigEntry<bool> SunlightEnabled;
public static ConfigEntry<float> SunHealthRegenPenalty;
public static ConfigEntry<float> SunStaminaRegenPenalty;
public static ConfigEntry<float> SunSpeedPenalty;
public static ConfigEntry<float> SunHealthLossPerSecond;
public static ConfigEntry<float> SunHealthFloor;
public static ConfigEntry<bool> FireWeaknessEnabled;
public static ConfigEntry<float> FireWeakness;
public static ConfigEntry<bool> FaderRemovesFireWeakness;
public static ConfigEntry<bool> PierceWeaknessEnabled;
public static ConfigEntry<float> PierceWeakness;
// ─── Running Water ─────────────────────────────────────────────────────
// Lore says a vampire cannot cross running water unaided (Dagaz's report). Swimming costs
// more, and open water - sea, river or lake - burns, swimming or flying over it; a boat
// carries you, which the lore allows, though the camera still sways on board. The camera sway is a per-player comfort choice and stays local
// (ConfigSync's "camera sway" key part).
public static ConfigEntry<bool> RunningWaterEnabled;
public static ConfigEntry<bool> WaterOceanOnly;
public static ConfigEntry<float> SwimStaminaMultiplier;
public static ConfigEntry<float> SeaHealthLossPerSecond;
public static ConfigEntry<float> SeaStaminaDrainPerSecond;
public static ConfigEntry<float> SeaHealthFloor;
public static ConfigEntry<bool> SeaCameraSway;
public static ConfigEntry<float> SeaCameraSwayStrength;
// ─── Bat Form ────────────────────────────────────────────────────────────
// 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
// to carry weight, and ignored by every monster until AswidBatAggro lied to six vanilla
// 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 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> BatGlideSpeed;
public static ConfigEntry<float> BatBoostSpeed;
public static ConfigEntry<float> BatSprintSpeed;
public static ConfigEntry<float> BatReverseSpeed;
public static ConfigEntry<float> BatLiftoffSpeed;
public static ConfigEntry<float> BatHoverSeconds;
public static ConfigEntry<float> BatPoweredStaminaPerSecond;
public static ConfigEntry<float> BatSprintStaminaPerSecond;
public static ConfigEntry<EncumberedMode> BatEncumbered;
public static ConfigEntry<float> BatEncumberedExtraCost;
public static ConfigEntry<float> BatMaxDuration;
public static ConfigEntry<float> BatDurationPerState;
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;
public static ConfigEntry<float> AuraRadiusDay; public static ConfigEntry<float> AuraRadiusDay;
@ -40,6 +116,8 @@ namespace RacesOfValheim
public static ConfigEntry<float> AuraBaseDamage; public static ConfigEntry<float> AuraBaseDamage;
public static ConfigEntry<float> AuraBloodMagicScaling; public static ConfigEntry<float> AuraBloodMagicScaling;
public static ConfigEntry<float> AuraExecuteThreshold; public static ConfigEntry<float> AuraExecuteThreshold;
public static ConfigEntry<bool> AuraInBatForm;
public static ConfigEntry<int> BatAuraUnlockState;
// ─── Superhuman Senses (tier 5+ passive) ───────────────────────────────── // ─── Superhuman Senses (tier 5+ passive) ─────────────────────────────────
public static ConfigEntry<float> SensesRadius; public static ConfigEntry<float> SensesRadius;
@ -54,6 +132,12 @@ namespace RacesOfValheim
// ─── Devour ──────────────────────────────────────────────────────────── // ─── Devour ────────────────────────────────────────────────────────────
public static ConfigEntry<float> DevourCooldown; public static ConfigEntry<float> DevourCooldown;
// What a devoured creature feeds - see AswidRace.ApplyFoodBalance.
public static ConfigEntry<float> DevourHealthMultiplier;
public static ConfigEntry<float> DevourStaminaShare;
public static ConfigEntry<float> EarlyStaminaShare;
public static ConfigEntry<float> FoodCapBase;
public static ConfigEntry<float> FoodCapPerBiome;
// ─── Domination (tier 6+ ability, native Interact key) ─────────────────── // ─── Domination (tier 6+ ability, native Interact key) ───────────────────
public static ConfigEntry<float> EnslaveCooldown; public static ConfigEntry<float> EnslaveCooldown;
@ -122,6 +206,96 @@ namespace RacesOfValheim
SurtlingFormDamageBonus = config.Bind(combat, "Surtling Form Damage Bonus", 30f, SurtlingFormDamageBonus = config.Bind(combat, "Surtling Form Damage Bonus", 30f,
new ConfigDescription("Flat damage added to every attack once the tier 8 Surtling form is unlocked.", new AcceptableValueRange<float>(0f, 100f))); new ConfigDescription("Flat damage added to every attack once the tier 8 Surtling form is unlocked.", new AcceptableValueRange<float>(0f, 100f)));
const string stamina = "Aswid - Stamina";
BaseStaminaBonus = config.Bind(stamina, "Base Stamina Bonus", 25f,
new ConfigDescription("Max stamina added on top of the game's base 75 and your food, before any boss.", new AcceptableValueRange<float>(0f, 300f)));
StaminaBonusPerState = config.Bind(stamina, "Stamina Bonus Per State", 10f,
new ConfigDescription("Max stamina added per progression state (8 at Fader).", new AcceptableValueRange<float>(0f, 50f)));
StaminaCostMultiplier = config.Bind(stamina, "Stamina Cost Multiplier", 1f,
new ConfigDescription("Multiplies every stamina cost: sprinting, swimming, attacks, blocking. 1 is the normal cost, 0.5 half. There is no infinite setting on purpose; set the bonuses above high instead.", new AcceptableValueRange<float>(0.1f, 2f)));
const string weak = "Aswid - Weaknesses";
SunlightEnabled = config.Bind(weak, "Sunlight", true,
new ConfigDescription("Weakens you by day while you stand under open sky. A roof (the same test as the game's Sheltered status), a dungeon, the Swamp, the Mistlands, the night and your own Eclipse all shield you.", null));
SunHealthRegenPenalty = config.Bind(weak, "Sunlight Health Regen Penalty", 0.5f,
new ConfigDescription("Health regeneration lost in sunlight. 0.5 = half.", new AcceptableValueRange<float>(0f, 1f)));
SunStaminaRegenPenalty = config.Bind(weak, "Sunlight Stamina Regen Penalty", 0.25f,
new ConfigDescription("Stamina regeneration lost in sunlight. 0.25 = a quarter.", new AcceptableValueRange<float>(0f, 1f)));
SunSpeedPenalty = config.Bind(weak, "Sunlight Speed Penalty", 0.1f,
new ConfigDescription("Movement speed lost in sunlight. 0.1 = 10% slower.", new AcceptableValueRange<float>(0f, 0.9f)));
SunHealthLossPerSecond = config.Bind(weak, "Sunlight Health Loss Per Second", 0.5f,
new ConfigDescription("Health the sun burns away each second. 0 turns it off.", new AcceptableValueRange<float>(0f, 10f)));
SunHealthFloor = config.Bind(weak, "Sunlight Health Floor", 0.3f,
new ConfigDescription("The sun stops burning at this fraction of your max health, so it weakens you but never kills you. 0.3 = 30%.", new AcceptableValueRange<float>(0f, 1f)));
FireWeaknessEnabled = config.Bind(weak, "Fire Weakness", true,
new ConfigDescription("Fire, burning included, hurts more.", null));
FireWeakness = config.Bind(weak, "Fire Weakness Amount", 0.25f,
new ConfigDescription("Extra fire damage taken. 0.25 = 25% more. Resistance meads and armour still reduce it.", new AcceptableValueRange<float>(0f, 2f)));
FaderRemovesFireWeakness = config.Bind(weak, "Fader Removes Fire Weakness", true,
new ConfigDescription("Defeating Fader, the boss that grants the Surtling form, ends the fire weakness.", null));
PierceWeaknessEnabled = config.Bind(weak, "Pierce Weakness", true,
new ConfigDescription("Pierce damage (arrows, spears, stakes) hurts more. Mist Form's immunity still wins.", null));
PierceWeakness = config.Bind(weak, "Pierce Weakness Amount", 0.2f,
new ConfigDescription("Extra pierce damage taken. 0.2 = 20% more.", new AcceptableValueRange<float>(0f, 2f)));
const string water = "Aswid - Running Water";
RunningWaterEnabled = config.Bind(water, "Running Water", true,
new ConfigDescription("Swimming costs more stamina, and open water - the sea, rivers, lakes - hurts you while you swim in it or fly over it. Standing on, steering or sitting in a boat protects you. Wading, docks and bridges are safe.", null));
WaterOceanOnly = config.Bind(water, "Ocean Only", false,
new ConfigDescription("Limits the burn, the drain and the camera sway to the Ocean biome, leaving rivers and lakes alone. The swim stamina cost applies everywhere either way.", null));
SwimStaminaMultiplier = config.Bind(water, "Swim Stamina Multiplier", 2f,
new ConfigDescription("Multiplies the stamina swimming costs, anywhere. At 0 stamina the game's own drowning starts. Around 5 and up, swimming any distance is no longer possible.", new AcceptableValueRange<float>(1f, 10f)));
SeaHealthLossPerSecond = config.Bind(water, "Open Water Health Loss Per Second", 1f,
new ConfigDescription("Health open water burns away each second.", new AcceptableValueRange<float>(0f, 20f)));
SeaStaminaDrainPerSecond = config.Bind(water, "Open Water Stamina Drain Per Second", 2f,
new ConfigDescription("Stamina open water drains each second, on top of what swimming or flying costs.", new AcceptableValueRange<float>(0f, 30f)));
SeaHealthFloor = config.Bind(water, "Open Water Health Floor", 0.1f,
new ConfigDescription("The water's burn stops at this fraction of your max health. Drowning, once your stamina runs out, has no floor.", new AcceptableValueRange<float>(0f, 1f)));
SeaCameraSway = config.Bind(water, "Camera Sway", true,
new ConfigDescription("The camera rolls gently while you are out on the water, on a boat too, as if seasick. Local: each player chooses for themselves.", null));
SeaCameraSwayStrength = config.Bind(water, "Camera Sway Strength", 1f,
new ConfigDescription("How far the camera rolls. 1 is about 4 degrees. Local.", new AcceptableValueRange<float>(0f, 3f)));
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
// sprints, S beats backwards, and letting go hovers briefly before gliding down.
BatTurnSpeed = config.Bind(batform, "Turn Speed", 180f,
new ConfigDescription("Degrees per second the bat turns towards where you aim.", new AcceptableValueRange<float>(30f, 720f)));
BatGlideSpeed = config.Bind(batform, "Glide Speed", 6f,
new ConfigDescription("Speed while gliding down with no key held, in m/s.", new AcceptableValueRange<float>(0f, 30f)));
// Not "Flight Speed": that key held the old debug-fly multiplier, and an existing .cfg
// would load its 1 here as one metre per second.
BatBoostSpeed = config.Bind(batform, "Boost Speed", 13f,
new ConfigDescription("Speed while holding W, in m/s. Costs the powered stamina below.", new AcceptableValueRange<float>(0f, 60f)));
BatSprintSpeed = config.Bind(batform, "Sprint Speed", 24f,
new ConfigDescription("Speed while holding W and Shift, in m/s. Costs the sprint stamina on top. The old bat flew at 50.", new AcceptableValueRange<float>(0f, 80f)));
BatReverseSpeed = config.Bind(batform, "Reverse Speed", 8f,
new ConfigDescription("Speed while holding S, in m/s. Costs the powered stamina.", new AcceptableValueRange<float>(0f, 40f)));
BatLiftoffSpeed = config.Bind(batform, "Liftoff Speed", 9f,
new ConfigDescription("Climb speed out of water, in m/s. Always free, so a bat that touches the sea can still leave it.", new AcceptableValueRange<float>(0f, 30f)));
BatHoverSeconds = config.Bind(batform, "Hover Seconds", 3f,
new ConfigDescription("How long the bat holds its height after the last powered beat before it starts to glide down.", new AcceptableValueRange<float>(0f, 30f)));
BatPoweredStaminaPerSecond = config.Bind(batform, "Flight Stamina Per Second", 3f,
new ConfigDescription("Stamina per second while holding W or S. Out of stamina, the bat can only glide. 0 makes flight free, like the drake's.", new AcceptableValueRange<float>(0f, 60f)));
BatSprintStaminaPerSecond = config.Bind(batform, "Sprint Stamina Per Second", 12f,
new ConfigDescription("Extra stamina per second while sprinting, on top of the flight cost.", new AcceptableValueRange<float>(0f, 60f)));
BatEncumbered = config.Bind(batform, "While Encumbered", EncumberedMode.Allowed,
new ConfigDescription("Allowed: the bat flies while you carry too much, at the extra stamina cost below. Blocked: you cannot take bat form while encumbered, and a bat that becomes encumbered in the air can only glide down.", null));
BatEncumberedExtraCost = config.Bind(batform, "Encumbered Extra Stamina Cost", 0.15f,
new ConfigDescription("With 'Allowed' above: how much more flight and sprint cost while encumbered. 0.15 = 15% more.", new AcceptableValueRange<float>(0f, 1f)));
BatMaxDuration = config.Bind(batform, "Max Duration", 0f,
new ConfigDescription("Seconds the bat form lasts before you turn back on your own. 0 means no limit: stamina is the limit.", new AcceptableValueRange<float>(0f, 3600f)));
BatDurationPerState = config.Bind(batform, "Duration Per State", 0f,
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,
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,
new ConfigDescription("Seconds between aura damage/lifesteal ticks.", new AcceptableValueRange<float>(0.05f, 2f))); new ConfigDescription("Seconds between aura damage/lifesteal ticks.", new AcceptableValueRange<float>(0.05f, 2f)));
@ -135,6 +309,10 @@ namespace RacesOfValheim
new ConfigDescription("Extra damage per tick at 100 Blood Magic skill (scales linearly from 0).", new AcceptableValueRange<float>(0f, 20f))); new ConfigDescription("Extra damage per tick at 100 Blood Magic skill (scales linearly from 0).", new AcceptableValueRange<float>(0f, 20f)));
AuraExecuteThreshold = config.Bind(aura, "Execute Threshold", 0.20f, AuraExecuteThreshold = config.Bind(aura, "Execute Threshold", 0.20f,
new ConfigDescription("Non-boss enemies at or below this fraction of max health are executed by the aura instead of merely damaged.", new AcceptableValueRange<float>(0f, 1f))); new ConfigDescription("Non-boss enemies at or below this fraction of max health are executed by the aura instead of merely damaged.", new AcceptableValueRange<float>(0f, 1f)));
AuraInBatForm = config.Bind(aura, "Active In Bat Form", false,
new ConfigDescription("Lets the aura drain while you are a bat from the start, as it did before. Off: the bat has no aura until the unlock state below.", null));
BatAuraUnlockState = config.Bind(aura, "Bat Form Unlock State", 7,
new ConfigDescription("The progression state at which the bat gets its aura back (7 = The Queen). 0 means never, so only the setting above can turn it on.", new AcceptableValueRange<int>(0, 8)));
const string senses = "Aswid - Superhuman Senses"; const string senses = "Aswid - Superhuman Senses";
SensesRadius = config.Bind(senses, "Detection Radius", 100f, SensesRadius = config.Bind(senses, "Detection Radius", 100f,
@ -156,7 +334,24 @@ namespace RacesOfValheim
const string devour = "Aswid - Devour"; const string devour = "Aswid - Devour";
DevourCooldown = config.Bind(devour, "Consume Cooldown", 5f, DevourCooldown = config.Bind(devour, "Consume Cooldown", 5f,
new ConfigDescription("Minimum seconds between devouring a corpse, outside of an execute (which bypasses this).", new AcceptableValueRange<float>(0f, 60f))); new ConfigDescription("How long one body stays drunk-dry, in seconds. A single death is reported to the devour more than once - by two damage patches, by the aura's execute, by a thrall's kill - and this is the window that keeps those from feeding you twice off the same corpse. It is per body, not per player: killing a whole pack at once devours every one of them. One second is used as the floor, so no corpse feeds you twice even at 0.", new AcceptableValueRange<float>(0f, 60f)));
DevourHealthMultiplier = config.Bind(devour, "Health Multiplier", 0.9f,
new ConfigDescription("Scales the health every devoured creature feeds you. 1 is the old amount.", new AcceptableValueRange<float>(0f, 2f)));
DevourStaminaShare = config.Bind(devour, "Stamina Share", 0.10f,
new ConfigDescription("Fraction of that health turned into stamina instead, for creatures past the Black Forest. 0.1 = 10%.", new AcceptableValueRange<float>(0f, 1f)));
EarlyStaminaShare = config.Bind(devour, "Early Creature Stamina Share", 0.60f,
new ConfigDescription("The same, for Meadows and Black Forest creatures. Above 0.5 they feed more stamina than health. Set it equal to the one above to treat every creature alike.", new AcceptableValueRange<float>(0f, 1f)));
FoodCapBase = config.Bind(devour, "Food Health Cap Base", 15f,
new ConfigDescription("Creatures with no hand-set meal feed half their health. That is capped at this plus the per-biome value times the biome's number (Meadows 1 ... Deep North 8). With the defaults: Black Forest 45, Mountains 75, Plains 90.", new AcceptableValueRange<float>(0f, 150f)));
FoodCapPerBiome = config.Bind(devour, "Food Health Cap Per Biome", 15f,
new ConfigDescription("See the base cap above.", new AcceptableValueRange<float>(0f, 50f)));
// Jotunn's server sync assigns Value, which fires SettingChanged, so the server's
// numbers reach the foods the same way a local drag does.
foreach (var entry in new[] { DevourHealthMultiplier, DevourStaminaShare, EarlyStaminaShare, FoodCapBase, FoodCapPerBiome })
{
entry.SettingChanged += (_, __) => AswidRace.ApplyAllFoodBalance();
}
const string domination = "Aswid - Domination"; const string domination = "Aswid - Domination";
EnslaveCooldown = config.Bind(domination, "Enslave Cooldown", 900f, EnslaveCooldown = config.Bind(domination, "Enslave Cooldown", 900f,
@ -281,7 +476,7 @@ namespace RacesOfValheim
new ConfigDescription("As above, around the third axis. The default half turn is what rights the borrowed socket, which arrives upside down on a player's head bone.", new ConfigDescription("As above, around the third axis. The default half turn is what rights the borrowed socket, which arrives upside down on a player's head bone.",
new AcceptableValueRange<float>(-180f, 180f), new ConfigurationManagerAttributes { Order = 58 })); new AcceptableValueRange<float>(-180f, 180f), new ConfigurationManagerAttributes { Order = 58 }));
EyeSmoke = config.Bind(eyes, "Eye Smoke", true, EyeSmoke = config.Bind(eyes, "Eye Smoke", false,
new ConfigDescription("Lights the smoke the creature carries inside its own sockets and leaves switched off. Tinted to match the eyes, so it turns with them at the last stage.", new ConfigDescription("Lights the smoke the creature carries inside its own sockets and leaves switched off. Tinted to match the eyes, so it turns with them at the last stage.",
null, new ConfigurationManagerAttributes { Order = 50 })); null, new ConfigurationManagerAttributes { Order = 50 }));
EyeFlatColorShader = config.Bind(eyes, "Eye Flat Colour Shader", false, EyeFlatColorShader = config.Bind(eyes, "Eye Flat Colour Shader", false,

View file

@ -53,7 +53,9 @@ namespace RacesOfValheim
[HarmonyPatch(typeof(SEMan), "AddStatusEffect", new System.Type[] { typeof(int), typeof(bool), typeof(int), typeof(float) })] // Valheim 1.0 appended a 'short variant' parameter to this overload. The type array has to
// match it exactly or the patch silently fails to bind and PatchAll throws.
[HarmonyPatch(typeof(SEMan), "AddStatusEffect", new System.Type[] { typeof(int), typeof(bool), typeof(int), typeof(float), typeof(short) })]
public static class AswidSEManPatch public static class AswidSEManPatch
{ {
public static bool Prefix(SEMan __instance, ref int nameHash) public static bool Prefix(SEMan __instance, ref int nameHash)
@ -217,6 +219,32 @@ namespace RacesOfValheim
} }
} }
/// <summary>
/// Fire and pierce hurt the Aswid more: fire for the old way vampires end, pierce for the
/// stake. A plain multiplier, like the Trol's fire weakness, rather than DamageModifier.Weak,
/// which is a fixed +50% with nothing in between. ApplyDamage runs after resistances, so a
/// fire resistance mead still helps, and Mist Form's pierce immunity has already zeroed the
/// pierce by the time this sees it.
/// </summary>
[HarmonyPatch(typeof(Character), "ApplyDamage")]
public static class Aswid_Weakness_Patch
{
public static void Prefix(Character __instance, ref HitData hit)
{
if (__instance != Player.m_localPlayer || !AswidRace.IsAswid()) return;
if (AswidRace.HasFireWeakness(BossProgressionManager.GetCurrentProgressionState()) && hit.m_damage.m_fire > 0f)
{
hit.m_damage.m_fire *= 1f + AswidConfig.FireWeakness.Value;
}
if (AswidConfig.PierceWeaknessEnabled.Value && hit.m_damage.m_pierce > 0f)
{
hit.m_damage.m_pierce *= 1f + AswidConfig.PierceWeakness.Value;
}
}
}
[HarmonyPatch(typeof(Humanoid), "StartAttack")] [HarmonyPatch(typeof(Humanoid), "StartAttack")]
public static class Aswid_Attack_Patch public static class Aswid_Attack_Patch
{ {
@ -237,6 +265,33 @@ namespace RacesOfValheim
} }
} }
/// <summary>
/// Bat and mist form shut the rest of the human's attack loop as well as StartAttack: crossbow
/// reload and draw live in PlayerAttackInput, and the form's Animator fires the held attack
/// through OnAttackTrigger. See Fenrir's BlockPlayerAttackInputPatch.
/// </summary>
public static class AswidFormAttackLoop
{
public static bool InForm(Humanoid player)
{
if (player != Player.m_localPlayer) return false;
return player.GetComponentInChildren<BatFormBehavior>() != null
|| player.GetSEMan().HaveStatusEffect("SE_MistForm".GetStableHashCode());
}
}
[HarmonyPatch(typeof(Player), "PlayerAttackInput")]
public static class Aswid_BlockAttackInput_Patch
{
public static bool Prefix(Player __instance) => !AswidFormAttackLoop.InForm(__instance);
}
[HarmonyPatch(typeof(Humanoid), nameof(Humanoid.OnAttackTrigger))]
public static class Aswid_BlockAttackTrigger_Patch
{
public static bool Prefix(Humanoid __instance) => !AswidFormAttackLoop.InForm(__instance);
}
[HarmonyPatch(typeof(Character), "SetRun")] [HarmonyPatch(typeof(Character), "SetRun")]
public static class Aswid_Run_Patch public static class Aswid_Run_Patch
{ {
@ -312,14 +367,11 @@ namespace RacesOfValheim
} }
} }
if (canRefresh) // Otherwise vanilla's answer stands: it already allows replacing the
{ // most depleted meal past half its time, and already showed its "too
__result = true; // full" message when it refused. Forcing false here used to block
} // that replacement, silently.
else if (canRefresh) __result = true;
{
__result = false; // Nessuno spazio disponibile, cibo si disintegra
}
} }
} }
else else
@ -381,16 +433,10 @@ namespace RacesOfValheim
Player.Food f = foodObj as Player.Food; Player.Food f = foodObj as Player.Food;
if (f != null && f.m_item.m_shared.m_name == item.m_shared.m_name && f.CanEatAgain()) if (f != null && f.m_item.m_shared.m_name == item.m_shared.m_name && f.CanEatAgain())
{ {
f.m_time = 0f; // Was `f.m_time = 0f`, which expired the meal instead of renewing
f.m_item = item; // it - see RaceFoodRefresh for the whole story. The fourth slot
// above genuinely does count up from zero; this list does not.
var consumeEffects = HarmonyLib.Traverse.Create(__instance).Field("m_consumeItemEffects").GetValue<EffectList>(); RaceFoodRefresh.Refresh(__instance, f, item);
if (consumeEffects != null) consumeEffects.Create(__instance.transform.position, Quaternion.identity, __instance.transform, 1f, -1);
var zanim = HarmonyLib.Traverse.Create(__instance).Field("m_zanim").GetValue<ZSyncAnimation>();
if (zanim != null) zanim.SetTrigger("eat");
if (item.m_shared.m_food > 0f) __instance.Heal(item.m_shared.m_food, true);
refreshed = true; refreshed = true;
break; break;
@ -403,9 +449,9 @@ namespace RacesOfValheim
return false; return false;
} }
// Se pieno e senza 4° slot disponibile, fallisce e disintegra // Full, no fourth slot free, no slot holding this meal. Native EatFood
__result = false; // replaces the most depleted meal past half its time, or refuses.
return false; return true;
} }
else else
{ {
@ -467,7 +513,7 @@ namespace RacesOfValheim
// AswidConfig.TameKey) - the hint never matched the working key, and would have // AswidConfig.TameKey) - the hint never matched the working key, and would have
// gone stale again the moment that key was rebound. MainKey.ToString() reads back // gone stale again the moment that key was rebound. MainKey.ToString() reads back
// whatever is actually bound. // whatever is actually bound.
__result += $"\n[<color=yellow><b>{AswidConfig.TameKey.Value.MainKey}</b></color>] Tame"; __result += ModText.Get("rov_hover_aswid_tame", AswidConfig.TameKey.Value.MainKey);
} }
} }
} }
@ -477,7 +523,7 @@ namespace RacesOfValheim
{ {
public static bool Prefix(Hud __instance, Player player) public static bool Prefix(Hud __instance, Player player)
{ {
if (player == Player.m_localPlayer && (AswidRace.IsAswid() || DraughRace.IsDraugh())) if (player == Player.m_localPlayer && DraughRace.IsDraugh())
{ {
if (__instance.m_staminaBar2Root != null && __instance.m_staminaBar2Root.gameObject.activeSelf) if (__instance.m_staminaBar2Root != null && __instance.m_staminaBar2Root.gameObject.activeSelf)
{ {
@ -485,6 +531,15 @@ namespace RacesOfValheim
} }
return false; return false;
} }
// Vanilla switches the bar on once, when the HUD is built, and never again. Without
// this a player who left the Draugh had no stamina bar until relog - and an Aswid
// updating from a version that still hid it would have none either.
if (player == Player.m_localPlayer && __instance.m_staminaBar2Root != null
&& !__instance.m_staminaBar2Root.gameObject.activeSelf)
{
__instance.m_staminaBar2Root.gameObject.SetActive(true);
}
return true; return true;
} }
} }
@ -506,9 +561,9 @@ namespace RacesOfValheim
__instance.m_icon = null; __instance.m_icon = null;
} }
__instance.m_name = "Night Aura"; __instance.m_name = "$rov_se_aswid_nightaura_name";
__instance.m_startMessage = ""; // "The darkness empowers you."; __instance.m_startMessage = ""; // "The darkness empowers you.";
__instance.m_tooltip = "The cold strengthens your beastly senses."; __instance.m_tooltip = "$rov_se_aswid_nightaura_tooltip";
if (__instance is SE_Stats stats) if (__instance is SE_Stats stats)
{ {
@ -533,7 +588,7 @@ namespace RacesOfValheim
{ {
AswidRace.DevourEnabled = !AswidRace.DevourEnabled; AswidRace.DevourEnabled = !AswidRace.DevourEnabled;
AswidRace.AuraEnabled = AswidRace.DevourEnabled; AswidRace.AuraEnabled = AswidRace.DevourEnabled;
string msg = AswidRace.DevourEnabled ? "Vampiric Aura: ENABLED" : "Vampiric Aura: DISABLED"; string msg = ModText.Get(AswidRace.DevourEnabled ? "rov_msg_aswid_aura_enabled" : "rov_msg_aswid_aura_disabled");
__instance.Message(MessageHud.MessageType.Center, msg); __instance.Message(MessageHud.MessageType.Center, msg);
} }
@ -570,6 +625,13 @@ namespace RacesOfValheim
bool isBat = nview.GetZDO().GetBool("Aswid_IsBatForm", false); bool isBat = nview.GetZDO().GetBool("Aswid_IsBatForm", false);
bool isMist = nview.GetZDO().GetBool("Aswid_IsMistForm", false); bool isMist = nview.GetZDO().GetBool("Aswid_IsMistForm", false);
// The bat flies on m_flying, which only the bat's own client sets. Mirror it here
// and switch gravity off for the duration, or this copy sinks to the terrain
// whatever altitude is replicated - the same fix ZdoVisualSync applies to drakes.
HarmonyLib.Traverse.Create(player).Field("m_flying").SetValue(isBat);
Rigidbody body = player.GetComponent<Rigidbody>();
if (body != null && body.useGravity == isBat) body.useGravity = !isBat;
Transform playerVisual = player.transform.Find("Visual"); Transform playerVisual = player.transform.Find("Visual");
// Bat logic // Bat logic
@ -792,6 +854,104 @@ namespace RacesOfValheim
stamina += extraFood.m_stamina; stamina += extraFood.m_stamina;
eitr += extraFood.m_eitr; eitr += extraFood.m_eitr;
} }
// Added on top of whatever vanilla and other mods put here, never assigned: a mod that
// raises max stamina has to keep raising it for an Aswid too.
stamina += AswidRace.GetStaminaBonus(BossProgressionManager.GetCurrentProgressionState());
}
}
/// <summary>
/// The Aswid's stamina. It used to be infinite: the Skeleton's UseStamina skip covered the
/// Aswid too, which made every stamina mod, food and skill meaningless for the race (the Discord
/// reports that started the rebalance). The cost is now scaled rather than skipped, so the
/// call still reaches vanilla - and any other mod patching it - with a smaller number.
/// </summary>
[HarmonyPatch(typeof(Player), "UseStamina")]
public static class Aswid_UseStamina_Patch
{
public static void Prefix(Player __instance, ref float v)
{
if (__instance != Player.m_localPlayer || !AswidRace.IsAswid()) return;
v *= AswidConfig.StaminaCostMultiplier.Value;
if (Aswid_SwimCost_Patch.Swimming && AswidConfig.RunningWaterEnabled.Value)
{
v *= AswidConfig.SwimStaminaMultiplier.Value;
}
}
}
/// <summary>
/// Marks the frames where vanilla charges for a swim stroke, so Aswid_UseStamina_Patch can
/// make that one cost dearer. Player.OnSwimming is the only place swimming spends stamina,
/// and it also runs the drowning check right after - which is what makes a high multiplier
/// play as "cannot swim" without any code of ours deciding who drowns.
/// </summary>
[HarmonyPatch(typeof(Player), "OnSwimming")]
public static class Aswid_SwimCost_Patch
{
public static bool Swimming { get; private set; }
public static void Prefix(Player __instance)
{
Swimming = __instance == Player.m_localPlayer;
}
public static void Finalizer()
{
Swimming = false;
}
}
/// <summary>
/// The seasick camera: a slow roll while the Aswid is out on the water, on a boat too. Applied after
/// vanilla has settled the camera's rotation for the frame, as a roll around the view axis,
/// so it never moves where the player aims - only how the horizon sits.
/// </summary>
[HarmonyPatch(typeof(GameCamera), "GetCameraPosition")]
public static class Aswid_SeaCameraSway_Patch
{
private const float DegreesAtStrengthOne = 4f;
private static float sway;
public static void Postfix(float dt, ref Quaternion rot)
{
bool on = AswidRace.OnWater && AswidConfig.SeaCameraSway.Value && AswidRace.IsAswid() &&
Player.m_localPlayer != null && !Player.m_localPlayer.IsDead();
// Eased in and out over about a second, so leaving the sea does not snap the horizon.
sway = Mathf.MoveTowards(sway, on ? 1f : 0f, dt);
if (sway <= 0f) return;
float t = Time.time;
float roll = (Mathf.Sin(t * 0.9f) + 0.4f * Mathf.Sin(t * 2.3f)) * DegreesAtStrengthOne *
AswidConfig.SeaCameraSwayStrength.Value * sway;
rot *= Quaternion.AngleAxis(roll, Vector3.forward);
}
}
/// <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;
} }
} }

File diff suppressed because it is too large Load diff

View file

@ -156,8 +156,8 @@ namespace RacesOfValheim
ItemDrop itemDrop = clone.GetComponent<ItemDrop>(); ItemDrop itemDrop = clone.GetComponent<ItemDrop>();
if (itemDrop == null) return false; if (itemDrop == null) return false;
itemDrop.m_itemData.m_shared.m_name = "Spectral Claw"; itemDrop.m_itemData.m_shared.m_name = "$rov_item_aswid_spectralclaw_name";
itemDrop.m_itemData.m_shared.m_description = "A claw of pure shadow, bound to your rage rather than your grip."; itemDrop.m_itemData.m_shared.m_description = "$rov_item_aswid_spectralclaw_desc";
itemDrop.m_itemData.m_shared.m_weight = 0f; itemDrop.m_itemData.m_shared.m_weight = 0f;
itemDrop.m_itemData.m_shared.m_useDurability = false; itemDrop.m_itemData.m_shared.m_useDurability = false;
itemDrop.m_itemData.m_shared.m_questItem = true; // undroppable, unsellable itemDrop.m_itemData.m_shared.m_questItem = true; // undroppable, unsellable

View file

@ -11,8 +11,8 @@ namespace RacesOfValheim
{ {
base.Setup(character); base.Setup(character);
name = "SE_AswidStats"; name = "SE_AswidStats";
m_name = "Benedictus et Afflictus"; m_name = "$rov_se_aswid_stats_name";
m_tooltip = "Vampiric senses and life drain."; m_tooltip = "$rov_se_aswid_stats_tooltip";
} }
public void UpdateStats(int state) public void UpdateStats(int state)
@ -59,20 +59,59 @@ namespace RacesOfValheim
{ {
base.Setup(character); base.Setup(character);
name = "SE_BatForm"; name = "SE_BatForm";
m_name = "Like a Bat out of Hell"; m_name = "$rov_se_aswid_batform_name";
m_tooltip = "You have taken the form of a Bat. You can fly, but cannot attack."; m_tooltip = "$rov_se_aswid_batform_tooltip";
m_fallDamageModifier = -1f; // Immune to fall damage just in case m_fallDamageModifier = -1f; // Immune to fall damage just in case
} }
} }
/// <summary>
/// Sunlight on an exposed Aswid. Its numbers are rewritten from AswidConfig every time
/// AswidRace.UpdateSunlight runs, so a slider moves them live; the health loss is not a stat
/// and is applied by that same tick.
/// </summary>
public class SE_AswidSunlight : SE_Stats
{
public override void Setup(Character character)
{
base.Setup(character);
name = "SE_AswidSunlight";
m_name = "$rov_se_aswid_sunlight_name";
m_tooltip = "$rov_se_aswid_sunlight_tooltip";
Refresh();
}
public void Refresh()
{
m_healthRegenMultiplier = 1f - AswidConfig.SunHealthRegenPenalty.Value;
m_staminaRegenMultiplier = 1f - AswidConfig.SunStaminaRegenPenalty.Value;
m_speedModifier = -AswidConfig.SunSpeedPenalty.Value;
}
}
/// <summary>
/// Open water under an Aswid off a boat. Only a marker: the burn and the drain are applied by
/// AswidRace.UpdateOpenSea, and the camera sway reads AswidRace.OnWater.
/// </summary>
public class SE_AswidOpenSea : SE_Stats
{
public override void Setup(Character character)
{
base.Setup(character);
name = "SE_AswidOpenSea";
m_name = "$rov_se_aswid_opensea_name";
m_tooltip = "$rov_se_aswid_opensea_tooltip";
}
}
public class SE_MistForm : SE_Stats public class SE_MistForm : SE_Stats
{ {
public override void Setup(Character character) public override void Setup(Character character)
{ {
base.Setup(character); base.Setup(character);
name = "SE_MistForm"; name = "SE_MistForm";
m_name = "Weight of Shadows"; m_name = "$rov_se_aswid_mistform_name";
m_tooltip = "You are mist. Immune to physical damage and poison. Cannot attack or run."; m_tooltip = "$rov_se_aswid_mistform_tooltip";
m_fallDamageModifier = -1f; m_fallDamageModifier = -1f;
m_mods = new System.Collections.Generic.List<HitData.DamageModPair> m_mods = new System.Collections.Generic.List<HitData.DamageModPair>
{ {
@ -90,7 +129,7 @@ namespace RacesOfValheim
{ {
base.Setup(character); base.Setup(character);
name = "SE_AswidSensesMark"; name = "SE_AswidSensesMark";
m_name = "Sensed"; m_name = "$rov_se_aswid_sensed_name";
m_tooltip = ""; m_tooltip = "";
m_ttl = 2f; m_ttl = 2f;
m_icon = null; // No icon needed for mobs m_icon = null; // No icon needed for mobs
@ -103,8 +142,8 @@ namespace RacesOfValheim
{ {
base.Setup(character); base.Setup(character);
name = "SE_SuperhumanSenses"; name = "SE_SuperhumanSenses";
m_name = "Auspex"; m_name = "$rov_se_aswid_auspex_name";
m_tooltip = "Sensing life force of nearby creatures."; m_tooltip = "$rov_se_aswid_auspex_tooltip";
} }
} }
@ -114,16 +153,26 @@ namespace RacesOfValheim
{ {
var aswidStats = ScriptableObject.CreateInstance<SE_AswidStats>(); var aswidStats = ScriptableObject.CreateInstance<SE_AswidStats>();
aswidStats.name = "SE_AswidStats"; aswidStats.name = "SE_AswidStats";
aswidStats.m_icon = PrefabManager.Cache.GetPrefab<ItemDrop>("TrophyBat")?.m_itemData.m_shared.m_icons[0]; aswidStats.m_icon = PrefabManager.Cache.GetPrefab<ItemDrop>("TrophyDeathsquito")?.m_itemData.m_shared.m_icons[0];
ItemManager.Instance.AddStatusEffect(new CustomStatusEffect(aswidStats, fixReference: false)); ItemManager.Instance.AddStatusEffect(new CustomStatusEffect(aswidStats, fixReference: false));
var batForm = ScriptableObject.CreateInstance<SE_BatForm>(); var batForm = ScriptableObject.CreateInstance<SE_BatForm>();
batForm.name = "SE_BatForm"; batForm.name = "SE_BatForm";
batForm.m_icon = PrefabManager.Cache.GetPrefab<ItemDrop>("TrophyBat")?.m_itemData.m_shared.m_icons[0]; batForm.m_icon = PrefabManager.Cache.GetPrefab<ItemDrop>("TrophyDeathsquito")?.m_itemData.m_shared.m_icons[0];
ItemManager.Instance.AddStatusEffect(new CustomStatusEffect(batForm, fixReference: false)); ItemManager.Instance.AddStatusEffect(new CustomStatusEffect(batForm, fixReference: false));
var sunlight = ScriptableObject.CreateInstance<SE_AswidSunlight>();
sunlight.name = "SE_AswidSunlight";
sunlight.m_icon = PrefabManager.Cache.GetPrefab<ItemDrop>("TrophySurtling")?.m_itemData.m_shared.m_icons[0];
ItemManager.Instance.AddStatusEffect(new CustomStatusEffect(sunlight, fixReference: false));
var openSea = ScriptableObject.CreateInstance<SE_AswidOpenSea>();
openSea.name = "SE_AswidOpenSea";
openSea.m_icon = PrefabManager.Cache.GetPrefab<ItemDrop>("TrophySerpent")?.m_itemData.m_shared.m_icons[0];
ItemManager.Instance.AddStatusEffect(new CustomStatusEffect(openSea, fixReference: false));
var mistForm = ScriptableObject.CreateInstance<SE_MistForm>(); var mistForm = ScriptableObject.CreateInstance<SE_MistForm>();
mistForm.name = "SE_MistForm"; mistForm.name = "SE_MistForm";
mistForm.m_icon = PrefabManager.Cache.GetPrefab<ItemDrop>("TrophyWraith")?.m_itemData.m_shared.m_icons[0]; mistForm.m_icon = PrefabManager.Cache.GetPrefab<ItemDrop>("TrophyWraith")?.m_itemData.m_shared.m_icons[0];
@ -132,7 +181,7 @@ namespace RacesOfValheim
var sensesMark = ScriptableObject.CreateInstance<SE_AswidSensesMark>(); var sensesMark = ScriptableObject.CreateInstance<SE_AswidSensesMark>();
sensesMark.name = "SE_AswidSensesMark"; sensesMark.name = "SE_AswidSensesMark";
sensesMark.m_name = "Sensed"; sensesMark.m_name = "$rov_se_aswid_sensed_name";
sensesMark.m_ttl = 2f; sensesMark.m_ttl = 2f;
ItemManager.Instance.AddStatusEffect(new CustomStatusEffect(sensesMark, fixReference: false)); ItemManager.Instance.AddStatusEffect(new CustomStatusEffect(sensesMark, fixReference: false));

View file

@ -81,12 +81,12 @@ namespace RacesOfValheim
if (m_ai.GetFollowTarget() == user.gameObject) if (m_ai.GetFollowTarget() == user.gameObject)
{ {
m_ai.SetFollowTarget(null); m_ai.SetFollowTarget(null);
user.Message(MessageHud.MessageType.Center, $"{m_character.m_name} is staying."); user.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_aswid_staying", m_character.m_name));
} }
else else
{ {
m_ai.SetFollowTarget(user.gameObject); m_ai.SetFollowTarget(user.gameObject);
user.Message(MessageHud.MessageType.Center, $"{m_character.m_name} is following."); user.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_aswid_following", m_character.m_name));
} }
} }
return true; return true;
@ -98,7 +98,7 @@ namespace RacesOfValheim
float cooldown = AswidRace.GetEnslaveCooldown(); float cooldown = AswidRace.GetEnslaveCooldown();
if (cooldown > 0) if (cooldown > 0)
{ {
user.Message(MessageHud.MessageType.Center, $"Dominate on cooldown ({Mathf.CeilToInt(cooldown / 60f)}m {Mathf.CeilToInt(cooldown % 60f)}s)"); user.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_aswid_dominate_cooldown_m_s", Mathf.CeilToInt(cooldown / 60f), Mathf.CeilToInt(cooldown % 60f)));
return false; return false;
} }
@ -117,10 +117,13 @@ namespace RacesOfValheim
m_ai.SetFollowTarget(user.gameObject); m_ai.SetFollowTarget(user.gameObject);
} }
GameObject vfx = ZNetScene.instance.GetPrefab("vfx_surtling_death"); // "vfx_surtling_death" was asked for here and is not a prefab in this game, so dominating
// a creature happened with no effect at all. The generic body-sized puff, rather than the
// Wraith's mist the Mist Form wears: nothing about domination is misty.
GameObject vfx = ZNetScene.instance.GetPrefab("vfx_corpse_destruction_medium");
if (vfx) Instantiate(vfx, m_character.transform.position, Quaternion.identity); if (vfx) Instantiate(vfx, m_character.transform.position, Quaternion.identity);
user.Message(MessageHud.MessageType.Center, $"{m_character.m_name} dominated!"); user.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_aswid_dominated", m_character.m_name));
return true; return true;
} }
@ -139,18 +142,22 @@ namespace RacesOfValheim
if (isEnslaved) if (isEnslaved)
{ {
bool following = m_ai != null && m_ai.GetFollowTarget() != null; bool following = m_ai != null && m_ai.GetFollowTarget() != null;
return following ? "[<color=yellow><b>E</b></color>] Stay" : "[<color=yellow><b>E</b></color>] Follow"; return (following ? ModText.Get("rov_hover_aswid_stay") : ModText.Get("rov_hover_aswid_follow"));
} }
else else
{ {
if (BossProgressionManager.GetCurrentProgressionState() < 6) return ""; if (BossProgressionManager.GetCurrentProgressionState() < 6) return "";
float cd = AswidRace.GetEnslaveCooldown(); float cd = AswidRace.GetEnslaveCooldown();
if (cd > 0) return $"[<color=red>E</color>] Dominate (Cooldown: {Mathf.CeilToInt(cd / 60f)}m)"; if (cd > 0) return ModText.Get("rov_hover_aswid_dominate_cooldown_m", Mathf.CeilToInt(cd / 60f));
return "[<color=yellow><b>E</b></color>] Dominate"; return ModText.Get("rov_hover_aswid_dominate");
} }
} }
// New in Valheim 1.0: Hoverable gained this. Every vanilla implementation returns a
// serialised m_hoverOffset, which is 0 unless the prefab sets one, so 0 is vanilla behaviour.
public float GetHoverOffset() => 0f;
public string GetHoverName() public string GetHoverName()
{ {
return ""; // Character component already provides the name return ""; // Character component already provides the name

View file

@ -58,6 +58,12 @@ namespace RacesOfValheim
private const float BaseEyeHeight = 0.181f; private const float BaseEyeHeight = 0.181f;
private const float BaseEyeSeparation = 0.032f; private const float BaseEyeSeparation = 0.032f;
// The borrowed socket at the size the Skeleton wears it, times the config multiplier, was
// two green blocks on the face; at half it was smaller than the painted eye underneath,
// which then showed round it. Applied before the multiplier, so a saved config keeps its
// meaning as "relative to the default".
private const float BaseEyeScale = 0.75f;
// ─── Race check ───────────────────────────────────────────────────── // ─── Race check ─────────────────────────────────────────────────────
/// <summary> /// <summary>
@ -99,6 +105,10 @@ namespace RacesOfValheim
// built again rather than merely moved. // built again rather than merely moved.
public string SourceModel = ""; public string SourceModel = "";
public bool FlatShader; public bool FlatShader;
// Which body the base pose was measured for: the female face puts the eyes elsewhere
// (PlayerFace), so a change of body model is a rebuild too.
public bool Female;
} }
/// <summary>The pose an eye was authored at on the creature. Everything else is a delta on this.</summary> /// <summary>The pose an eye was authored at on the creature. Everything else is a delta on this.</summary>
@ -180,7 +190,8 @@ namespace RacesOfValheim
EyeFrame existing = eyes.GetComponent<EyeFrame>(); EyeFrame existing = eyes.GetComponent<EyeFrame>();
if (existing == null || if (existing == null ||
existing.SourceModel != AswidConfig.EyeSourceModel.Value || existing.SourceModel != AswidConfig.EyeSourceModel.Value ||
existing.FlatShader != AswidConfig.EyeFlatColorShader.Value) existing.FlatShader != AswidConfig.EyeFlatColorShader.Value ||
existing.Female != PlayerFace.IsFemale(player))
{ {
eyes.name = EyesName + "_Removed"; eyes.name = EyesName + "_Removed";
Object.Destroy(eyes.gameObject); Object.Destroy(eyes.gameObject);
@ -309,9 +320,6 @@ namespace RacesOfValheim
float scale = GetPlayerScale(player) * toLocal; float scale = GetPlayerScale(player) * toLocal;
Vector3 shift = frame.LocalForward * (AswidConfig.EyeForwardOffset.Value * scale)
+ frame.LocalUp * (AswidConfig.EyeHeightOffset.Value * scale);
for (int i = 0; i < holder.childCount; i++) for (int i = 0; i < holder.childCount; i++)
{ {
Transform eye = holder.GetChild(i); Transform eye = holder.GetChild(i);
@ -324,6 +332,16 @@ namespace RacesOfValheim
float side = Mathf.Sign(Vector3.Dot(authored.Position, frame.LocalRight)); float side = Mathf.Sign(Vector3.Dot(authored.Position, frame.LocalRight));
if (side == 0f) side = i == 0 ? -1f : 1f; if (side == 0f) side = i == 0 ? -1f : 1f;
// This eye's hand corrections (RaceEyeTuning), on top of the race's own offsets.
RaceEyeTuning.Eye tuning = RaceEyeTuning.For("Aswid", player, side);
float forward = AswidConfig.EyeForwardOffset.Value + (tuning != null ? tuning.Forward : 0f);
float height = AswidConfig.EyeHeightOffset.Value + (tuning != null ? tuning.Height : 0f);
float separation = AswidConfig.EyeSeparationOffset.Value + (tuning != null ? tuning.Separation : 0f);
float size = AswidConfig.EyeSizeMultiplier.Value * (tuning != null ? tuning.Size : 1f);
Vector3 shift = frame.LocalForward * (forward * scale)
+ frame.LocalUp * (height * scale);
// YAW IS MIRRORED, the other two are not. Turning both eyes the same way on Y // YAW IS MIRRORED, the other two are not. Turning both eyes the same way on Y
// makes the pair look sideways - both point off the same shoulder, because a face // makes the pair look sideways - both point off the same shoulder, because a face
// is symmetric about its centre line and yaw is the axis that crosses it. Negating // is symmetric about its centre line and yaw is the axis that crosses it. Negating
@ -332,15 +350,31 @@ namespace RacesOfValheim
// //
// Pitch and roll are shared deliberately: both eyes looking up is a face looking // Pitch and roll are shared deliberately: both eyes looking up is a face looking
// up, and mirroring either of those would cross them instead of aiming them. // up, and mirroring either of those would cross them instead of aiming them.
//
// This twist is on the HEAD BONE's raw axes (it multiplies from the left), and on
// this rig those are not the face's: bone X points out of the face and bone Z
// sideways. The defaults were dialled in against that, so it stays as it is.
Quaternion twist = Quaternion.Euler( Quaternion twist = Quaternion.Euler(
AswidConfig.EyeRotationX.Value, AswidConfig.EyeRotationX.Value,
AswidConfig.EyeRotationY.Value * side, AswidConfig.EyeRotationY.Value * side,
AswidConfig.EyeRotationZ.Value); AswidConfig.EyeRotationZ.Value);
// The RaceEyeTuning corrections turn the eye on the FACE's axes instead: conjugated by
// the face frame, X tips it, Y turns it toward the temple and Z raises the outer
// corner, the same on both eyes. Added to the bone-axis twist above, X rolled the
// eyes and a mirrored Z tipped one up and the other down.
Quaternion nudge = Quaternion.identity;
if (tuning != null)
{
nudge = authored.Rotation
* Quaternion.Euler(tuning.RotX, tuning.RotY * side, tuning.RotZ * side)
* Quaternion.Inverse(authored.Rotation);
}
eye.localPosition = authored.Position + shift + eye.localPosition = authored.Position + shift +
frame.LocalRight * (side * AswidConfig.EyeSeparationOffset.Value * scale); frame.LocalRight * (side * separation * scale);
eye.localRotation = twist * authored.Rotation; eye.localRotation = nudge * twist * authored.Rotation;
eye.localScale = authored.Scale * AswidConfig.EyeSizeMultiplier.Value; eye.localScale = authored.Scale * size;
} }
} }
@ -424,6 +458,12 @@ namespace RacesOfValheim
MeasureFrame(player, headBone, frame); MeasureFrame(player, headBone, frame);
frame.SourceModel = modelName; frame.SourceModel = modelName;
frame.FlatShader = AswidConfig.EyeFlatColorShader.Value; frame.FlatShader = AswidConfig.EyeFlatColorShader.Value;
frame.Female = PlayerFace.IsFemale(player);
float baseHeight = BaseEyeHeight;
float baseSeparation = BaseEyeSeparation;
float baseSize = BaseEyeScale;
PlayerFace.AdjustEyes(player, ref baseHeight, ref baseSeparation, ref baseSize);
// canonicalToFrame turns "face forward, as authored" into "face forward, on THIS // canonicalToFrame turns "face forward, as authored" into "face forward, on THIS
// rig's own axes" - the rotation that carries the ordinary (X,Y,Z) convention onto // rig's own axes" - the rotation that carries the ordinary (X,Y,Z) convention onto
@ -458,8 +498,8 @@ namespace RacesOfValheim
float toLocal = 1f / headBone.lossyScale.x; float toLocal = 1f / headBone.lossyScale.x;
Vector3 basePosition = frame.LocalForward * (BaseEyeForward * toLocal) Vector3 basePosition = frame.LocalForward * (BaseEyeForward * toLocal)
+ frame.LocalUp * (BaseEyeHeight * toLocal) + frame.LocalUp * (baseHeight * toLocal)
+ frame.LocalRight * (side * BaseEyeSeparation * toLocal); + frame.LocalRight * (side * baseSeparation * toLocal);
// The socket's own authored tilt is skipped for the same reason its position is - // The socket's own authored tilt is skipped for the same reason its position is -
// canonicalToFrame alone (face forward, on this rig's axes) is what the config's // canonicalToFrame alone (face forward, on this rig's axes) is what the config's
@ -481,7 +521,7 @@ namespace RacesOfValheim
// this object at on a real skeleton. Divided into the new parent's scale, the pair // this object at on a real skeleton. Divided into the new parent's scale, the pair
// lands at exactly the size vanilla wears them, which is the whole point of // lands at exactly the size vanilla wears them, which is the whole point of
// borrowing them instead of drawing spheres. // borrowing them instead of drawing spheres.
Vector3 baseScale = source.lossyScale * toLocal; Vector3 baseScale = source.lossyScale * (toLocal * baseSize);
// Remembered before anything moves it, because everything the config does is // Remembered before anything moves it, because everything the config does is
// expressed as a delta on this. // expressed as a delta on this.

View file

@ -1,54 +1,169 @@
using HarmonyLib;
using UnityEngine; using UnityEngine;
using Jotunn.Managers;
namespace RacesOfValheim namespace RacesOfValheim
{ {
public class BatFormBehavior : MonoBehaviour /// <summary>
/// The bat's flight, held on for as long as the worn model exists.
///
/// The bat flies on Character.m_flying and is steered by DirectedFlightPatch, the same
/// controls as the Skadi's drake; this class only hands over the bat's own numbers and keeps
/// the flag up. It used to fly on vanilla's debug-fly flag, which ignored carry weight, cost
/// nothing, moved at 50 m/s and made every monster blind to the player - the Discord reports
/// that started the 2026 rebalance.
///
/// Other clients learn the bat is airborne from Aswid_IsBatForm in the ZDO, which
/// 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>
public class BatFormBehavior : MonoBehaviour, IDirectedFlyer
{ {
private static readonly System.Reflection.FieldInfo FlyingField =
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 bool warnedTooHeavy;
private bool expired;
private bool free;
public void Initialize(AswidProgression.FormRules rules) public void Initialize(AswidProgression.FormRules rules)
{ {
this.formRules = rules; this.formRules = rules;
} }
// ─── IDirectedFlyer ─────────────────────────────────────────────────────
// A bat is never grounded on purpose: it flies for as long as the form lasts.
public bool IsFlying => true;
public float LastPoweredTime { get; set; }
public float TurnSpeed => AswidConfig.BatTurnSpeed.Value;
public float GlideSpeed => AswidConfig.BatGlideSpeed.Value;
public float BoostSpeed => AswidConfig.BatBoostSpeed.Value;
public float SprintSpeed => AswidConfig.BatSprintSpeed.Value;
public float ReverseSpeed => AswidConfig.BatReverseSpeed.Value;
public float LiftoffSpeed => AswidConfig.BatLiftoffSpeed.Value;
public float HoverSeconds => AswidConfig.BatHoverSeconds.Value;
public float PoweredStaminaPerSecond => AswidConfig.BatPoweredStaminaPerSecond.Value * EncumberedCostFactor();
public float SprintStaminaPerSecond => AswidConfig.BatSprintStaminaPerSecond.Value * EncumberedCostFactor();
public bool CanPower => !(IsEncumbered() && AswidConfig.BatEncumbered.Value == AswidConfig.EncumberedMode.Blocked);
private static bool IsEncumbered()
{
return Player.m_localPlayer != null && Player.m_localPlayer.IsEncumbered();
}
private static float EncumberedCostFactor()
{
return IsEncumbered() ? 1f + AswidConfig.BatEncumberedExtraCost.Value : 1f;
}
/// <summary>
/// The form's lifetime in seconds at the current state, or 0 for no limit. The per-state
/// bonus is Dissolution's "scales with boss progression", and only means anything on top
/// of a base limit.
/// </summary>
public static float MaxDuration()
{
float max = AswidConfig.BatMaxDuration.Value;
if (max <= 0f) return 0f;
return max + AswidConfig.BatDurationPerState.Value * BossProgressionManager.GetCurrentProgressionState();
}
private void Start() private void Start()
{ {
anim = GetComponentInChildren<Animator>(); anim = GetComponentInChildren<Animator>();
if (Player.m_localPlayer != null) startTime = Time.time;
{ LastPoweredTime = Time.time;
HarmonyLib.Traverse.Create(Player.m_localPlayer).Field("m_debugFly").SetValue(true); free = AswidConfig.UsesFreeBatFlight();
} if (!free) DirectedFlight.Register(this);
Hold();
} }
private void Update() private void Update()
{ {
if (Player.m_localPlayer == null || Player.m_localPlayer.IsDead()) return; Player player = Player.m_localPlayer;
if (player == null || player.IsDead()) return;
// Ensure flight remains on continuously // Held every frame rather than set once, for the same reason the debug-fly flag was:
HarmonyLib.Traverse.Create(Player.m_localPlayer).Field("m_debugFly").SetValue(true); // anything that clears it mid-form (a vanilla reset, another mod) would drop the bat
// into walking with the model still on.
Hold();
// Free Flight ignores weight, so only Stamina Flight warns about it.
if (!free)
{
if (!CanPower && !warnedTooHeavy)
{
warnedTooHeavy = true;
player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_aswid_bat_too_heavy_to_beat"));
}
else if (CanPower)
{
warnedTooHeavy = false;
}
}
float max = MaxDuration();
if (max > 0f && !expired && Time.time - startTime >= max && AswidRace.Instance != null)
{
expired = true;
player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_aswid_bat_form_fades"));
AswidRace.Instance.ForceRevert();
}
// Sync Animator
if (anim != null) if (anim != null)
{ {
Vector3 vel = Player.m_localPlayer.GetVelocity(); Vector3 vel = player.GetVelocity();
vel.y = 0f; vel.y = 0f;
float speed = vel.magnitude; anim.SetFloat("forward_speed", vel.magnitude);
// Bats don't necessarily have a complex animator like players,
// but if they do have a speed or flying parameter, we set it here.
anim.SetFloat("forward_speed", speed);
anim.SetBool("flying", true); anim.SetBool("flying", true);
} }
} }
private void OnDestroy() private void OnDestroy()
{ {
if (Player.m_localPlayer != null) DirectedFlight.Unregister(this);
{ SetFlying(false);
HarmonyLib.Traverse.Create(Player.m_localPlayer).Field("m_debugFly").SetValue(false);
} }
private void Hold()
{
if (free) SetDebugFly(true);
else SetFlying(true);
}
/// <summary>
/// The local half of Stamina Flight. The remote half is the Aswid_IsBatForm ZDO flag
/// 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>
public static void SetFlying(bool flying)
{
Player player = Player.m_localPlayer;
if (player == null) return;
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);
} }
} }
} }

View file

@ -79,14 +79,16 @@ namespace RacesOfValheim
private bool OnAddMeat(Switch caller, Humanoid user, ItemDrop.ItemData item) private bool OnAddMeat(Switch caller, Humanoid user, ItemDrop.ItemData item)
{ {
return TryAdd(user, item, isMeat: true); return TryAdd(user, item, isMeat: true) || item != null;
} }
private bool OnAddBone(Switch caller, Humanoid user, ItemDrop.ItemData item) private bool OnAddBone(Switch caller, Humanoid user, ItemDrop.ItemData item)
{ {
return TryAdd(user, item, isMeat: false); return TryAdd(user, item, isMeat: false) || item != null;
} }
// Both switches treat an item in hand as handled whatever TryAdd says: false makes
// Humanoid.UseItem cover our own message with the generic "$msg_cantuseon".
private bool TryAdd(Humanoid user, ItemDrop.ItemData item, bool isMeat) private bool TryAdd(Humanoid user, ItemDrop.ItemData item, bool isMeat)
{ {
if (user == null) return false; if (user == null) return false;
@ -96,7 +98,7 @@ namespace RacesOfValheim
if (item == null) item = FindUsable(inventory, isMeat); if (item == null) item = FindUsable(inventory, isMeat);
if (item == null) if (item == null)
{ {
user.Message(MessageHud.MessageType.Center, isMeat ? "No raw flesh to render." : "No bone to grind."); user.Message(MessageHud.MessageType.Center, (isMeat ? ModText.Get("rov_msg_aswid_no_raw_flesh_render") : ModText.Get("rov_msg_aswid_no_bone_grind")));
return false; return false;
} }

Binary file not shown.

Binary file not shown.

View file

@ -0,0 +1,368 @@
using System.Collections.Generic;
using System.Reflection;
using HarmonyLib;
using Jotunn.Configs;
using Jotunn.Entities;
using Jotunn.Managers;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// The Bone Ship, first piece: the small one, a clone of the Karve. See Skeleton_BoneShip.txt, sections
/// 2, 10 and 11 - every number and node name below was read off the game, not remembered.
///
/// WHAT THIS STEP DOES
/// - A new buildable ship, BoneKarve, cloned from "Karve" so the vanilla one is left alone.
/// - A hull that is rotten from the first day: WearNTear is pointed at the prefab's own worn hull as
/// its "new" one, so full health shows the worn model, and a light tint goes on top. The game's
/// SetHealthVisual guards the equal case (it only turns a visual off when it differs from the new
/// one), so m_new == m_worn is a supported shape, not a trick. The fresh hull is switched off in
/// the prefab or both would show at once.
/// - It goes where the sails are not: the wind-independent push (SailK) and a sail that never
/// unfurls, in BoneShipSailForcePatch and BoneShipSailPatch below.
///
/// WHAT IS NOT HERE YET: the torn sail texture, the bones, the rowers, the figurehead, the altar, the
/// roster and the archers. Each is its own step. The archer's mount already exists (ShipMount.cs).
/// </summary>
public static class BoneShip
{
// Every vanilla ship but the Raft has a bone version (the design, 2026-10-05). The names are what
// ShipMountTest's post table and the rest of the Bone Ship know them by.
public const string KarveName = "BoneKarve";
public const string LongshipName = "BoneLongship";
public const string AshlandsName = "BoneAshlands";
/// <summary>The hover name of the altar on the deck, where bone fragments are offered.</summary>
public const string AltarName = "$rov_piece_boneship_altar_name";
/// <summary>
/// Places in the roster, melee and archers, by ship (Skeleton_BoneShip.txt 5.7). The small ship is
/// the pile's idea at half size, the Longship a pile's 4+4, and the Ashlands ship - the biggest hull,
/// three times the Karve's mass - 6+6 (decided). Constants, because the answer is a balance call.
/// The rowers' seats follow: one per place, half on each side.
/// </summary>
private const int KarveMelee = 2, KarveRanged = 2;
private const int LongshipMelee = 4, LongshipRanged = 4;
private const int AshlandsMelee = 6, AshlandsRanged = 6;
public static int MeleeCapOf(Component ship) =>
IsKarve(ship) ? KarveMelee : IsAshlands(ship) ? AshlandsMelee : LongshipMelee;
public static int RangedCapOf(Component ship) =>
IsKarve(ship) ? KarveRanged : IsAshlands(ship) ? AshlandsRanged : LongshipRanged;
private static bool IsAshlands(Component ship)
{
return ship != null && ship.name.StartsWith(AshlandsName);
}
private static bool IsKarve(Component ship)
{
return ship != null && ship.name.StartsWith(KarveName);
}
public static bool IsKarveShip(Component ship) => IsKarve(ship);
/// <summary>Half the length of the hull, read from the OnboardTrigger every ship carries.</summary>
public static float HalfLengthOf(Component ship)
{
Transform trigger = ship != null ? ship.transform.Find("OnboardTrigger") : null;
BoxCollider box = trigger != null ? trigger.GetComponent<BoxCollider>() : null;
return box != null ? Mathf.Abs(box.size.z * trigger.localScale.z) * 0.5f : 0f;
}
/// <summary>Our prefab, the vanilla one it is cloned from, and the localisation key stem.</summary>
private struct Spec
{
public string Name;
public string Source;
public string KeyStem;
public Spec(string name, string source, string keyStem) { Name = name; Source = source; KeyStem = keyStem; }
}
private static readonly Spec[] Specs =
{
new Spec(KarveName, "Karve", "karve"),
new Spec(LongshipName, "VikingShip", "longship"),
new Spec(AshlandsName, "VikingShip_Ashlands", "ashlands"),
};
private static string DisplayKey(Spec s) => "$rov_piece_boneship_" + s.KeyStem + "_name";
private static string DescriptionKey(Spec s) => "$rov_piece_boneship_" + s.KeyStem + "_desc";
/// <summary>
/// What the oarsmen push with, as a share of what a perfect wind would. Wind direction and strength
/// no longer matter, so this is the whole sail. The vanilla factor is angle * lerp(0.25, 1, wind):
/// 1.0 is the best a real wind can ever do, and a good breeze on a good heading is about 0.7. Measured
/// on a Karve at Full: 0.46 gave 4.5 m/s. 0.75 is the proposal; to be tuned with an F8 at cruise.
/// </summary>
public const float SailK = 0.75f;
/// <summary>The key part of every bone ship's recipe: the swamp's Wishbone. One per ship.</summary>
private const string WishbonePrefab = "Wishbone";
/// <summary>
/// What each costs. The Wishbone is the decided part; the rest are PLACEHOLDERS that grow with the
/// hull, and the Ashlands one asks for the fine wood a late-game ship would. The workbench requirement
/// comes from the vanilla ship each one is cloned from. Open to every race: nothing here, or on the
/// pieces, asks who is building.
/// </summary>
private static RequirementConfig[] CostOf(string name)
{
switch (name)
{
case KarveName:
return new[]
{
new RequirementConfig(WishbonePrefab, 1, 0, true),
new RequirementConfig("Wood", 30, 0, true),
new RequirementConfig("BoneFragments", 60, 0, true),
new RequirementConfig("Resin", 10, 0, true),
};
case LongshipName:
return new[]
{
new RequirementConfig(WishbonePrefab, 1, 0, true),
new RequirementConfig("Wood", 60, 0, true),
new RequirementConfig("BoneFragments", 120, 0, true),
new RequirementConfig("Resin", 20, 0, true),
};
default: // the Ashlands one
return new[]
{
new RequirementConfig(WishbonePrefab, 1, 0, true),
new RequirementConfig("FineWood", 60, 0, true),
new RequirementConfig("BoneFragments", 200, 0, true),
new RequirementConfig("Resin", 30, 0, true),
};
}
}
/// <summary>Multiplied into the worn hull's colour: a touch darker and greener on top of the worn one.</summary>
private static readonly Color RotTint = new Color(0.80f, 0.82f, 0.72f, 1f);
public static bool IsBoneShip(Ship ship)
{
return ship != null && ship.GetComponent<BoneShipMarker>() != null;
}
public static void Register()
{
BoneShipArcher.Register();
foreach (Spec spec in Specs)
{
RegisterShip(spec);
}
}
private static void RegisterShip(Spec spec)
{
GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(spec.Name, spec.Source);
if (prefab == null)
{
Jotunn.Logger.LogWarning($"[BoneShip] Could not clone '{spec.Source}'; {spec.Name} is not registered.");
return;
}
prefab.AddComponent<BoneShipMarker>();
RotHull(prefab, spec.Name);
BoneShipSail.Apply(prefab, spec.Name);
// The roster (the altar's bookkeeping and the troops) and the fittings (bones and the altar
// itself, built when the ship is in the world). The roster registers its RPC in Awake.
prefab.AddComponent<BoneShipRoster>();
prefab.AddComponent<BoneShipFittings>();
prefab.AddComponent<BoneShipRowers>(); // the oarsmen; how many show is the roster's count
Piece piece = prefab.GetComponent<Piece>();
if (piece == null)
{
Jotunn.Logger.LogWarning($"[BoneShip] The cloned '{spec.Source}' has no Piece; {spec.Name} is not registered.");
return;
}
piece.m_name = DisplayKey(spec);
piece.m_description = DescriptionKey(spec);
Sprite icon = BorrowIcon("TrophySkeleton");
if (icon != null) piece.m_icon = icon;
PieceManager.Instance.AddPiece(new CustomPiece(prefab, fixReference: false, new PieceConfig
{
Name = DisplayKey(spec),
Description = DescriptionKey(spec),
PieceTable = PieceTables.Hammer,
Category = PieceCategories.Misc,
CraftingStation = CraftingStations.Workbench,
Icon = icon,
Requirements = CostOf(spec.Name),
}));
}
/// <summary>
/// Worn hull from full health. Every vanilla ship keeps its three hull visuals where WearNTear can
/// name them - m_new, m_worn, m_broken - whatever the node path (Karve: ship/visual_new,
/// Longship and Ashlands: ship/visual/hull_new), so the clone's own fields are read instead of a
/// path per ship. The fresh one is on in the prefab and has to be switched off, or both would show.
/// </summary>
private static void RotHull(GameObject prefab, string name)
{
WearNTear wear = prefab.GetComponent<WearNTear>();
if (wear == null || wear.m_new == null || wear.m_worn == null)
{
Jotunn.Logger.LogWarning($"[BoneShip] {name}: WearNTear has no new/worn hull to swap; the hull stays as it is.");
return;
}
GameObject fresh = wear.m_new;
GameObject worn = wear.m_worn;
if (fresh == worn) return;
wear.m_new = worn;
fresh.SetActive(false);
Tint(worn, RotTint);
}
/// <summary>
/// Darkens the Piece-shader materials of a hull. COPIES them, so the vanilla ship that shares the
/// asset keeps its colour; the water mask and anything without a plain colour are left alone.
/// </summary>
private static void Tint(GameObject root, Color tint)
{
Dictionary<Material, Material> copies = new Dictionary<Material, Material>();
foreach (Renderer renderer in root.GetComponentsInChildren<Renderer>(true))
{
if (renderer == null || renderer is ParticleSystemRenderer) continue;
Material[] shared = renderer.sharedMaterials;
bool changed = false;
for (int i = 0; i < shared.Length; i++)
{
Material source = shared[i];
if (source == null || source.shader == null) continue;
if (source.shader.name != "Custom/Piece" || !source.HasProperty("_Color")) continue;
Material copy;
if (!copies.TryGetValue(source, out copy))
{
copy = new Material(source) { name = source.name + "_bone" };
copy.SetColor("_Color", source.GetColor("_Color") * tint);
copies[source] = copy;
}
shared[i] = copy;
changed = true;
}
if (changed) renderer.sharedMaterials = shared;
}
}
public static void EnsureKnown(Player player)
{
if (player == null) return;
Traverse traverse = Traverse.Create(player);
bool any = false;
foreach (Spec spec in Specs)
{
GameObject prefab = PrefabManager.Instance.GetPrefab(spec.Name);
Piece piece = prefab != null ? prefab.GetComponent<Piece>() : null;
if (piece == null) continue;
traverse.Method("AddKnownPiece", piece).GetValue();
any = true;
}
if (any) traverse.Method("UpdateAvailablePiecesList").GetValue();
}
private static Sprite BorrowIcon(string prefabName)
{
ItemDrop drop = PrefabManager.Cache.GetPrefab<ItemDrop>(prefabName);
Sprite[] icons = drop != null && drop.m_itemData != null && drop.m_itemData.m_shared != null
? drop.m_itemData.m_shared.m_icons
: null;
if (icons != null && icons.Length > 0 && icons[0] != null) return icons[0];
Jotunn.Logger.LogWarning($"[BoneShip] Could not borrow the icon from '{prefabName}'.");
return null;
}
}
/// <summary>Marks a ship as one of ours. No logic: the patches below and the archers look for it.</summary>
public class BoneShipMarker : MonoBehaviour
{
}
/// <summary>
/// The oarsmen's push, in place of the wind's.
///
/// Ship.GetSailForce is, read off the IL: normalize(windDir + forward) * angleFactor * lerp(0.25, 1,
/// windIntensity) * m_sailForceFactor * sailSize, smoothed into m_sailForce over a second. The angle
/// factor is zero when the wind comes from ahead - that is what stops a vanilla ship dead. For a bone
/// ship the target is simply forward * m_sailForceFactor * sailSize * SailK, smoothed the same way with
/// the same two private fields, so the ship accelerates like a sailing one and the vanilla factor of
/// each hull (Karve 0.03, VikingShip 0.05, Ashlands 0.085) still scales the push.
///
/// sailSize is 0 below Half, 0.5 at Half and 1 at Full, so Slow and Back are untouched: they were
/// never the wind's.
/// </summary>
[HarmonyPatch(typeof(Ship), "GetSailForce")]
public static class BoneShipSailForcePatch
{
private static readonly FieldInfo SailForce = AccessTools.Field(typeof(Ship), "m_sailForce");
private static readonly FieldInfo WindChangeVelocity = AccessTools.Field(typeof(Ship), "m_windChangeVelocity");
public static bool Prefix(Ship __instance, float sailSize, ref Vector3 __result)
{
if (!BoneShip.IsBoneShip(__instance)) return true;
if (SailForce == null || WindChangeVelocity == null) return true; // changed under us: fall back to vanilla
Vector3 current = (Vector3)SailForce.GetValue(__instance);
Vector3 velocity = (Vector3)WindChangeVelocity.GetValue(__instance);
Vector3 target = __instance.transform.forward * (__instance.m_sailForceFactor * sailSize * BoneShip.SailK);
current = Vector3.SmoothDamp(current, target, ref velocity, 1f, 99f);
SailForce.SetValue(__instance, current);
WindChangeVelocity.SetValue(__instance, velocity);
__result = current;
return false;
}
}
/// <summary>
/// The sail never unfurls and the mast never turns to the wind: there is no sailing to show. Half and
/// Full would otherwise raise a sail that is meant to hang in rags. UpdateSail is what runs
/// UpdateSailSize (the furl animation) and then turns the mast, so skipping it skips both.
/// What the sail looks like left alone is for the game to show: the prefab's own pose.
/// </summary>
[HarmonyPatch(typeof(Ship), "UpdateSail")]
public static class BoneShipSailPatch
{
public static bool Prefix(Ship __instance)
{
return !BoneShip.IsBoneShip(__instance);
}
}
/// <summary>Makes the piece buildable without having to craft its parts first, like the bone pile.</summary>
[HarmonyPatch(typeof(Player), "OnSpawned")]
public static class BoneShipKnownPatch
{
public static void Postfix(Player __instance)
{
if (__instance != Player.m_localPlayer) return;
BoneShip.EnsureKnown(__instance);
}
}
}

View file

@ -0,0 +1,54 @@
using UnityEngine;
using Jotunn.Managers;
namespace RacesOfValheim
{
/// <summary>
/// The archer a bone ship carries: the Bound Sentry, with the parts of it that make no sense on a deck
/// taken away and the ones that make it a ship's archer put in.
///
/// A PREFAB OF ITS OWN, not the sentry with a component added when it is spawned. A component added in
/// play is not saved: after a reload the archer would come back with no mount, and stand on nothing. This
/// one is built with ShipMount and ShipBust already on it, so a reloaded archer finds its ship again by the
/// id in its own ZDO (see ShipMount) and the roster, which counts archers by that id, never has to rebuild
/// one that was already there.
///
/// Taken away from the sentry:
/// - RaisedThrall. The orders (follow, wait, go home) are for troops; an archer on a mast of the ship
/// has no business following anyone, and E on it would send it after the player;
/// - CharacterDrop. The sentry gives back what it cost when it falls. This one is invulnerable while the
/// ship stands, and when the ship goes down it goes too - which must not pay out a soul stone and ten
/// bone fragments for every archer on every ship that sinks.
/// What stays is the bow, the AI and the tamed flag the spawner sets.
/// </summary>
public static class BoneShipArcher
{
public const string Name = "BoneShipArcher";
public static void Register()
{
// The sentry is registered by the bone pile, earlier in the same window.
GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(Name, SkeletonSentry.SentryName);
if (prefab == null)
{
Jotunn.Logger.LogWarning($"[BoneShip] Could not clone '{SkeletonSentry.SentryName}'; the ships have no archers.");
return;
}
foreach (RaisedThrall thrall in prefab.GetComponentsInChildren<RaisedThrall>(true))
{
if (thrall != null) Object.DestroyImmediate(thrall);
}
foreach (CharacterDrop drop in prefab.GetComponentsInChildren<CharacterDrop>(true))
{
if (drop != null) Object.DestroyImmediate(drop);
}
prefab.AddComponent<ShipMount>();
prefab.AddComponent<ShipBust>();
PrefabManager.Instance.AddPrefab(prefab);
}
}
}

View file

@ -0,0 +1,572 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// What is bolted to a bone ship's hull: the bones along both rails and the bow, a few scattered on the
/// deck, and the ALTAR where bone fragments are offered (see BoneShipRoster).
///
/// Built when the ship comes into the world, on every client, and not baked into the prefab - because
/// the three hulls are different shapes (the Karve's nodes bear no relation to the Longship's, and the
/// Ashlands ship's rope nodes are in another axis altogether) and the only generic way to find "the rail"
/// and "the deck" on all of them is to ask the physics engine. So a ray is dropped from above at points
/// scanned inward from outside the hull; the first thing it lands on is the rail's top, and a ray down the
/// centre line lands on the deck. The mast, the sail and the ropes are skipped by NAME up the hierarchy,
/// because the boom of the Karve is a collider that spans the whole beam at six metres.
///
/// Everything is deterministic from the ship's own id, so every client builds the same bones.
///
/// The bones are borrowed models (ModelBorrow strips them to renderers) cached once as templates and
/// copied, so a ship coming into view is a few dozen cheap instantiates and not a few dozen strips.
/// The model names that are not certain to exist - the bigger bones - are tried in order and whatever
/// resolves is logged once.
/// </summary>
public class BoneShipFittings : MonoBehaviour
{
private const string SkullPrefab = "TrophySkeleton";
private const string FragmentsPrefab = "BoneFragments";
// The bigger bones along the rail. A pickable from the forest crypts: it is a pile of remains meant to
// be seen, and it is certain to exist (the earlier guesses - bone_stack, skull_pile, a ribcage item -
// never were). Kept as a list so a second model is one more entry.
private static readonly string[] LargeBonePrefabs = { "Pickable_ForestCryptRemains01" };
internal const float RayStartHeight = 14f;
private const float RayLength = 32f;
// The offering chest next to the cargo hatch. Both are tunable by eye: ChestSize is the borrowed chest's
// widest side in metres (the model is measured and fitted by ModelBorrow), ChestHeight the box that is
// clicked and where the skull sits.
private const string ChestPrefab = "piece_chest_wood";
private const float ChestSize = 0.85f;
private const float ChestHeight = 0.62f;
private static GameObject s_holder;
private static readonly Dictionary<string, GameObject> s_templates = new Dictionary<string, GameObject>();
private static bool s_reported;
/// <summary>Where the altar ended up, in the ship's space. The roster keeps its hover on this.</summary>
public Switch Altar { get; private set; }
/// <summary>One archer's place: where it stands on the ship (ship space) and whether it is a bust.</summary>
public struct ArcherPost
{
public Vector3 Local;
public bool Bust;
}
/// <summary>
/// Where the ship's archers stand, found by ray once the hull's colliders exist. Null until then; the
/// roster waits for it. The small ship has one, at the bow; the large ones a pair, bow and stern.
/// All are busts - only the chest and up shows, a figurehead that shoots.
/// </summary>
public List<ArcherPost> ArcherPosts { get; private set; }
private void Start()
{
StartCoroutine(Build());
}
private IEnumerator Build()
{
ZNetView nview = GetComponent<ZNetView>();
if (nview == null || !nview.IsValid()) yield break; // a placement ghost: no bones
// One physics step so the hull's colliders exist for the rays.
yield return new WaitForFixedUpdate();
yield return null;
Bounds hull;
if (!TryHullExtent(out hull))
{
Jotunn.Logger.LogWarning($"[BoneShip] '{name}' has no OnboardTrigger to measure; no bones were fitted.");
yield break;
}
ReportModels();
System.Random rng = new System.Random(nview.GetZDO().m_uid.GetHashCode());
float hx = hull.extents.x;
float hz = hull.extents.z;
int rays = 0;
int placed = 0;
// ---- both rails
int slots = Mathf.Max(4, Mathf.RoundToInt(2f * 0.92f * hz / 1.3f));
for (int side = -1; side <= 1; side += 2)
{
for (int i = 0; i < slots; i++)
{
float t = slots == 1 ? 0.5f : i / (float)(slots - 1);
float z = Mathf.Lerp(-0.92f * hz, 0.92f * hz, t) + Range(rng, -0.25f, 0.25f);
Vector3 point;
if (!FindRail(side, z, hx, out point, ref rays)) continue;
if (rays >= 40) { rays = 0; yield return null; }
if (PlaceOnRail(point, side, rng)) placed++;
}
}
// ---- the bow: a cluster on the centre line at the very front
Vector3 bow;
if (FindSurface(new Vector3(0f, RayStartHeight, 0.90f * hz), out bow))
{
for (int k = 0; k < 3; k++)
{
Vector3 p = bow + new Vector3(Range(rng, -0.35f, 0.35f), 0.02f, Range(rng, -0.35f, 0.15f));
if (Place(SkullPrefab, p, Range(rng, 0.30f, 0.42f), rng, 25f)) placed++;
}
}
// ---- loose on the deck
int scatter = Mathf.Max(5, slots / 2);
for (int k = 0; k < scatter; k++)
{
float x = Range(rng, -0.55f, 0.55f) * hx;
float z = Range(rng, -0.8f, 0.8f) * hz;
if (NearHatch(x, z)) continue; // keep the cargo hatch and the offering chest beside it clear
Vector3 point;
if (!FindSurface(new Vector3(x, RayStartHeight, z), out point)) continue;
if (Place(FragmentsPrefab, point + Vector3.up * 0.02f, Range(rng, 0.22f, 0.34f), rng, 180f)) placed++;
if (++rays >= 40) { rays = 0; yield return null; }
}
BuildAltar(hz, rng);
FindArcherPosts(hz);
Jotunn.Logger.LogInfo($"[BoneShip] '{name}': {placed} bones fitted, altar {(Altar != null ? "built" : "not built")}, " +
$"{ArcherPosts.Count} archer post(s).");
}
// ---------------------------------------------------------------- the archers' posts
/// <summary>
/// Bow always; the large ships a second one at the stern. A point at the very tip of a hull is often
/// past the end of its colliders and the surface there climbs steeply, so any slope counts and, if
/// nothing is under the point, the search walks back toward the middle in 30 cm steps.
/// </summary>
private void FindArcherPosts(float hz)
{
ArcherPosts = new List<ArcherPost>();
AddPost(+0.93f * hz, -1f);
if (!BoneShip.IsKarveShip(this)) AddPost(-0.88f * hz, +1f);
}
private void AddPost(float z, float towardMiddle)
{
for (float back = 0f; back <= 2.4f; back += 0.3f)
{
Vector3 point;
if (!FindSurface(new Vector3(0f, RayStartHeight, z + towardMiddle * back), out point, -1f)) continue;
// A hand's breadth INTO the stem, not on top of it: the pelvis stub the bust leaves where the legs
// were then sits in the wood instead of resting on it, which is what made it look hung in air.
ArcherPosts.Add(new ArcherPost { Local = point + Vector3.down * 0.10f, Bust = true });
Jotunn.Logger.LogInfo($"[BoneShip] '{name}': archer post at local ({point.x:F2}, {point.y:F2}, {point.z:F2}) " +
(back > 0f ? $"(walked back {back:F1} m from the tip)." : "(at the tip)."));
return;
}
Jotunn.Logger.LogWarning($"[BoneShip] '{name}': no hull found for an archer at z {z:F1}; that post is empty.");
}
// ---------------------------------------------------------------- the altar
/// <summary>
/// The offering chest: a wooden chest standing on the deck NEXT TO THE CARGO HATCH. Every ship has
/// that hatch (the "piece_chest" Container, a flat square lid on the centre line: 0.9 m on the Karve,
/// 1.5 on the Longship, 1.8 on the Ashlands ship), so it is the one spot that is the same idea on all
/// three and the one a player already knows to look at. The first version put an altar of bones a
/// fixed distance down the centre line, which on the Karve is the stretch between the mast and the
/// helm, right where its rowers sit.
///
/// Candidate places are tried beside the hatch, then behind it, then in front, and a candidate is
/// taken only if the whole footprint of the chest lies on FLAT deck at the hatch's own height - five
/// rays, the centre and four points around it - and is clear of the mast. A Karve is narrow and its
/// hull closes in toward the bow, so beside the hatch is not always deck; the rays are what say so.
/// </summary>
private void BuildAltar(float hz, System.Random rng)
{
Vector3 spot;
string where;
if (!FindChestSpot(hz, out spot, out where))
{
Jotunn.Logger.LogWarning($"[BoneShip] '{name}': no flat deck found for the offering chest; it was not built.");
return;
}
GameObject chest = new GameObject("BoneChest");
chest.transform.SetParent(transform, false);
chest.transform.localPosition = spot;
// Its front toward the stern, where the helm is and where a player stands when he looks around.
chest.transform.localRotation = Quaternion.Euler(0f, 180f, 0f);
chest.layer = LayerMask.NameToLayer("piece_nonsolid");
// The model: the wooden chest of the game, shut, with a skull on the lid so it reads as ours.
GameObject template = TemplateOf(ChestPrefab);
if (template != null)
{
GameObject model = Object.Instantiate(template, chest.transform, false);
model.name = ChestPrefab;
model.transform.localPosition = Vector3.zero;
model.transform.localScale = Vector3.one * ChestSize;
// A chest prefab carries both an open and a closed lid; the container switches them at run
// time and the copy has no container, so the open one is turned off here.
foreach (Transform node in model.GetComponentsInChildren<Transform>(true))
{
if (node != model.transform && node.name.ToLowerInvariant() == "open") node.gameObject.SetActive(false);
}
}
else
{
Jotunn.Logger.LogWarning($"[BoneShip] No '{ChestPrefab}' to borrow; the offering chest is a box of fragments instead.");
Place(FragmentsPrefab, chest.transform, new Vector3(0f, 0f, 0f), 0.45f, rng, 10f);
}
Place(SkullPrefab, chest.transform, new Vector3(0f, ChestHeight, 0f), 0.26f, rng, 8f);
BoxCollider box = chest.AddComponent<BoxCollider>();
box.center = new Vector3(0f, ChestHeight * 0.5f, 0f);
box.size = new Vector3(ChestSize * 0.95f, ChestHeight, ChestSize * 0.65f);
Switch sw = chest.AddComponent<Switch>();
sw.m_name = BoneShip.AltarName;
Altar = sw;
BoneShipRoster roster = GetComponent<BoneShipRoster>();
if (roster != null) roster.Bind(sw);
Jotunn.Logger.LogInfo($"[BoneShip] '{name}': offering chest {where} the cargo hatch, at local " +
$"({spot.x:F2}, {spot.y:F2}, {spot.z:F2}).");
}
private bool FindChestSpot(float hz, out Vector3 spot, out string where)
{
spot = Vector3.zero;
where = "";
Transform hatch = transform.Find("piece_chest");
BoxCollider hatchBox = hatch != null ? hatch.GetComponent<BoxCollider>() : null;
if (hatch == null)
{
// A ship with no cargo hatch: the old rule, a fixed place down the centre line.
where = "(no hatch found, fixed spot behind the middle) of";
return FindSurface(new Vector3(0f, RayStartHeight, -0.42f * hz), out spot);
}
Vector3 centre = hatch.localPosition;
float half = hatchBox != null ? Mathf.Abs(hatchBox.size.x * hatch.localScale.x) * 0.5f : 0.6f;
float gap = half + ChestSize * 0.5f + 0.1f;
Vector3 hatchTop;
if (!FindSurface(new Vector3(centre.x, RayStartHeight, centre.z), out hatchTop)) return false;
float level = hatchTop.y;
// Beside first (the hatch is on the centre line, so beside is out toward a rail), then behind and
// in front. The mast is on the centre line too, and its collider is skipped by the ray, so it is
// kept away from by position.
Vector2[] offsets =
{
new Vector2(+gap, 0f), new Vector2(-gap, 0f), new Vector2(0f, -gap), new Vector2(0f, +gap),
};
string[] names = { "right of", "left of", "behind", "in front of" };
List<Vector2> masts = MastPositions();
for (int i = 0; i < offsets.Length; i++)
{
Vector2 c = new Vector2(centre.x + offsets[i].x, centre.z + offsets[i].y);
if (NearAny(masts, c, 0.7f)) continue;
if (!FlatDeckAround(c, level, ChestSize * 0.5f, out spot)) continue;
where = names[i];
return true;
}
return false;
}
/// <summary>
/// The chest's whole footprint is on deck: the centre and four points half a chest away all find a
/// surface that is flat and at the hatch's own height. Returns the centre's point.
/// </summary>
private bool FlatDeckAround(Vector2 c, float level, float reach, out Vector3 centre)
{
Vector2[] around = { Vector2.zero, new Vector2(reach, 0f), new Vector2(-reach, 0f), new Vector2(0f, reach), new Vector2(0f, -reach) };
centre = Vector3.zero;
for (int i = 0; i < around.Length; i++)
{
Vector3 p;
if (!FindSurface(new Vector3(c.x + around[i].x, RayStartHeight, c.y + around[i].y), out p, 0.85f)) return false;
if (Mathf.Abs(p.y - level) > 0.22f) return false;
if (i == 0) centre = p;
}
return true;
}
/// <summary>Within a couple of metres of the cargo hatch, on any side: where the chest will stand.</summary>
private bool NearHatch(float x, float z)
{
Transform hatch = transform.Find("piece_chest");
if (hatch == null) return false;
Vector2 d = new Vector2(x - hatch.localPosition.x, z - hatch.localPosition.z);
return d.sqrMagnitude < 2.2f * 2.2f;
}
private List<Vector2> MastPositions()
{
List<Vector2> masts = new List<Vector2>();
foreach (Transform t in GetComponentsInChildren<Transform>(true))
{
if (t == transform || t.name.ToLowerInvariant() != "mast") continue;
Vector3 local = transform.InverseTransformPoint(t.position);
masts.Add(new Vector2(local.x, local.z));
}
return masts;
}
private static bool NearAny(List<Vector2> points, Vector2 p, float distance)
{
foreach (Vector2 q in points)
{
if ((q - p).sqrMagnitude < distance * distance) return true;
}
return false;
}
// ---------------------------------------------------------------- placing
private bool PlaceOnRail(Vector3 point, int side, System.Random rng)
{
double roll = rng.NextDouble();
Vector3 up = point + Vector3.up * 0.02f;
if (roll < 0.38) return Place(SkullPrefab, up, Range(rng, 0.30f, 0.38f), rng, 14f);
if (roll < 0.70) return Place(FragmentsPrefab, up, Range(rng, 0.28f, 0.40f), rng, 180f);
if (roll < 0.88)
{
// The big ones lean outward over the side, like something draped there.
string large = LargestAvailable();
return Place(large ?? SkullPrefab, up + new Vector3(side * 0.05f, 0f, 0f), large != null ? Range(rng, 0.7f, 1.0f) : 0.42f, rng, 20f);
}
return false; // a gap, on purpose: a hull that is covered evenly looks decorated, not grown over
}
private bool Place(string prefabName, Vector3 localPosition, float size, System.Random rng, float tilt)
{
return Place(prefabName, transform, localPosition, size, rng, tilt);
}
private static bool Place(string prefabName, Transform parent, Vector3 localPosition, float size, System.Random rng, float tilt)
{
GameObject template = TemplateOf(prefabName);
if (template == null) return false;
GameObject copy = Object.Instantiate(template, parent, false);
copy.name = prefabName;
copy.transform.localPosition = localPosition;
copy.transform.localRotation = Quaternion.Euler(Range(rng, -tilt, tilt), (float)rng.NextDouble() * 360f, Range(rng, -tilt, tilt));
copy.transform.localScale = Vector3.one * size;
return true;
}
// ---------------------------------------------------------------- models
/// <summary>
/// One stripped, 1 m model per source prefab, kept under an inactive holder that survives scene loads.
/// Built on first use. The holder being inactive is what keeps the template from ever being drawn.
/// </summary>
private static GameObject TemplateOf(string prefabName)
{
GameObject cached;
if (s_templates.TryGetValue(prefabName, out cached)) return cached;
if (s_holder == null)
{
s_holder = new GameObject("RoV_BoneShipModels");
s_holder.SetActive(false);
Object.DontDestroyOnLoad(s_holder);
}
GameObject source = Jotunn.Managers.PrefabManager.Cache.GetPrefab<GameObject>(prefabName);
GameObject template = null;
if (source != null)
{
template = ModelBorrow.Attach(s_holder.transform, prefabName, source, Vector3.zero, Quaternion.identity, 1f, "BoneShip");
StripEffects(template);
}
s_templates[prefabName] = template;
return template;
}
/// <summary>
/// A dropped item is dressed to be seen from far away: sparkles, a glow, sometimes a light and a
/// sound. ModelBorrow removes everything that THINKS (scripts, colliders, bodies, the network
/// view) but a particle system or a light does not think, it just plays - so the first version of
/// the fittings lit every bone on the hull like a drop on the ground, and the whole ship glowed.
///
/// Only meshes are wanted. A node that carries an effect and no mesh goes with all its children;
/// otherwise just the effect components come off. A particle system cannot be removed while its
/// renderer is there, so the renderer goes first.
/// </summary>
internal static void StripEffects(GameObject template)
{
if (template == null) return;
foreach (ParticleSystem system in template.GetComponentsInChildren<ParticleSystem>(true))
{
if (system == null) continue;
GameObject node = system.gameObject;
if (node == template || node.GetComponent<MeshRenderer>() != null || node.GetComponent<SkinnedMeshRenderer>() != null)
{
ParticleSystemRenderer renderer = node.GetComponent<ParticleSystemRenderer>();
if (renderer != null) Object.DestroyImmediate(renderer);
Object.DestroyImmediate(system);
}
else
{
Object.DestroyImmediate(node);
}
}
foreach (Light light in template.GetComponentsInChildren<Light>(true))
{
if (light != null) Object.DestroyImmediate(light);
}
foreach (AudioSource audio in template.GetComponentsInChildren<AudioSource>(true))
{
if (audio != null) Object.DestroyImmediate(audio);
}
foreach (TrailRenderer trail in template.GetComponentsInChildren<TrailRenderer>(true))
{
if (trail != null) Object.DestroyImmediate(trail);
}
foreach (LineRenderer line in template.GetComponentsInChildren<LineRenderer>(true))
{
if (line != null) Object.DestroyImmediate(line);
}
}
private static string LargestAvailable()
{
foreach (string name in LargeBonePrefabs)
{
if (TemplateOf(name) != null) return name;
}
return null;
}
private static void ReportModels()
{
if (s_reported) return;
s_reported = true;
List<string> found = new List<string>();
List<string> missing = new List<string>();
foreach (string name in LargeBonePrefabs)
{
(TemplateOf(name) != null ? found : missing).Add(name);
}
Jotunn.Logger.LogInfo("[BoneShip] large bone models: found [" + string.Join(", ", found.ToArray()) +
"], missing [" + string.Join(", ", missing.ToArray()) + "].");
}
// ---------------------------------------------------------------- measuring
/// <summary>
/// The hull's footprint in the ship's own space, from the OnboardTrigger every ship has: the volume
/// the game uses to decide who is aboard is, by construction, about the hull.
/// </summary>
internal bool TryHullExtent(out Bounds bounds)
{
bounds = new Bounds();
Transform trigger = transform.Find("OnboardTrigger");
BoxCollider box = trigger != null ? trigger.GetComponent<BoxCollider>() : null;
if (box == null) return false;
Vector3 centre = transform.InverseTransformPoint(trigger.TransformPoint(box.center));
Vector3 size = Vector3.Scale(box.size, trigger.lossyScale) ;
size = new Vector3(Mathf.Abs(size.x), Mathf.Abs(size.y), Mathf.Abs(size.z));
bounds = new Bounds(centre, size);
return true;
}
/// <summary>
/// The top of the rail on one side at one z: scanned from outside the hull inward, the first ray that
/// lands on the ship is the outer edge of the rail.
/// </summary>
internal bool FindRail(int side, float z, float hx, out Vector3 point, ref int rays)
{
for (float x = 1.15f * hx; x > 0.3f * hx; x -= 0.12f)
{
rays++;
if (FindSurface(new Vector3(side * x, RayStartHeight, z), out point)) return true;
}
point = Vector3.zero;
return false;
}
/// <summary>
/// The highest solid surface of THIS ship under a local point, in local space. Triggers, and anything
/// whose name up the hierarchy says mast, sail, cloth or rope, are not the hull.
/// </summary>
internal bool FindSurface(Vector3 localOrigin, out Vector3 localPoint, float minUp = 0.2f)
{
Vector3 origin = transform.TransformPoint(localOrigin);
RaycastHit best = default(RaycastHit);
bool found = false;
float bestDistance = float.MaxValue;
foreach (RaycastHit hit in Physics.RaycastAll(origin, -transform.up, RayLength))
{
Collider collider = hit.collider;
if (collider == null || collider.isTrigger) continue;
if (!collider.transform.IsChildOf(transform)) continue;
if (Vector3.Dot(hit.normal, transform.up) < minUp) continue;
if (IsRigging(collider.transform)) continue;
if (hit.distance >= bestDistance) continue;
best = hit;
bestDistance = hit.distance;
found = true;
}
localPoint = found ? transform.InverseTransformPoint(best.point) : Vector3.zero;
return found;
}
private bool IsRigging(Transform t)
{
for (; t != null && t != transform; t = t.parent)
{
string n = t.name.ToLowerInvariant();
if (n.Contains("mast") || n.Contains("sail") || n.Contains("cloth") || n.Contains("rope")) return true;
}
return false;
}
private static float Range(System.Random rng, float min, float max)
{
return min + (float)rng.NextDouble() * (max - min);
}
}
}

View file

@ -0,0 +1,709 @@
using System;
using System.Collections.Generic;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// The ship as a mobile bone pile. Skeleton_BoneShip.txt, sections 5.3-5.7.
///
/// Bone fragments are offered at the altar, twenty to a PLACE, and a place is paid for once and refills
/// itself for ever - exactly the bone pile's economy (SkeletonBonePileBehaviour), because it is the same
/// design: nothing is created or consumed when a skeleton falls, the place simply stands up again.
///
/// What is different is where the troops are. UNDERWAY they are DATA: a count per kind in the ship's own
/// ZDO ("aboard"), no creature, no AI, nothing to fall in the water. When the ship has been stopped for a
/// few seconds with land in reach they come ashore one at a time, real tamed skeletons that follow whoever
/// built the ship; when it moves off again, the ones that are following and close enough go back aboard,
/// one at a time, and become a number again.
///
/// The rest of the world is COUNTED, never tallied. A troop's ZDO carries the id of its ship; "how many
/// are out" is however many loaded troops carry it. A death, a despawn, a player killing his own
/// skeleton all correct themselves, as on the pile. The known price is the pile's too: a troop in an
/// unloaded zone is not counted, so its place can refill while it is away.
///
/// Troops are NOT bound to a point (no RaisedThrall anchor): a ship moves, and the anchor logic would
/// read the empty water it sailed from as a fallen station and wither them. They are bound to the ship by
/// id, and die with it. Only the owner of the ship's ZDO runs any of this.
/// </summary>
public class BoneShipRoster : MonoBehaviour
{
// ZDO keys, on the ship.
private const string KeyBones = "RoV_bshBones";
private const string KeySlotsMelee = "RoV_bshSlotsM";
private const string KeySlotsRanged = "RoV_bshSlotsR";
private const string KeyAboardMelee = "RoV_bshAbM";
private const string KeyAboardRanged = "RoV_bshAbR";
/// <summary>
/// Set when a troop that was told to go home boards a ship that is standing still: they have been
/// called back on purpose, so nobody should be sent straight out again. Cleared the moment the ship
/// moves, so the next stop lands the crew as usual.
/// </summary>
private const string KeyHold = "RoV_bshHold";
/// <summary>A recalled troop further than BoardRange but within this many metres is walked to the ship.</summary>
private const float RecallReach = 80f;
/// <summary>How many rowers should show: everyone aboard. Read by the rowers when they exist.</summary>
public const string KeyRowers = "RoV_bshRowers";
/// <summary>ZDO key on a TROOP: the id of the ship it belongs to.</summary>
public const string KeyShip = "RoV_bshShip";
// ─── Balance. Same numbers as the pile where the idea is the same. ───
private const float TickSeconds = 0.5f;
private const float DockedSeconds = 2.5f; // stopped this long before anyone comes ashore
private const float UnderwaySeconds = 1.0f; // moving this long before anyone goes back aboard
private const float StepSeconds = 0.8f; // one troop at a time, this far apart
private const float StillSpeed = 0.6f; // m/s: slower than this counts as stopped
private const float BoardRange = 20f; // decided with the orders: same as the pile's home check
private const float LandingBand = 10f; // how far past the hull to look for shore
private const float LandingMargin = 0.25f; // metres above the water for it to count as land
private ZNetView m_nview;
private Ship m_ship;
private Rigidbody m_body;
// The archers are not troops and are not counted with them: their own key, their own check.
private const float ArcherCheckSeconds = 2f;
private const float ArcherGraceSeconds = 4f; // a post whose registered archer is gone this long gets a new one
private float m_archerTimer;
private float[] m_postEmptyFor = new float[0];
private float m_stillTime;
private float m_movingTime;
private float m_stepTimer;
private float m_refillTimer;
private int m_deployIndex;
private bool m_toldNoShore;
private readonly List<Vector3> m_recentLandings = new List<Vector3>();
private void Awake()
{
m_nview = GetComponent<ZNetView>();
m_ship = GetComponent<Ship>();
m_body = GetComponent<Rigidbody>();
if (m_nview == null || m_nview.GetZDO() == null) return; // a placement ghost
m_nview.Register<string, int>("RoV_BshFeed", RPC_Feed);
WearNTear wear = GetComponent<WearNTear>();
if (wear != null) wear.m_onDestroyed = (Action)Delegate.Combine(wear.m_onDestroyed, new Action(OnDestroyed));
InvokeRepeating("Tick", 2f, TickSeconds);
}
/// <summary>The altar's Switch, once the fittings have built it.</summary>
public void Bind(Switch altar)
{
if (altar == null) return;
altar.m_onUse = OnUse;
altar.m_onHover = Hover;
}
// ---------------------------------------------------------------- interaction
// With an item in hand every outcome counts as handled, refusals included: false makes
// Humanoid.UseItem cover our own message with the generic one. Same as the pile.
private bool OnUse(Switch caller, Humanoid user, ItemDrop.ItemData item)
{
return Use(user, item) || item != null;
}
private bool Use(Humanoid user, ItemDrop.ItemData item)
{
Player player = user as Player;
if (player == null || item == null) return false;
Inventory inventory = player.GetInventory();
if (inventory == null) return false;
string prefabName = item.m_dropPrefab != null ? item.m_dropPrefab.name : null;
if (prefabName != SkeletonBonePile.BonePrefab)
{
player.Message(MessageHud.MessageType.Center, "$msg_wontwork");
return false;
}
// Bone is measured in fragments, not places: what is left to buy, minus what is already part-paid
// towards the next place. Taken from the player only if the ship will actually keep it.
int room = (TotalCap() - PaidSlots()) * SkeletonBonePile.BonesPerSlot - m_nview.GetZDO().GetInt(KeyBones);
if (room <= 0)
{
player.Message(MessageHud.MessageType.Center, "$msg_itsfull");
return false;
}
int taken = Mathf.Min(Mathf.Max(1, item.m_stack), room);
player.Message(MessageHud.MessageType.Center, $"$msg_added {item.m_shared.m_name} x{taken}");
inventory.RemoveItem(item, taken);
m_nview.InvokeRPC("RoV_BshFeed", prefabName, taken);
return true;
}
private void RPC_Feed(long sender, string prefabName, int count)
{
if (!m_nview.IsOwner()) return;
if (prefabName != SkeletonBonePile.BonePrefab) return;
if (count < 1) count = 1;
int bones = m_nview.GetZDO().GetInt(KeyBones) + count;
// Melee places fill first, then the archers'. A loop, so a whole stack cannot overflow into bones
// that are never counted.
while (bones >= SkeletonBonePile.BonesPerSlot && PaidSlots() < TotalCap())
{
bones -= SkeletonBonePile.BonesPerSlot;
if (Slots(SkeletonBonePile.KindMelee) < MeleeCap()) SetSlots(SkeletonBonePile.KindMelee, Slots(SkeletonBonePile.KindMelee) + 1);
else SetSlots(SkeletonBonePile.KindRanged, Slots(SkeletonBonePile.KindRanged) + 1);
}
m_nview.GetZDO().Set(KeyBones, bones);
}
private string Hover()
{
int outM = CountDeployed(SkeletonBonePile.KindMelee);
int outR = CountDeployed(SkeletonBonePile.KindRanged);
int aboard = Aboard(SkeletonBonePile.KindMelee) + Aboard(SkeletonBonePile.KindRanged);
string body = ModText.Get("rov_hover_boneship_roster",
outM + Aboard(SkeletonBonePile.KindMelee), Slots(SkeletonBonePile.KindMelee), MeleeCap(),
outR + Aboard(SkeletonBonePile.KindRanged), Slots(SkeletonBonePile.KindRanged), RangedCap(),
aboard);
int bonesToward = m_nview.GetZDO().GetInt(KeyBones);
int placesLeft = TotalCap() - PaidSlots();
body += placesLeft > 0
? ModText.Get("rov_hover_skeleton_bone_toward_next_places", bonesToward, SkeletonBonePile.BonesPerSlot, placesLeft)
: ModText.Get("rov_hover_skeleton_every_place_bought");
if (m_refillTimer > 0f)
{
int left = Mathf.Max(1, Mathf.CeilToInt(SkeletonBonePile.RespawnSeconds - m_refillTimer));
body += ModText.Get("rov_hover_skeleton_next_rises_s", left);
}
body += ModText.Get("rov_hover_boneship_bone_hand");
return Localization.instance.Localize($"{BoneShip.AltarName} ({body})");
}
// ---------------------------------------------------------------- the tick
private void Tick()
{
if (m_nview == null || !m_nview.IsValid() || !m_nview.IsOwner()) return;
if (m_ship == null) return;
Refill();
PublishRowers();
m_archerTimer += TickSeconds;
if (m_archerTimer >= ArcherCheckSeconds)
{
TickArchers(m_archerTimer);
m_archerTimer = 0f;
}
bool stopped = m_ship.GetSpeedSetting() == Ship.Speed.Stop &&
(m_body == null || m_body.velocity.magnitude < StillSpeed);
if (stopped)
{
m_stillTime += TickSeconds;
m_movingTime = 0f;
}
else
{
m_movingTime += TickSeconds;
m_stillTime = 0f;
m_toldNoShore = false;
m_recentLandings.Clear();
}
// Moving off ends any hold: the next stop lands the crew as usual.
if (!stopped && m_movingTime >= UnderwaySeconds && m_nview.GetZDO().GetBool(KeyHold, false))
{
m_nview.GetZDO().Set(KeyHold, false);
}
WalkRecalled();
m_stepTimer -= TickSeconds;
if (m_stepTimer > 0f) return;
// A troop sent home boards whether the ship is moving or not; the ones merely following only
// when it is underway. Whichever is first takes the step.
bool underway = !stopped && m_movingTime >= UnderwaySeconds;
string boarded = BoardOne(underway);
if (boarded != null)
{
m_stepTimer = StepSeconds;
// Anyone who boards while the ship is standing still came aboard on purpose - called back, or
// walked up the plank - and must not be sent straight out again. Held until the ship moves.
if (stopped) m_nview.GetZDO().Set(KeyHold, true);
return;
}
if (stopped && m_stillTime >= DockedSeconds && !m_nview.GetZDO().GetBool(KeyHold, false))
{
if (TryDeploy()) m_stepTimer = StepSeconds;
}
}
/// <summary>
/// A paid place with nobody in it - not aboard and not standing somewhere - fills after a while, as
/// the pile's does. Melee first. It fills ABOARD, so on a stopped ship it is then the next to come
/// ashore by the ordinary route.
/// </summary>
private void Refill()
{
string empty = FirstEmptyKind();
if (empty == null)
{
m_refillTimer = 0f;
return;
}
m_refillTimer += TickSeconds;
if (m_refillTimer < SkeletonBonePile.RespawnSeconds) return;
m_refillTimer = 0f;
SetAboard(empty, Aboard(empty) + 1);
}
private string FirstEmptyKind()
{
if (Slots(SkeletonBonePile.KindMelee) - CountDeployed(SkeletonBonePile.KindMelee) - Aboard(SkeletonBonePile.KindMelee) > 0)
return SkeletonBonePile.KindMelee;
if (Slots(SkeletonBonePile.KindRanged) - CountDeployed(SkeletonBonePile.KindRanged) - Aboard(SkeletonBonePile.KindRanged) > 0)
return SkeletonBonePile.KindRanged;
return null;
}
private void PublishRowers()
{
int rowers = Aboard(SkeletonBonePile.KindMelee) + Aboard(SkeletonBonePile.KindRanged);
if (m_nview.GetZDO().GetInt(KeyRowers, -1) != rowers) m_nview.GetZDO().Set(KeyRowers, rowers);
}
// ---------------------------------------------------------------- coming ashore
private bool TryDeploy()
{
int melee = Aboard(SkeletonBonePile.KindMelee);
int ranged = Aboard(SkeletonBonePile.KindRanged);
if (melee + ranged == 0) return false;
Vector3 landing;
if (!FindLanding(out landing))
{
// Open water or a cliff: they stay at the oars. Said once per stop, to whoever is looking.
if (!m_toldNoShore && Player.m_localPlayer != null &&
Vector3.Distance(Player.m_localPlayer.transform.position, transform.position) < 40f)
{
Player.m_localPlayer.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_boneship_no_shore"));
}
m_toldNoShore = true;
return false;
}
// Whichever kind has more waiting goes first, so the line comes ashore mixed, not all spears then all bows.
string kind = melee >= ranged ? SkeletonBonePile.KindMelee : SkeletonBonePile.KindRanged;
string prefabName = kind == SkeletonBonePile.KindRanged ? SkeletonBonePile.ThrallRangedName : SkeletonBonePile.ThrallMeleeName;
GameObject prefab = ZNetScene.instance != null ? ZNetScene.instance.GetPrefab(prefabName) : null;
if (prefab == null)
{
Jotunn.Logger.LogWarning($"[BoneShip] No '{prefabName}' in ZNetScene; nothing can come ashore.");
return false;
}
GameObject spawned = Instantiate(prefab, landing, Quaternion.Euler(0f, UnityEngine.Random.Range(0, 360), 0f));
// Tamed, so it never turns on its master: the two calls RaisedThrall.Bind makes, without the anchor.
MonsterAI ai = spawned.GetComponent<MonsterAI>();
if (ai != null) ai.MakeTame();
Character character = spawned.GetComponent<Character>();
if (character != null) character.SetTamed(true);
ZNetView troopView = spawned.GetComponent<ZNetView>();
if (troopView != null && troopView.GetZDO() != null) troopView.GetZDO().Set(KeyShip, m_nview.GetZDO().m_uid);
// Out and following their master. NOT through RaisedThrall.SetFollowing: that refuses anyone who is
// not a Skeleton, and the ship is open to every race - a non-Skeleton's crew would come ashore, stand
// there, and never be able to come back aboard, because boarding is for the ones that follow. So the
// follow target is set directly, as the ship's own right.
Player master = Master();
if (ai != null && master != null) ai.SetFollowTarget(master.gameObject);
SetAboard(kind, Aboard(kind) - 1);
m_recentLandings.Add(landing);
if (m_recentLandings.Count > 12) m_recentLandings.RemoveAt(0);
return true;
}
/// <summary>
/// Dry land near the hull. Looks on rings around the ship, nearest first, from just past the hull out
/// to LandingBand metres beyond it; a point is land if the terrain there is above the water. The first
/// ring angle moves on with each troop, and a point near one already used is skipped, so they do not
/// all stack on one spot.
/// </summary>
private bool FindLanding(out Vector3 landing)
{
landing = Vector3.zero;
if (ZoneSystem.instance == null) return false;
float hull = Mathf.Max(BoneShip.HalfLengthOf(this), 4f);
float water = ZoneSystem.instance.m_waterLevel + LandingMargin;
for (float radius = hull + 1.5f; radius <= hull + 1.5f + LandingBand; radius += 1.5f)
{
for (int step = 0; step < 24; step++)
{
float angle = (m_deployIndex * 47f + step * 15f) * Mathf.Deg2Rad;
Vector3 point = transform.position + new Vector3(Mathf.Cos(angle), 0f, Mathf.Sin(angle)) * radius;
float ground = ZoneSystem.instance.GetGroundHeight(point);
if (ground < water) continue;
if (NearRecent(point)) continue;
landing = new Vector3(point.x, ground + 0.5f, point.z);
m_deployIndex++;
return true;
}
}
return false;
}
private bool NearRecent(Vector3 point)
{
foreach (Vector3 used in m_recentLandings)
{
Vector3 d = used - point;
d.y = 0f;
if (d.sqrMagnitude < 1.4f * 1.4f) return true;
}
return false;
}
// ---------------------------------------------------------------- going back aboard
/// <summary>
/// Takes ONE troop back aboard: it vanishes and the count goes up. Which: the nearest, within
/// BoardRange, that was SENT HOME (a "go home" order, the troop's RoV_bshRecall flag) - or, when the
/// ship is underway, that is following its master. Ones told to wait, and followers when the ship is
/// standing still, stay where they are: an outpost, still counted, still this ship's.
/// Returns "recalled" or "following" for what it took, null for nothing.
/// </summary>
private string BoardOne(bool underway)
{
Player master = Master();
Character nearest = null;
RaisedThrall nearestThrall = null;
bool nearestRecalled = false;
float best = BoardRange * BoardRange;
foreach (Character character in Character.GetAllCharacters())
{
if (character == null || character.IsDead() || !BelongsHere(character)) continue;
RaisedThrall thrall = character.GetComponent<RaisedThrall>();
if (thrall == null) continue;
bool recalled = IsRecalled(character);
// A troop that follows its master and has WALKED ONTO THE DECK is aboard, whatever the ship is
// doing: standing about on the planks as a creature is not what a crew is. The first version
// only took followers once the ship was underway, so stepping off and back on left the crew
// standing on deck, never at the oars, until the ship moved.
bool followingMaster = master != null && thrall.IsFollowing(master);
bool following = followingMaster && (underway || OnDeck(character));
if (!recalled && !following) continue;
float distance = (character.transform.position - transform.position).sqrMagnitude;
if (distance >= best) continue;
best = distance;
nearest = character;
nearestThrall = thrall;
nearestRecalled = recalled;
}
if (nearest == null) return null;
string kind = nearestThrall.Kind == SkeletonBonePile.KindRanged ? SkeletonBonePile.KindRanged : SkeletonBonePile.KindMelee;
ZNetView troopView = nearest.GetComponent<ZNetView>();
if (troopView != null) troopView.ClaimOwnership(); // it may belong to another client's zone
ZNetScene.instance.Destroy(nearest.gameObject);
SetAboard(kind, Aboard(kind) + 1);
return nearestRecalled ? "recalled" : "following";
}
/// <summary>
/// A recalled troop out of boarding range walks to the ship: its patrol point is pinned on the ship
/// every tick, because the ship may be moving. Past RecallReach it is not chased - out of earshot.
/// </summary>
private void WalkRecalled()
{
foreach (Character character in Character.GetAllCharacters())
{
if (character == null || character.IsDead() || !BelongsHere(character)) continue;
if (!IsRecalled(character)) continue;
float distance = Vector3.Distance(character.transform.position, transform.position);
if (distance <= BoardRange || distance > RecallReach) continue;
RaisedThrall thrall = character.GetComponent<RaisedThrall>();
if (thrall != null) thrall.WalkTo(transform.position);
}
}
/// <summary>Standing inside the hull's boarding volume: the same box the game uses to decide who is aboard.</summary>
private bool OnDeck(Character character)
{
BoneShipFittings fittings = GetComponent<BoneShipFittings>();
Bounds hull;
if (fittings == null || !fittings.TryHullExtent(out hull)) return false;
return hull.Contains(transform.InverseTransformPoint(character.transform.position));
}
private static bool IsRecalled(Character character)
{
ZNetView view = character.GetComponent<ZNetView>();
return view != null && view.GetZDO() != null && view.GetZDO().GetBool(RaisedThrall.KeyRecall, false);
}
// ---------------------------------------------------------------- the archers
/// <summary>
/// Keeps the ship's archers standing. Counted from the world, like the troops: a loaded archer
/// carrying this ship's id and a post number holds that post. A post nobody holds for a while gets a
/// new archer - not at once, because after a reload the ship is loaded a moment before the archers
/// that were standing on it, and spawning then would double them. A second archer found on a post
/// that is already held is removed.
/// </summary>
private void TickArchers(float elapsed)
{
BoneShipFittings fittings = GetComponent<BoneShipFittings>();
if (fittings == null || fittings.ArcherPosts == null) return; // the hull is not measured yet
int posts = fittings.ArcherPosts.Count;
if (m_postEmptyFor.Length != posts) m_postEmptyFor = new float[posts];
ZDO shipZdo = m_nview.GetZDO();
ZDOID mine = shipZdo.m_uid;
// ---- 1. the archers that are in the world now: adopt the first of each post, remove the rest.
//
// The ship keeps a REGISTER of who holds each post (its own ZDO, one id per post). The first
// version only counted the archers it could see and spawned one for any post it saw nobody on -
// and "can see" is only what is loaded, so a ship that woke before its archers did, or a post
// whose archer sat in a zone the owner had not loaded, got a second archer on top of the first,
// again at every reload. The register does not depend on what is loaded. Archers made before the
// register existed have no entry: the first found is adopted, the others are the duplicates.
foreach (Character character in Character.GetAllCharacters())
{
if (character == null) continue;
ZNetView view = character.GetComponent<ZNetView>();
if (view == null || view.GetZDO() == null) continue;
if (view.GetZDO().GetZDOID(ShipMount.KeyArcherShip) != mine) continue;
int post = view.GetZDO().GetInt(ShipMount.KeyArcherPost, -1);
if (post < 0 || post >= posts)
{
RemoveArcher(character, view, "a post this ship no longer has");
continue;
}
ZDOID registered = shipZdo.GetZDOID(SlotKey(post));
ZDOID self = view.GetZDO().m_uid;
if (registered == ZDOID.None) shipZdo.Set(SlotKey(post), self);
else if (registered != self) RemoveArcher(character, view, "a duplicate on post " + post);
}
// ---- 2. posts whose registered archer is gone: a new one, after a short grace.
GameObject prefab = ZNetScene.instance != null ? ZNetScene.instance.GetPrefab(BoneShipArcher.Name) : null;
for (int i = 0; i < posts; i++)
{
ZDOID registered = shipZdo.GetZDOID(SlotKey(i));
bool exists = registered != ZDOID.None && ZDOMan.instance != null && ZDOMan.instance.GetZDO(registered) != null;
if (exists)
{
m_postEmptyFor[i] = 0f;
continue;
}
m_postEmptyFor[i] += elapsed;
if (m_postEmptyFor[i] < ArcherGraceSeconds) continue;
m_postEmptyFor[i] = 0f;
if (prefab == null)
{
Jotunn.Logger.LogWarning($"[BoneShip] No '{BoneShipArcher.Name}' in ZNetScene; the ship has no archer at post {i}.");
continue;
}
SpawnArcher(prefab, i, fittings.ArcherPosts[i]);
}
}
private static string SlotKey(int post) => "RoV_bshArcher" + post;
private void RemoveArcher(Character character, ZNetView view, string why)
{
Jotunn.Logger.LogInfo($"[BoneShip] '{name}': removing an archer - {why}.");
view.ClaimOwnership();
ZNetScene.instance.Destroy(character.gameObject);
}
private void SpawnArcher(GameObject prefab, int post, BoneShipFittings.ArcherPost at)
{
Vector3 world = transform.TransformPoint(at.Local);
GameObject archer = Instantiate(prefab, world, transform.rotation);
// The ship's id and the place on it go into the archer's own ZDO at once, before its mount first
// runs, so it knows where it stands from its first physics step - and again after any reload.
ZNetView view = archer.GetComponent<ZNetView>();
if (view != null && view.GetZDO() != null)
{
ZDO zdo = view.GetZDO();
zdo.Set(ShipMount.KeyArcherShip, m_nview.GetZDO().m_uid);
zdo.Set(ShipMount.KeyArcherPoint, at.Local);
zdo.Set(ShipMount.KeyArcherBust, at.Bust);
zdo.Set(ShipMount.KeyArcherPost, post);
// Signed into the ship's register straight away, so the very next check already knows.
m_nview.GetZDO().Set(SlotKey(post), zdo.m_uid);
Jotunn.Logger.LogInfo($"[BoneShip] '{name}': archer raised on post {post} at local " +
$"({at.Local.x:F2}, {at.Local.y:F2}, {at.Local.z:F2}).");
}
// Tamed, so it never turns on whoever is aboard: the two calls the sentry's seed makes.
MonsterAI ai = archer.GetComponent<MonsterAI>();
if (ai != null) ai.MakeTame();
Character character = archer.GetComponent<Character>();
if (character != null) character.SetTamed(true);
}
// ---------------------------------------------------------------- the ship falls
/// <summary>
/// The ship going down takes its troops with it, those that are loaded. Same as the pile's immediate
/// off switch: a garrison that refills for free needs something that ends it. Any in an unloaded zone
/// outlive the ship - the known gap, noted in the design.
/// </summary>
private void OnDestroyed()
{
if (m_nview == null || !m_nview.IsOwner()) return;
int lost = 0;
foreach (Character character in Character.GetAllCharacters())
{
if (character == null || character.IsDead() || !BelongsHere(character)) continue;
RaisedThrall thrall = character.GetComponent<RaisedThrall>();
if (thrall != null) thrall.Kill();
lost++;
}
// The archers go down with it as well; they are not counted among the troops that are lost.
ZDOID mine = m_nview.GetZDO().m_uid;
foreach (Character character in Character.GetAllCharacters())
{
if (character == null) continue;
ZNetView view = character.GetComponent<ZNetView>();
if (view == null || view.GetZDO() == null) continue;
if (view.GetZDO().GetZDOID(ShipMount.KeyArcherShip) != mine) continue;
view.ClaimOwnership();
ZNetScene.instance.Destroy(character.gameObject);
}
if (lost > 0 && Player.m_localPlayer != null)
{
Player.m_localPlayer.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_boneship_sunk", lost));
}
}
// ---------------------------------------------------------------- state
private Player Master()
{
Piece piece = GetComponent<Piece>();
long creator = piece != null ? piece.GetCreator() : 0L;
if (creator != 0L)
{
foreach (Player player in Player.GetAllPlayers())
{
if (player != null && player.GetPlayerID() == creator) return player;
}
}
// Its builder is not here: whoever is nearest, so a ship found abandoned is still crewed.
return Player.GetClosestPlayer(transform.position, 40f);
}
private bool BelongsHere(Character character)
{
ZNetView view = character.GetComponent<ZNetView>();
if (view == null || view.GetZDO() == null) return false;
return view.GetZDO().GetZDOID(KeyShip) == m_nview.GetZDO().m_uid;
}
private int CountDeployed(string kind)
{
int count = 0;
foreach (Character character in Character.GetAllCharacters())
{
if (character == null || character.IsDead() || !BelongsHere(character)) continue;
RaisedThrall thrall = character.GetComponent<RaisedThrall>();
string troopKind = thrall != null && thrall.Kind == SkeletonBonePile.KindRanged
? SkeletonBonePile.KindRanged : SkeletonBonePile.KindMelee;
if (troopKind == kind) count++;
}
return count;
}
private int Slots(string kind) => m_nview != null && m_nview.IsValid() ? m_nview.GetZDO().GetInt(kind == SkeletonBonePile.KindRanged ? KeySlotsRanged : KeySlotsMelee) : 0;
private void SetSlots(string kind, int value)
{
if (m_nview != null && m_nview.IsValid()) m_nview.GetZDO().Set(kind == SkeletonBonePile.KindRanged ? KeySlotsRanged : KeySlotsMelee, Mathf.Max(0, value));
}
private int Aboard(string kind) => m_nview != null && m_nview.IsValid() ? m_nview.GetZDO().GetInt(kind == SkeletonBonePile.KindRanged ? KeyAboardRanged : KeyAboardMelee) : 0;
private void SetAboard(string kind, int value)
{
if (m_nview != null && m_nview.IsValid()) m_nview.GetZDO().Set(kind == SkeletonBonePile.KindRanged ? KeyAboardRanged : KeyAboardMelee, Mathf.Max(0, value));
}
private int PaidSlots() => Slots(SkeletonBonePile.KindMelee) + Slots(SkeletonBonePile.KindRanged);
private int MeleeCap() => BoneShip.MeleeCapOf(this);
private int RangedCap() => BoneShip.RangedCapOf(this);
private int TotalCap() => MeleeCap() + RangedCap();
}
}

View file

@ -0,0 +1,480 @@
using System.Collections;
using System.Collections.Generic;
using HarmonyLib;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// The oarsmen: skeletons seated at benches along both sides, pulling oars, who are the reason a ship
/// with no wind in its sail goes anywhere. Skeleton_BoneShip.txt, sections 1 and 3.4.
///
/// PURE SCENERY. There is no creature here: no Character, no AI, no network object. Each is a copy of the
/// skeleton's MODEL, and how many are visible is one number the roster keeps in the ship's own ZDO
/// (RoV_bshRowers = how many troops are aboard), so every client draws the same crew and they come
/// ashore one at a time exactly as the roster says. How hard they pull is the ship's own gear
/// (Stop, Slow, Half, Full, Back), which every client already has, so nothing here needs to be sent.
///
/// NOTHING TO REUSE: no ship in the game has oars (the dump found none), so the oars are built here too,
/// from two stretched cubes in the ship's own wood.
///
/// SEATED WITHOUT A SEATED ANIMATION. The model stands, but is lowered until its hips are at bench
/// height: the legs go down through the deck, which hides them from above, so what shows is a body sitting
/// at a bench. The same trick as the bust at the bow, and for the same reason - the model cannot be cut.
///
/// THE ARMS follow the oar. Each arm bone is turned, in world space, to point at its grip on the handle
/// (FromToRotation from where it points now to where the grip is), after the animator has posed it, so
/// nothing depends on the rig's local axes, which were never read. The bones are found by name (the rig is
/// Mixamo-style: LeftArm, LeftForeArm, LeftHand) and, when any is missing, the whole skeleton is logged
/// once so the names can be corrected; the crew then still sits and rocks, with arms at their sides.
///
/// THE STROKE. One shared phase per ship, all oars in time. The blade sweeps aft in the water (the pull,
/// the rower leans back and the handle comes toward his chest) and forward out of it (the recovery, the
/// blade lifted). The period follows the gear; Back runs it in reverse; Stop lets the oars settle level.
/// </summary>
public class BoneShipRowers : MonoBehaviour
{
// The model, and how big the oarsmen are.
private const string SkeletonPrefab = "Skeleton";
private const float ModelHeight = 1.7f;
// Where on the hull they sit, as fractions of the half length, from the stern forward. The Karve's
// are further apart because its helm and bow seats leave less room between.
// The Karve's front pair moved from +0.22 to -0.12 of the half length: the cargo hatch is at z = +1.3
// and the offering chest stands beside it, and a bench at +1.0 was in the way.
private static readonly float[] SmallSeatsZ = { -0.40f, -0.12f };
private static readonly float[] LargeSeatsZ = { -0.50f, -0.26f, -0.02f, 0.22f };
private const float SeatHeight = 0.47f; // hips above the deck: a bench and a little
private const float OarlockLift = 0.12f; // oarlock above the rail's top
private const float OarInboard = 0.75f; // handle end, from the oarlock
private const float OarOutboard = 1.70f; // blade end
// The stroke.
private const float SweepMax = 0.45f; // radians, blade fore and aft
private const float LiftMax = 0.35f; // radians, blade up on the recovery
private const float LeanMax = 14f; // degrees, rower back and forth
private const float PeriodSlow = 2.6f;
private const float PeriodHalf = 1.9f;
private const float PeriodFull = 1.3f;
private class Seat
{
public GameObject Root; // at the hips, in the ship's space
public GameObject Bench;
public Transform Lean; // rotates about the hips
public Transform Oar;
public int Side; // +1 right, -1 left
public Vector3 Oarlock; // ship space
public Transform LeftArm, LeftFore, LeftHand, RightArm, RightFore, RightHand;
}
private readonly List<Seat> m_seats = new List<Seat>();
private ZNetView m_nview;
private Ship m_ship;
private float m_phase;
private float m_amplitude;
private bool m_built;
private static GameObject s_holder;
private static GameObject s_template;
private static bool s_templateTried;
private static Mesh s_cube;
private static bool s_loggedBones;
private void Start()
{
m_nview = GetComponent<ZNetView>();
m_ship = GetComponent<Ship>();
if (m_nview == null || !m_nview.IsValid()) return; // a placement ghost
StartCoroutine(Build());
}
// ---------------------------------------------------------------- building
private IEnumerator Build()
{
// The fittings measure the hull the same way, a physics step after the ship exists.
yield return new WaitForFixedUpdate();
yield return null;
yield return null;
BoneShipFittings fittings = GetComponent<BoneShipFittings>();
Bounds hull;
if (fittings == null || !fittings.TryHullExtent(out hull))
{
Jotunn.Logger.LogWarning($"[BoneShip] '{name}': no hull to seat rowers on.");
yield break;
}
GameObject template = Template();
if (template == null)
{
Jotunn.Logger.LogWarning($"[BoneShip] No '{SkeletonPrefab}' model; '{name}' has no rowers.");
yield break;
}
float hx = hull.extents.x;
float hz = hull.extents.z;
float[] zs = SeatStations((BoneShip.MeleeCapOf(this) + BoneShip.RangedCapOf(this)) / 2);
Material wood = FindWood();
int rays = 0;
for (int side = -1; side <= 1; side += 2)
{
foreach (float f in zs)
{
float z = f * hz;
Vector3 rail;
if (!fittings.FindRail(side, z, hx, out rail, ref rays)) continue;
float seatX = side * Mathf.Max(0.45f, Mathf.Abs(rail.x) - 0.55f);
Vector3 deck;
if (!fittings.FindSurface(new Vector3(seatX, BoneShipFittings.RayStartHeight, z), out deck)) continue;
m_seats.Add(MakeSeat(template, wood, side, deck, rail, z));
if (++rays >= 30) { rays = 0; yield return null; }
}
}
// Fill order: both sides at each station, from the bow back, so a short crew is balanced.
m_seats.Sort((a, b) =>
{
int byStation = b.Root.transform.localPosition.z.CompareTo(a.Root.transform.localPosition.z);
return byStation != 0 ? byStation : a.Side.CompareTo(b.Side);
});
m_built = true;
Jotunn.Logger.LogInfo($"[BoneShip] '{name}': {m_seats.Count} rowers' seats built.");
}
/// <summary>
/// Where along the hull the benches go, for this many on each side: the hand-placed lists where they
/// were tuned (two on the Karve, four on the Longship), an even spread from the stern forward for any
/// other number - the Ashlands ship has six a side.
/// </summary>
private static float[] SeatStations(int perSide)
{
if (perSide == SmallSeatsZ.Length) return SmallSeatsZ;
if (perSide == LargeSeatsZ.Length) return LargeSeatsZ;
float[] stations = new float[perSide];
for (int i = 0; i < perSide; i++)
{
float t = perSide == 1 ? 0.5f : i / (float)(perSide - 1);
stations[i] = Mathf.Lerp(-0.52f, 0.24f, t);
}
return stations;
}
private Seat MakeSeat(GameObject template, Material wood, int side, Vector3 deck, Vector3 rail, float z)
{
Seat seat = new Seat { Side = side };
// The hips, at bench height above the deck.
GameObject root = new GameObject("Rower");
root.transform.SetParent(transform, false);
root.transform.localPosition = deck + Vector3.up * SeatHeight;
seat.Root = root;
GameObject lean = new GameObject("Lean");
lean.transform.SetParent(root.transform, false);
seat.Lean = lean.transform;
// Facing the stern, as an oarsman does. The model's own front turned out to be the OTHER way from
// what a 180 degree turn assumed - the first build had the crew looking at the bow - so it is
// left as it comes: no turn.
GameObject model = Instantiate(template, lean.transform, false);
model.name = "model";
model.transform.localRotation = Quaternion.identity;
model.transform.localScale = Vector3.one * (ModelHeight / 1.8f);
model.SetActive(true);
Animator animator = model.GetComponentInChildren<Animator>(true);
if (animator != null)
{
// The idle clip fires animation events at a receiver the strip removed: unanswered, each
// one logs an error. Switched off, the clip still poses the body.
animator.fireEvents = false;
animator.applyRootMotion = false;
}
FindBones(model.transform, seat);
SeatHips(model.transform, lean.transform, seat);
// A bench, across the beam, so nobody sits on nothing.
GameObject bench = MakeBox("Bench", transform, wood, new Vector3(0.85f, 0.07f, 0.34f));
bench.transform.localPosition = new Vector3(deck.x, deck.y + SeatHeight - 0.09f, z);
// The oar: pivot at the oarlock on the rail, a shaft and a blade along its own +z (outboard).
seat.Oarlock = new Vector3(rail.x, rail.y + OarlockLift, z);
GameObject oar = new GameObject("Oar");
oar.transform.SetParent(transform, false);
oar.transform.localPosition = seat.Oarlock;
seat.Oar = oar.transform;
float length = OarInboard + OarOutboard;
GameObject shaft = MakeBox("Shaft", oar.transform, wood, new Vector3(0.07f, 0.07f, length));
shaft.transform.localPosition = new Vector3(0f, 0f, (OarOutboard - OarInboard) * 0.5f);
GameObject blade = MakeBox("Blade", oar.transform, wood, new Vector3(0.20f, 0.03f, 0.55f));
blade.transform.localPosition = new Vector3(0f, 0f, OarOutboard - 0.27f);
root.SetActive(false);
oar.SetActive(false);
bench.SetActive(false);
seat.Root = root;
seat.Bench = bench;
return seat;
}
/// <summary>Moves the model so its hips sit on the lean pivot - or, if no hips are found, by height.</summary>
private static void SeatHips(Transform model, Transform pivot, Seat seat)
{
Transform hips = Find(model, "hips") ?? Find(model, "pelvis");
if (hips != null)
{
Vector3 hipsInPivot = pivot.InverseTransformPoint(hips.position);
model.localPosition -= hipsInPivot;
}
else
{
model.localPosition = new Vector3(0f, -0.95f * (ModelHeight / 1.8f), 0f);
}
}
// ---------------------------------------------------------------- the stroke
private void Update()
{
if (!m_built || m_ship == null || m_nview == null || !m_nview.IsValid()) return;
int crew = m_nview.GetZDO().GetInt(BoneShipRoster.KeyRowers, 0);
Ship.Speed gear = m_ship.GetSpeedSetting();
float period = gear == Ship.Speed.Full ? PeriodFull : gear == Ship.Speed.Half ? PeriodHalf : PeriodSlow;
bool rowing = gear != Ship.Speed.Stop && (crew > 0);
m_amplitude = Mathf.MoveTowards(m_amplitude, rowing ? 1f : 0f, Time.deltaTime * 1.5f);
if (rowing) m_phase = Mathf.Repeat(m_phase + Time.deltaTime / period * (gear == Ship.Speed.Back ? -1f : 1f), 1f);
float twoPi = Mathf.PI * 2f;
float sweep = -Mathf.Cos(twoPi * m_phase); // forward extreme at 0, aft at 0.5
float recovery = Mathf.Clamp01(-Mathf.Sin(twoPi * m_phase) * 2f); // 1 mid-recovery, 0 in the water
recovery = recovery * recovery * (3f - 2f * recovery);
float lift = Mathf.Lerp(-0.08f, LiftMax, recovery);
float lean = LeanMax * sweep;
for (int i = 0; i < m_seats.Count; i++)
{
Seat seat = m_seats[i];
bool shown = i < crew;
seat.Root.SetActive(shown);
seat.Oar.gameObject.SetActive(shown);
seat.Bench.SetActive(shown);
if (!shown) continue;
float psi = SweepMax * sweep * m_amplitude;
float lam = Mathf.Lerp(0.10f, lift, m_amplitude);
// The oar's outboard direction in the ship's space: out across the beam, a little fore or
// aft with the sweep (positive aft), and tilted up by the lift.
Vector3 outward = new Vector3(seat.Side * Mathf.Cos(psi) * Mathf.Cos(lam),
Mathf.Sin(lam),
-Mathf.Sin(psi) * Mathf.Cos(lam));
seat.Oar.localRotation = Quaternion.LookRotation(outward, Vector3.up);
seat.Lean.localRotation = Quaternion.AngleAxis(lean * m_amplitude, Vector3.right);
}
}
/// <summary>After the animator: the arms reach for the handle.</summary>
private void LateUpdate()
{
if (!m_built) return;
foreach (Seat seat in m_seats)
{
if (!seat.Root.activeSelf) continue;
// Two grips on the handle, near and far from the chest.
Vector3 gripNear = seat.Oar.TransformPoint(0f, 0f, -OarInboard * 0.55f);
Vector3 gripFar = seat.Oar.TransformPoint(0f, 0f, -OarInboard * 0.15f);
Reach(seat.LeftArm, seat.LeftFore, gripNear);
Reach(seat.LeftFore, seat.LeftHand, gripNear);
Reach(seat.RightArm, seat.RightFore, gripFar);
Reach(seat.RightFore, seat.RightHand, gripFar);
}
}
/// <summary>Turns a bone, in world space, so the line to its child points at the target.</summary>
private static void Reach(Transform bone, Transform child, Vector3 target)
{
if (bone == null || child == null) return;
Vector3 now = child.position - bone.position;
Vector3 want = target - bone.position;
if (now.sqrMagnitude < 1e-6f || want.sqrMagnitude < 1e-6f) return;
bone.rotation = Quaternion.FromToRotation(now, want) * bone.rotation;
}
// ---------------------------------------------------------------- bones
private static void FindBones(Transform model, Seat seat)
{
seat.LeftArm = Find(model, "leftarm");
seat.LeftFore = Find(model, "leftforearm");
seat.LeftHand = Find(model, "lefthand");
seat.RightArm = Find(model, "rightarm");
seat.RightFore = Find(model, "rightforearm");
seat.RightHand = Find(model, "righthand");
if (seat.LeftArm != null && seat.LeftFore != null && seat.LeftHand != null &&
seat.RightArm != null && seat.RightFore != null && seat.RightHand != null) return;
if (s_loggedBones) return;
s_loggedBones = true;
List<string> names = new List<string>();
foreach (Transform t in model.GetComponentsInChildren<Transform>(true)) names.Add(t.name);
Jotunn.Logger.LogWarning("[BoneShip] The rowers' arm bones were not all found by name; they will hang at " +
"their sides. Skeleton: " + string.Join(", ", names.ToArray()));
}
/// <summary>A bone by name, ignoring case and any "mixamorig:"-style prefix.</summary>
private static Transform Find(Transform root, string lowerName)
{
foreach (Transform t in root.GetComponentsInChildren<Transform>(true))
{
string n = t.name.ToLowerInvariant();
int colon = n.LastIndexOf(':');
if (colon >= 0) n = n.Substring(colon + 1);
if (n == lowerName) return t;
}
return null;
}
// ---------------------------------------------------------------- model, wood, boxes
/// <summary>
/// The skeleton's model with nothing that acts. Instantiated into an INACTIVE holder, so nothing wakes,
/// and then stripped in DEPENDENCY order: ModelBorrow's one pass is not safe on a creature, because
/// Unity refuses to remove a component another one requires - Humanoid under CharacterDrop - and the
/// Humanoid it leaves behind is a live creature. The Hive taught that: it broke the hammer for every
/// piece in the game. So each pass removes only what nothing still present requires, and passes repeat.
/// </summary>
private static GameObject Template()
{
if (s_templateTried) return s_template;
s_templateTried = true;
GameObject source = Jotunn.Managers.PrefabManager.Cache.GetPrefab<GameObject>(SkeletonPrefab);
if (source == null) return null;
s_holder = new GameObject("RoV_BoneShipRowers");
s_holder.SetActive(false);
Object.DontDestroyOnLoad(s_holder);
GameObject copy = Object.Instantiate(source, s_holder.transform);
copy.name = "RowerTemplate";
StripBehaviours(copy);
foreach (Rigidbody body in copy.GetComponentsInChildren<Rigidbody>(true)) if (body != null) Object.DestroyImmediate(body);
foreach (Collider collider in copy.GetComponentsInChildren<Collider>(true)) if (collider != null) Object.DestroyImmediate(collider);
BoneShipFittings.StripEffects(copy);
copy.transform.localPosition = Vector3.zero;
copy.transform.localRotation = Quaternion.identity;
copy.transform.localScale = Vector3.one;
s_template = copy;
return s_template;
}
private static void StripBehaviours(GameObject root)
{
for (int pass = 0; pass < 12; pass++)
{
bool any = false;
bool removed = false;
foreach (MonoBehaviour behaviour in root.GetComponentsInChildren<MonoBehaviour>(true))
{
if (behaviour == null) continue;
any = true;
if (RequiredByAnother(behaviour)) continue;
Object.DestroyImmediate(behaviour);
removed = true;
}
if (!any) return;
if (!removed) break;
}
int left = 0;
foreach (MonoBehaviour behaviour in root.GetComponentsInChildren<MonoBehaviour>(true)) if (behaviour != null) left++;
if (left > 0) Jotunn.Logger.LogWarning($"[BoneShip] {left} component(s) of the rower model could not be removed.");
}
private static bool RequiredByAnother(MonoBehaviour behaviour)
{
System.Type type = behaviour.GetType();
foreach (Component other in behaviour.GetComponents<Component>())
{
if (other == null || other == behaviour) continue;
foreach (object attribute in other.GetType().GetCustomAttributes(typeof(RequireComponent), true))
{
RequireComponent need = (RequireComponent)attribute;
if (Needs(need.m_Type0, type) || Needs(need.m_Type1, type) || Needs(need.m_Type2, type)) return true;
}
}
return false;
}
private static bool Needs(System.Type required, System.Type type)
{
return required != null && required.IsAssignableFrom(type);
}
/// <summary>The ship's own rotten wood, so the oars and benches match: the first Piece-shader material on it.</summary>
private Material FindWood()
{
foreach (Renderer renderer in GetComponentsInChildren<Renderer>(true))
{
if (renderer == null || renderer is ParticleSystemRenderer || renderer is LineRenderer) continue;
foreach (Material material in renderer.sharedMaterials)
{
if (material != null && material.shader != null && material.shader.name == "Custom/Piece") return material;
}
}
return null;
}
private static GameObject MakeBox(string name, Transform parent, Material material, Vector3 size)
{
if (s_cube == null)
{
GameObject primitive = GameObject.CreatePrimitive(PrimitiveType.Cube);
s_cube = primitive.GetComponent<MeshFilter>().sharedMesh;
Object.Destroy(primitive);
}
GameObject box = new GameObject(name);
box.transform.SetParent(parent, false);
box.transform.localScale = size;
box.AddComponent<MeshFilter>().sharedMesh = s_cube;
MeshRenderer renderer = box.AddComponent<MeshRenderer>();
if (material != null) renderer.sharedMaterial = material;
return box;
}
}
}

View file

@ -0,0 +1,178 @@
using System.Collections.Generic;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// The bone ships' sails: black, and torn.
///
/// Every vanilla sail is a Custom/Vegetation material - an alpha-cutout shader (it has a _Cutoff of
/// 0.5) - so a hole is simply a texel whose alpha is under that. Nothing is imported: the texture is
/// drawn here in code, one per source material (sail_white on the Karve, sail and sail_brown on the
/// Longship, ashlandshipsail_mat on the Ashlands ship), and goes onto a COPY of the material so the
/// vanilla ships keep theirs.
///
/// The holes come from value noise, not a drawing, because the sail's UV layout was not read. Two
/// scales: broad tears, and small shreds, with the top and bottom edges frayed. Whether the shader
/// actually clips on that alpha is the one thing only the game can confirm.
/// </summary>
public static class BoneShipSail
{
private const int Size = 256;
// The big tears: a share of the sail, roughly. Higher threshold = fewer, smaller holes.
private const float TearThreshold = 0.62f;
private const float ShredThreshold = 0.70f;
public static void Apply(GameObject prefab, string shipName)
{
Dictionary<Material, Material> copies = new Dictionary<Material, Material>();
int seed = shipName.GetHashCode();
foreach (Renderer renderer in prefab.GetComponentsInChildren<Renderer>(true))
{
if (renderer == null || renderer is ParticleSystemRenderer || renderer is LineRenderer) continue;
Material[] shared = renderer.sharedMaterials;
bool changed = false;
for (int i = 0; i < shared.Length; i++)
{
Material source = shared[i];
if (!IsSail(source)) continue;
Material copy;
if (!copies.TryGetValue(source, out copy))
{
copy = new Material(source) { name = source.name + "_bone" };
copy.SetTexture("_MainTex", Draw(seed + source.name.GetHashCode()));
copy.SetColor("_Color", Color.white);
copies[source] = copy;
}
shared[i] = copy;
changed = true;
}
if (changed) renderer.sharedMaterials = shared;
}
if (copies.Count == 0)
{
Jotunn.Logger.LogWarning($"[BoneShip] {shipName}: no sail material found, the sail is left as it is.");
}
}
private static bool IsSail(Material material)
{
if (material == null || material.shader == null) return false;
if (!material.HasProperty("_MainTex")) return false;
string name = material.name.ToLowerInvariant();
return name.Contains("sail");
}
// ---------------------------------------------------------------- the texture
private static Texture2D Draw(int seed)
{
Texture2D texture = new Texture2D(Size, Size, TextureFormat.RGBA32, true)
{
name = "boneship_sail",
wrapMode = TextureWrapMode.Clamp,
filterMode = FilterMode.Bilinear,
};
Color32[] pixels = new Color32[Size * Size];
for (int y = 0; y < Size; y++)
{
float v = (y + 0.5f) / Size;
for (int x = 0; x < Size; x++)
{
float u = (x + 0.5f) / Size;
pixels[y * Size + x] = Pixel(u, v, seed);
}
}
texture.SetPixels32(pixels);
texture.Apply(true, false);
return texture;
}
private static Color32 Pixel(float u, float v, int seed)
{
// Cloth: near black, mottled, with a faint warp of vertical streaks.
float mottle = Fbm(u * 7f, v * 7f, seed + 3);
float streak = 0.5f + 0.5f * Mathf.Sin(u * 90f + Fbm(u * 3f, v * 3f, seed + 5) * 6f);
float shade = Mathf.Lerp(0.04f, 0.17f, mottle) * Mathf.Lerp(0.85f, 1.05f, streak);
Color cloth = new Color(shade * 1.00f, shade * 0.97f, shade * 0.93f, 1f);
// Holes. Each term is an alpha with 0.5 at its own edge; the lowest wins.
float tear = Fbm(u * 4f, v * 4f, seed + 11);
float shred = Fbm(u * 13f, v * 13f, seed + 29);
float alpha = 1f;
alpha = Mathf.Min(alpha, 0.5f + (TearThreshold - tear) * 14f);
alpha = Mathf.Min(alpha, 0.5f + (ShredThreshold - shred) * 14f);
// Fringe: the top and bottom edges are eaten away in ragged teeth, the sides a little.
float edge = Mathf.Min(v, 1f - v);
float teeth = ValueNoise(u * 22f, v * 3f, seed + 41);
alpha = Mathf.Min(alpha, 0.5f + (teeth * 0.16f - edge) * 28f);
float side = Mathf.Min(u, 1f - u);
float sideTeeth = ValueNoise(u * 3f, v * 20f, seed + 53);
alpha = Mathf.Min(alpha, 0.5f + (sideTeeth * 0.07f - side) * 28f);
// Scorched round the holes: darker where the tear is nearly through.
float burn = Mathf.Clamp01((tear - (TearThreshold - 0.10f)) * 8f);
cloth = Color.Lerp(cloth, new Color(0.015f, 0.015f, 0.015f, 1f), burn * 0.8f);
cloth.a = Mathf.Clamp01(alpha);
return cloth;
}
// ---------------------------------------------------------------- noise
private static float Hash(int x, int y, int seed)
{
unchecked
{
int h = x * 374761393 + y * 668265263 + seed * 1442695041;
h = (h ^ (h >> 13)) * 1274126177;
return ((h ^ (h >> 16)) & 0xffff) / 65535f;
}
}
private static float ValueNoise(float x, float y, int seed)
{
int xi = Mathf.FloorToInt(x);
int yi = Mathf.FloorToInt(y);
float tx = x - xi;
float ty = y - yi;
tx = tx * tx * (3f - 2f * tx);
ty = ty * ty * (3f - 2f * ty);
float a = Hash(xi, yi, seed);
float b = Hash(xi + 1, yi, seed);
float c = Hash(xi, yi + 1, seed);
float d = Hash(xi + 1, yi + 1, seed);
return Mathf.Lerp(Mathf.Lerp(a, b, tx), Mathf.Lerp(c, d, tx), ty);
}
private static float Fbm(float x, float y, int seed)
{
float value = 0f;
float amplitude = 0.5f;
for (int octave = 0; octave < 4; octave++)
{
value += amplitude * ValueNoise(x, y, seed + octave * 17);
x *= 2.03f;
y *= 2.03f;
amplitude *= 0.5f;
}
return value / 0.9375f; // 0.5 + 0.25 + 0.125 + 0.0625, so the sum stays in 0..1
}
}
}

View file

@ -0,0 +1,392 @@
using System.Collections.Generic;
using HarmonyLib;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// Holds a creature to one spot of a ship's deck, however the ship moves.
///
/// The Bone Ship's archers (Skeleton_BoneShip.txt, section 6) are the Bound Sentry - a tamed archer
/// whose speeds are all zero - and zero speed alone does not keep a Character on a moving deck: it
/// is carried only as far as the game's own ground-body inheritance happens to carry it. So each
/// physics step the mount sets its position to the ship's local point and its velocity to the ship's
/// velocity at that point. Rotation is left to the archer: it turns to face what it shoots.
///
/// Runs on the OWNER of the archer only; everyone else sees the result through the creature's own
/// ZSyncTransform.
///
/// TWO WAYS TO KNOW THE SHIP. The F7 experiment sets Ship and LocalPoint directly and the mount does not
/// survive a reload (an archer that wakes without its ship is removed). The real archers are a prefab
/// of their own (BoneShipArcher) that carries this component from the start, and know their ship by its
/// id in their own ZDO: after a reload the ship is looked up again as soon as it is loaded. If the ship's
/// ZDO is gone altogether for a few seconds, the ship has sunk, and the archer goes with it - "it dies
/// with the ship", with nothing to remember.
/// </summary>
public class ShipMount : MonoBehaviour
{
/// <summary>ZDO keys on a ship's ARCHER: the ship it guards, and where it stands on it.</summary>
public const string KeyArcherShip = "RoV_bshArcherShip";
public const string KeyArcherPoint = "RoV_bshArcherPoint";
public const string KeyArcherBust = "RoV_bshArcherBust";
public const string KeyArcherPost = "RoV_bshArcherPost";
/// <summary>Seconds without the ship's ZDO before the archer decides the ship is gone.</summary>
private const float GoneAfter = 6f;
/// <summary>The ship this creature is bolted to.</summary>
public Ship Ship;
/// <summary>Where on that ship, in the ship's own space.</summary>
public Vector3 LocalPoint;
private ZNetView m_nview;
private Rigidbody m_body;
private Rigidbody m_shipBody;
private ZDOID m_shipId = ZDOID.None;
private bool m_byId;
private float m_missing;
private float m_nextResolve;
private void Awake()
{
m_nview = GetComponent<ZNetView>();
m_body = GetComponent<Rigidbody>();
// No interpolation on the archer's own body: the transform is set by hand every frame in
// LateUpdate, and a body that interpolates between physics steps would fight that and put back
// the very stutter this exists to remove.
if (m_body != null) m_body.interpolation = RigidbodyInterpolation.None;
}
private void Start()
{
if (Ship != null) { IgnoreShipColliders(); return; }
// The real archers: the ship is a number in their own ZDO. Read on EVERY client, not just the
// owner, because every client pins the visual to the ship (LateUpdate).
if (m_nview == null || !m_nview.IsValid()) return;
m_shipId = m_nview.GetZDO().GetZDOID(KeyArcherShip);
if (m_shipId == ZDOID.None) return;
LocalPoint = m_nview.GetZDO().GetVec3(KeyArcherPoint, Vector3.zero);
m_byId = true;
}
/// <summary>
/// Every frame, on every client: the archer's transform is the ship's local point, taken from the
/// ship's own (interpolated) transform at render time.
///
/// The physics pin below only moves the archer once per physics step, from where the ship was at the
/// start of that step. The ship is drawn smoothly between steps and the archer was not, so at speed
/// it jumped in 50 Hz hops against a hull that glides - "in jerks", and, trailing a step behind,
/// looking not quite attached. Setting the transform here, after everything else has moved it, makes
/// it exactly as smooth as the hull it stands on. For a remote client this also overrides the
/// position the network would give it, which is itself a few steps old.
/// </summary>
private void LateUpdate()
{
if (Ship == null)
{
if (m_byId && Time.time >= m_nextResolve)
{
m_nextResolve = Time.time + 0.5f;
TryResolveShip();
}
return;
}
transform.position = Ship.transform.TransformPoint(LocalPoint);
}
private bool TryResolveShip()
{
GameObject found = ZNetScene.instance != null ? ZNetScene.instance.FindInstance(m_shipId) : null;
Ship ship = found != null ? found.GetComponent<Ship>() : null;
if (ship == null) return false;
Ship = ship;
m_missing = 0f;
IgnoreShipColliders();
return true;
}
/// <summary>
/// Pinned inside the ship's own volume, so it must not fight the ship's colliders: with them live the
/// physics keeps trying to push it out and the mount keeps putting it back. Ignoring them costs
/// nothing - it is invulnerable, and nobody needs to bump into it.
/// </summary>
private void IgnoreShipColliders()
{
Collider[] mine = GetComponentsInChildren<Collider>(true);
Collider[] theirs = Ship.GetComponentsInChildren<Collider>(true);
foreach (Collider a in mine)
{
if (a == null) continue;
foreach (Collider b in theirs)
{
if (b != null) Physics.IgnoreCollision(a, b, true);
}
}
}
private void FixedUpdate()
{
if (m_nview == null || !m_nview.IsValid() || !m_nview.IsOwner()) return;
if (Ship == null)
{
if (m_byId) FindShip();
else if (ZNetScene.instance != null) ZNetScene.instance.Destroy(gameObject); // the experiment's way
return;
}
if (m_body == null) return;
if (m_shipBody == null) m_shipBody = Ship.GetComponent<Rigidbody>();
Vector3 target = Ship.transform.TransformPoint(LocalPoint);
m_body.position = target;
m_body.velocity = m_shipBody != null ? m_shipBody.GetPointVelocity(target) : Vector3.zero;
}
/// <summary>
/// Looks the ship up by id. Loaded: bolted on. Not loaded but still in the world's books: wait, it is
/// about to be (they load together). Not in the books at all, for long enough: it has sunk.
/// </summary>
private void FindShip()
{
if (TryResolveShip()) return;
if (ZDOMan.instance != null && ZDOMan.instance.GetZDO(m_shipId) != null)
{
m_missing = 0f;
return;
}
m_missing += Time.fixedDeltaTime;
if (m_missing >= GoneAfter && ZNetScene.instance != null) ZNetScene.instance.Destroy(gameObject);
}
}
/// <summary>
/// Makes an archer a BUST: the leg bones are collapsed to nothing every frame, so only the pelvis, the
/// chest and the arms show - a figurehead that shoots.
///
/// The model cannot be cut, so the legs are scaled to zero where they join the hips: everything skinned
/// to them folds into that point. A leg bone's children inherit the zero, so feet and shins go with it.
/// It is done in LateUpdate, after the animator has written its pose, so nothing animated can put them
/// back. The BONE NAMES are not verified - they are searched for ("upleg", "thigh", "upperleg") on the
/// first frame and what was found is logged. If it finds none it logs the whole skeleton, which is the
/// list the next attempt is written from.
/// </summary>
public class ShipBust : MonoBehaviour
{
private static readonly string[] LegBones = { "upleg", "thigh", "upperleg", "leg_upper" };
private readonly List<Transform> m_legs = new List<Transform>();
/// <summary>Set by the F7 experiment; the real archers say so in their ZDO instead.</summary>
public bool Force;
private void Start()
{
// On the prefab of the real archers this component is always there, and only the ones placed as a
// bust (the ZDO says so) are cut off at the waist; the deck ones keep their legs.
ZNetView nview = GetComponent<ZNetView>();
bool bust = Force || (nview != null && nview.IsValid() && nview.GetZDO().GetBool(ShipMount.KeyArcherBust, false));
if (!bust)
{
enabled = false;
return;
}
foreach (Transform t in GetComponentsInChildren<Transform>(true))
{
string n = t.name.ToLowerInvariant();
foreach (string key in LegBones)
{
if (!n.Contains(key)) continue;
// Only the topmost of a chain: a bone whose parent is already a leg is covered by it.
if (!m_legs.Contains(t.parent)) m_legs.Add(t);
break;
}
}
if (m_legs.Count > 0)
{
List<string> names = new List<string>();
foreach (Transform t in m_legs) names.Add(t.name);
Jotunn.Logger.LogInfo("[ShipBust] collapsing " + m_legs.Count + " leg bone(s): " + string.Join(", ", names.ToArray()));
return;
}
// Nothing matched: say what is there so the names can be read instead of guessed.
List<string> all = new List<string>();
foreach (Transform t in GetComponentsInChildren<Transform>(true)) all.Add(t.name);
Jotunn.Logger.LogWarning("[ShipBust] no leg bone matched. Skeleton: " + string.Join(", ", all.ToArray()));
}
private void LateUpdate()
{
foreach (Transform leg in m_legs)
{
if (leg != null) leg.localScale = Vector3.zero;
}
}
}
/// <summary>
/// A ship's archer cannot be killed - it goes down with the ship, which is the stake. Skipping
/// Character.Damage is enough: the Bound Sentry's own regeneration patch only listens to it too.
/// </summary>
[HarmonyPatch(typeof(Character), "Damage")]
public static class ShipMountInvulnerablePatch
{
public static bool Prefix(Character __instance)
{
return __instance.GetComponent<ShipMount>() == null;
}
}
/// <summary>
/// The deck-finding and post table the bone ships use to place their archers.
///
/// WHERE: a local (x, z) per ship, and the height is NOT guessed - a ray is dropped from above that
/// spot and the deck is wherever it first hits the ship's own solid collider. The mast and the sail's
/// cloth collider are skipped. The point it settled on is reported, so a bad spot is fixed by editing
/// the table below, not by reading code.
/// </summary>
public static class ShipMountTest
{
private const float ShipRange = 40f;
private const float RayStartHeight = 8f;
private const float RayLength = 20f;
/// <summary>
/// One archer's place: where on the deck (local x, z), and whether it is a BUST - only the chest and
/// up shows, the legs are collapsed, and it stands on the stem as a figurehead that shoots.
/// </summary>
private struct Post
{
public Vector2 At;
public bool Bust;
public Post(float x, float z, bool bust) { At = new Vector2(x, z); Bust = bust; }
}
/// <summary>
/// The Karve's bow is at about local z = +4.8 (its WaterTrigger sits there, and the hull mesh is
/// ~10 m long); the post is a little back from the very tip so the ray finds the hull under it.
/// The large ships keep their deck posts until they get a bust of their own.
/// </summary>
private static readonly Dictionary<string, Post[]> Posts = new Dictionary<string, Post[]>
{
{ "Karve", new[] { new Post(0f, 4.3f, true) } },
{ "BoneKarve", new[] { new Post(0f, 4.3f, true) } },
{ "VikingShip", new[] { new Post(0f, 3.2f, false), new Post(0f, -5.0f, false) } },
{ "BoneLongship", new[] { new Post(0f, 3.2f, false), new Post(0f, -5.0f, false) } },
{ "VikingShip_Ashlands", new[] { new Post(0f, 3.2f, false), new Post(0f, -5.0f, false) } },
{ "BoneAshlands", new[] { new Post(0f, 3.2f, false), new Post(0f, -5.0f, false) } },
};
private static readonly Post[] DefaultPosts = { new Post(0f, 0f, false) };
/// <summary>
/// How far above the hull's surface a bust stands, in metres: the pelvis is left as a stub where the
/// legs were, and this keeps that stub inside the stem instead of above it. To be tuned by eye.
/// </summary>
private const float BustLift = 0.0f;
/// <summary>The deck under a local (x, z): the highest solid surface of THIS ship, not the mast or the sail.</summary>
private static bool FindDeck(Ship ship, Vector2 post, bool bust, out Vector3 local, out string hitName)
{
local = Vector3.zero;
hitName = "";
// A deck is flat. A bow is not: near the stem the hull's surface climbs steeply, and a flat-only
// filter (normal.y >= 0.5) found nothing there at all. A bust takes ANY surface of the ship under
// the point, and if the point is past the end of the hull it walks back toward the middle until
// something is there - the step it settled on shows in the reported local z.
float minUp = bust ? -1f : 0.5f;
float maxBack = bust ? 2.4f : 0f;
const float Step = 0.3f;
for (float back = 0f; back <= maxBack + 0.001f; back += Step)
{
Vector3 origin = ship.transform.TransformPoint(new Vector3(post.x, RayStartHeight, post.y - back));
Vector3 down = -ship.transform.up;
RaycastHit best = default(RaycastHit);
bool found = false;
float bestDistance = float.MaxValue;
foreach (RaycastHit hit in Physics.RaycastAll(origin, down, RayLength))
{
if (hit.collider == null || hit.collider.isTrigger) continue;
if (!hit.collider.transform.IsChildOf(ship.transform)) continue;
if (Vector3.Dot(hit.normal, ship.transform.up) < minUp) continue;
string n = hit.collider.name.ToLowerInvariant();
if (n.Contains("mast") || n.Contains("cloth")) continue;
if (hit.distance >= bestDistance) continue;
best = hit;
bestDistance = hit.distance;
found = true;
}
if (!found) continue;
local = ship.transform.InverseTransformPoint(best.point);
hitName = best.collider.name + (back > 0f ? " (stepped back " + back.ToString("F1") + " m)" : "");
return true;
}
return false;
}
private static Ship NearestShip()
{
Player player = Player.m_localPlayer;
if (player == null) return null;
Ship best = null;
float bestDistance = ShipRange;
foreach (Ship ship in Object.FindObjectsOfType<Ship>())
{
float distance = Vector3.Distance(ship.transform.position, player.transform.position);
if (distance >= bestDistance) continue;
best = ship;
bestDistance = distance;
}
return best;
}
private static List<ShipMount> MountsOn(Ship ship)
{
List<ShipMount> mounts = new List<ShipMount>();
foreach (Character character in Character.GetAllCharacters())
{
if (character == null) continue;
ShipMount mount = character.GetComponent<ShipMount>();
if (mount != null && mount.Ship == ship) mounts.Add(mount);
}
return mounts;
}
/// <summary>"Karve(Clone)" to "Karve".</summary>
private static string Clean(string name)
{
int paren = name.IndexOf('(');
return (paren >= 0 ? name.Substring(0, paren) : name).Trim();
}
private static void Report(string line)
{
Jotunn.Logger.LogInfo(line);
if (Console.instance != null) Console.instance.Print(line);
}
}
}

View file

@ -39,6 +39,26 @@ namespace RacesOfValheim
{ "FaderDrop", 8 } // Fader - Fader relic { "FaderDrop", 8 } // Fader - Fader relic
}; };
/// <summary>
/// The boss's name as the game's own localization token, for text shown to players:
/// Valheim translates it wherever it is localized, so "The Elder" arrives in every language.
/// GetBossNameForState stays English, for logs and anything not localized.
/// </summary>
public static string GetBossTokenForState(int state)
{
switch (state)
{
case 2: return "$enemy_eikthyr";
case 3: return "$enemy_gdking";
case 4: return "$enemy_bonemass";
case 5: return "$enemy_dragon";
case 6: return "$enemy_goblinking";
case 7: return "$enemy_seekerqueen";
case 8: return "$enemy_fader";
default: return GetBossNameForState(state);
}
}
public static string GetBossNameForState(int state) public static string GetBossNameForState(int state)
{ {
switch (state) switch (state)
@ -95,6 +115,36 @@ namespace RacesOfValheim
} }
} }
/// <summary>
/// Whether this character carries a claimed personal tier at all. Distinct from
/// "PersonalState == MinState": the getter answers MinState for a character who has never
/// claimed anything AND for one who has been reset, and the Reset Progression button needs
/// to tell the player which of the two just happened.
/// </summary>
public static bool HasPersonalState
{
get
{
Player player = Player.m_localPlayer;
if (player == null || player.m_customData == null) return false;
return player.m_customData.ContainsKey(PersonalStateKey);
}
}
/// <summary>
/// Gives back every tier claimed with a boss relic. The key is removed rather than written
/// back as MinState so the character reads as one that never claimed anything - which is
/// what a reset means, and what HasPersonalState above then reports.
///
/// The relics themselves do not come back: RaceMenuWardBehavior.UseItem consumed them.
/// </summary>
public static void ClearPersonalState()
{
Player player = Player.m_localPlayer;
if (player == null || player.m_customData == null) return;
player.m_customData.Remove(PersonalStateKey);
}
/// <summary> /// <summary>
/// Returns the current progression state of the world based on defeated bosses. /// Returns the current progression state of the world based on defeated bosses.
/// 1 = No bosses defeated /// 1 = No bosses defeated

View file

@ -42,13 +42,13 @@ namespace RacesOfValheim
// The smith inherits the names the single servant had, so nothing already built is orphaned. // The smith inherits the names the single servant had, so nothing already built is orphaned.
public const string SmithName = "BoneServant"; public const string SmithName = "BoneServant";
public const string SmithTableName = "ServantTable"; public const string SmithTableName = "ServantTable";
public const string SmithDisplay = "Bone Smith"; public const string SmithDisplay = "$rov_creature_bonesmith_name";
public const string SmithTableDisplay = "Smith's Table"; public const string SmithTableDisplay = "$rov_piece_smithtable_name";
public const string CookName = "BoneCook"; public const string CookName = "BoneCook";
public const string CookTableName = "CookTable"; public const string CookTableName = "CookTable";
public const string CookDisplay = "Bone Cook"; public const string CookDisplay = "$rov_creature_bonecook_name";
public const string CookTableDisplay = "Cook's Table"; public const string CookTableDisplay = "$rov_piece_cooktable_name";
/// <summary>Vanilla's guaranteed-melee skeleton: the plain one rolls its own weapon, and the /// <summary>Vanilla's guaranteed-melee skeleton: the plain one rolls its own weapon, and the
/// point here is to have none at all.</summary> /// point here is to have none at all.</summary>
@ -90,11 +90,11 @@ namespace RacesOfValheim
if (RegisterServant(SmithName, SmithDisplay, ButlerFamily.Forge)) if (RegisterServant(SmithName, SmithDisplay, ButlerFamily.Forge))
{ {
RegisterTable(SmithTableName, SmithTableDisplay, SmithName, ButlerFamily.Forge, RegisterTable(SmithTableName, SmithTableDisplay, SmithName, ButlerFamily.Forge,
"A slab of bone and slate, dusted with ore. Something patient waits by the fires.", "$rov_piece_smithtable_desc",
"Coal"); "Coal");
PieceDensityLimit.Register(SmithTableName, TableSpacing, 1, PieceDensityLimit.Register(SmithTableName, TableSpacing, 1,
"Another smith's table stands within forty paces. One smith to a yard."); "rov_msg_build_limit_smithtable");
// Two races, and it is the wider of the two locks: the Skeleton raises the dead to work // Two races, and it is the wider of the two locks: the Skeleton raises the dead to work
// for it, and Skadi's hold is a forge under ice. // for it, and Skadi's hold is a forge under ice.
@ -105,7 +105,7 @@ namespace RacesOfValheim
if (player != null) if (player != null)
{ {
player.Message(MessageHud.MessageType.Center, player.Message(MessageHud.MessageType.Center,
"The bones do not answer to your blood."); ModText.Get("rov_msg_butler_bones_do_not_answer_blood"));
} }
return false; return false;
}); });
@ -114,11 +114,11 @@ namespace RacesOfValheim
if (RegisterServant(CookName, CookDisplay, ButlerFamily.Kitchen)) if (RegisterServant(CookName, CookDisplay, ButlerFamily.Kitchen))
{ {
RegisterTable(CookTableName, CookTableDisplay, CookName, ButlerFamily.Kitchen, RegisterTable(CookTableName, CookTableDisplay, CookName, ButlerFamily.Kitchen,
"A slab of bone and slate, worn smooth. Something patient waits by the hearth.", "$rov_piece_cooktable_desc",
"CookedMeat"); "CookedMeat");
PieceDensityLimit.Register(CookTableName, TableSpacing, 1, PieceDensityLimit.Register(CookTableName, TableSpacing, 1,
"Another cook's table stands within forty paces. One cook to a yard."); "rov_msg_build_limit_cooktable");
// Skadi alone. A hearth kept by something dead is hers, not the Skeleton's. // Skadi alone. A hearth kept by something dead is hers, not the Skeleton's.
PieceDensityLimit.RegisterGate(CookTableName, (player, position) => PieceDensityLimit.RegisterGate(CookTableName, (player, position) =>
@ -128,7 +128,7 @@ namespace RacesOfValheim
if (player != null) if (player != null)
{ {
player.Message(MessageHud.MessageType.Center, player.Message(MessageHud.MessageType.Center,
"Only Skadi's hearth is kept by the dead."); ModText.Get("rov_msg_butler_only_skadi_s_hearth_kept"));
} }
return false; return false;
}); });
@ -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>();
@ -233,8 +234,12 @@ namespace RacesOfValheim
piece.m_resources = new Piece.Requirement[0]; piece.m_resources = new Piece.Requirement[0];
piece.m_name = displayName; piece.m_name = displayName;
piece.m_canBeRemoved = true; piece.m_canBeRemoved = true;
piece.m_groundPiece = true; // Neither flag, like the Bone Pile. m_groundPiece made Player.UpdatePlacementGhost switch
piece.m_groundOnly = true; // the ghost off outright wherever the aim was not terrain - floors, rocks, a troll cave's
// mesh floor - so players saw no ghost at all and could not tell why. A station belongs
// in a house or a cave as much as outside.
piece.m_groundPiece = false;
piece.m_groundOnly = false;
piece.m_icon = icon; piece.m_icon = icon;
Piece template = PrefabManager.Cache.GetPrefab<Piece>("piece_workbench"); Piece template = PrefabManager.Cache.GetPrefab<Piece>("piece_workbench");
@ -251,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

@ -103,6 +103,31 @@ namespace RacesOfValheim
/// with every instance the table raises.</summary> /// with every instance the table raises.</summary>
public ButlerFamily m_family = ButlerFamily.Forge; public ButlerFamily m_family = ButlerFamily.Forge;
/// <summary>
/// Whether this one stands and fights instead of walking home when trouble comes. Off for the
/// Bone Servants, which are pacifists by decision; on for the Sverm's Seeker Workers, which
/// keep the forge AND defend the nest. See <see cref="HandsToVanilla"/>.
/// </summary>
public bool m_fightsBack = false;
/// <summary>
/// How close to the anchor counts as home, and how far past the configured radius it works.
/// 2.5 and 0 for a table. A Sverm nest is metres of collider that grows with its stage, so
/// SvermWorkerBehaviour sets both to the nest's measured edge - otherwise an idle worker would
/// spend its life walking into the trunk, and the work circle would be mostly nest.
/// </summary>
public float m_homeDistance = 2.5f;
public float m_radiusBonus = 0f;
/// <summary>For a servant that fights back: how close an enemy has to be to stop the work, how
/// often that is asked, and how long the fight holds after the last sign of one.</summary>
private const float FightRange = 12f;
private const float FightScanInterval = 1f;
private const float FightLinger = 5f;
private float m_nextFightScan;
private float m_fightUntil;
private ZNetView m_nview; private ZNetView m_nview;
private Character m_character; private Character m_character;
private MonsterAI m_ai; private MonsterAI m_ai;
@ -207,13 +232,62 @@ namespace RacesOfValheim
} }
/// <summary>Hit by something: stop working and walk home. It never fights back - there is /// <summary>Hit by something: stop working and walk home. It never fights back - there is
/// nothing in this class that could.</summary> /// nothing in this class that could. A servant that fights back ignores this: vanilla already
/// holds the attacker as its target (MonsterAI.OnDamaged calls SetTarget, read off the IL), and
/// <see cref="HandsToVanilla"/> gives it the tick on the next frame.</summary>
public void NoteDamage() public void NoteDamage()
{ {
if (m_fightsBack) return;
m_fleeUntil = Time.time + FleeSeconds; m_fleeUntil = Time.time + FleeSeconds;
m_job = null; m_job = null;
} }
/// <summary>
/// True while vanilla's MonsterAI should have the tick instead of the work - only ever for a
/// servant that fights back, and only on the client that runs it.
///
/// VANILLA DOES THE FIGHTING, this only decides when. Two things start a fight: a target the
/// MonsterAI already holds - which covers being hit, see NoteDamage - and an enemy inside
/// FightRange, found with BaseAI.FindClosestEnemy. That one is a static sweep of distance and
/// IsEnemy with no line of sight (IL), which is why the range is short. Either holds the fight
/// for FightLinger seconds, so the worker does not flicker between swinging and walking to the
/// chest on alternate ticks.
///
/// The job is dropped, not the payload: whatever it was carrying stays in the ZDO, and the
/// first plan after the fight carries it on to where it was going.
/// </summary>
public bool HandsToVanilla()
{
if (!m_fightsBack || m_ai == null || m_character == null || m_character.IsDead()) return false;
if (m_nview == null || !m_nview.IsValid() || !m_nview.IsOwner()) return false;
Character target = m_ai.GetTargetCreature();
if (target != null && !target.IsDead())
{
m_fightUntil = Time.time + FightLinger;
}
else if (Time.time >= m_nextFightScan)
{
m_nextFightScan = Time.time + FightScanInterval;
// 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;
}
}
if (Time.time >= m_fightUntil) return false;
m_job = null;
m_nextPlan = 0f; // the fight moved it; plan afresh the moment it hands back
SetStatus("Fighting.");
return true;
}
// ================================================================ the tick // ================================================================ the tick
/// <summary>Everything. Returns what MonsterAI.UpdateAI would have returned.</summary> /// <summary>Everything. Returns what MonsterAI.UpdateAI would have returned.</summary>
@ -289,14 +363,12 @@ 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
// The forge has no clock: a smelter holds its ore indefinitely and puts its own output on // it timed out and was planned again on every tick, frozen with the goods in hand.
// the floor, so PlanRescue would ask a question whose answer is always no. The smith is a Job job;
// four-state machine and the cook is a five-state one, and that is the whole of the if (m_payload.Count > 0) job = PlanDelivery(anchor.Value);
// simplification the split bought. else job = PlanWork();
Job job = m_family == ButlerFamily.Kitchen ? PlanRescue() : null;
job = job ?? PlanCollect() ?? PlanLoad() ?? PlanFuel();
if (job != null && (m_job == null || m_job.Kind != job.Kind || m_job.Target != job.Target)) if (job != null && (m_job == null || m_job.Kind != job.Kind || m_job.Target != job.Target))
{ {
@ -305,6 +377,22 @@ namespace RacesOfValheim
m_job = job; m_job = job;
} }
private Job PlanWork()
{
// The forge has no clock: a smelter holds its ore indefinitely and puts its own output on
// the floor, so PlanRescue would ask a question whose answer is always no. The smith is a
// four-state machine and the cook is a five-state one, and that is the whole of the
// simplification the split bought.
// REFUEL BEFORE LOAD, and that order is the whole of the blast furnace fix. FreeSlots goes
// back above zero the instant a furnace eats one ore, so while there is scrap left in any
// chest PlanLoad always has an answer and PlanFuel, sitting behind it, never got a turn -
// the furnace was topped up forever and burned down to nothing. Fuel cannot starve loading
// in return, because FuelWanted is zero for a station with no work: an empty furnace asks
// for no coal, gets filled, and only then becomes worth stoking.
Job job = m_family == ButlerFamily.Kitchen ? PlanRescue() : null;
return job ?? PlanCollect() ?? PlanFuel() ?? PlanLoad();
}
/// <summary> /// <summary>
/// Everything within the radius, once every planning tick. Piece.s_allPieces is the cheap way in /// Everything within the radius, once every planning tick. Piece.s_allPieces is the cheap way in
/// - it is the list the game already keeps of every built piece - so there is no OverlapSphere /// - it is the list the game already keeps of every built piece - so there is no OverlapSphere
@ -321,7 +409,7 @@ namespace RacesOfValheim
List<Piece> pieces = AllPiecesField != null ? AllPiecesField.GetValue(null) as List<Piece> : null; List<Piece> pieces = AllPiecesField != null ? AllPiecesField.GetValue(null) as List<Piece> : null;
if (pieces == null) return; if (pieces == null) return;
float radius = ButlerConfig.WorkRadius.Value; float radius = ButlerConfig.WorkRadius.Value + m_radiusBonus;
float radiusSq = radius * radius; float radiusSq = radius * radius;
for (int i = 0; i < pieces.Count; i++) for (int i = 0; i < pieces.Count; i++)
@ -449,7 +537,7 @@ namespace RacesOfValheim
} }
/// <summary> /// <summary>
/// 3. LOAD. Urgency, then distance - and the urgency of a station with nothing wrong with it is /// 4. LOAD. Urgency, then distance - and the urgency of a station with nothing wrong with it is
/// how long it has been waiting. A metre of walking is worth four seconds of a station standing /// how long it has been waiting. A metre of walking is worth four seconds of a station standing
/// idle, so the far furnace wins eventually instead of never. /// idle, so the far furnace wins eventually instead of never.
/// </summary> /// </summary>
@ -495,9 +583,20 @@ namespace RacesOfValheim
}; };
} }
/// <summary>4. REFUEL. Only stations that actually have something to work on.</summary> /// <summary>
/// 3. REFUEL. Only stations that actually have something to work on.
///
/// Scored by the walk, the same way PlanLoad is, and for a reason that only appeared once this
/// moved up the list: taking the first station in scan order was harmless while refuelling was
/// the job of last resort, but ahead of loading it lets one furnace at the edge of the circle
/// hold the servant while a cold one two metres away waits.
/// </summary>
private Job PlanFuel() private Job PlanFuel()
{ {
Container bestChest = null;
string bestFuel = null;
float bestScore = float.MaxValue;
foreach (ButlerStation station in m_stations) foreach (ButlerStation station in m_stations)
{ {
if (!station.Alive || IsPenalised(station.Id)) continue; if (!station.Alive || IsPenalised(station.Id)) continue;
@ -512,18 +611,26 @@ namespace RacesOfValheim
Container chest = FindChestWith(fuel); Container chest = FindChestWith(fuel);
if (chest == null) continue; if (chest == null) continue;
float score = Vector3.Distance(transform.position, chest.transform.position) +
Vector3.Distance(chest.transform.position, station.Position);
if (score >= bestScore) continue;
bestScore = score;
bestChest = chest;
bestFuel = fuel;
}
if (bestChest == null) return null;
return new Job return new Job
{ {
Kind = "fuel", Kind = "fuel",
Target = ZdoOf(chest), Target = ZdoOf(bestChest),
Point = chest.transform.position, Point = bestChest.transform.position,
Label = "Fetching " + fuel, Label = "Fetching " + bestFuel,
}; };
} }
return null;
}
/// <summary>Where the load in hand is going: on to its station, or back into a chest.</summary> /// <summary>Where the load in hand is going: on to its station, or back into a chest.</summary>
private Job PlanDelivery(Vector3 anchor) private Job PlanDelivery(Vector3 anchor)
{ {
@ -535,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
{ {
@ -563,8 +672,31 @@ namespace RacesOfValheim
}; };
} }
// Every sealed chest is full. Beside the table it goes: a stalled chain is worse than a // Every sealed chest is full - but a chest is not the only place a thing can go. A station
// tidy floor, and nothing may vanish (sec. 7.3). // that BURNS what is in hand is a destination too, and for the smith it is usually the
// right one: the charcoal kiln releases its whole batch in one go (verified in the IL -
// UpdateSmelter only calls SpawnProcessed once the ore queue empties), which is exactly the
// delivery a nearly full chest cannot absorb, and the coal it makes is what the furnace
// beside it is waiting for. Offering the load to a consumer before giving up is what turns
// "nowhere to put 20x Coal" into a full blast furnace.
//
// It comes AFTER the chest and not before, so a product still goes home to the chest that
// paid for it whenever there is room; this is the step before the floor, not instead of
// storing.
ButlerStation consumer = StationWanting();
if (consumer != null)
{
return new Job
{
Kind = "deposit_station",
Target = consumer.Id,
Point = consumer.Position,
Label = "Loading " + Describe(),
};
}
// Nothing will take it. Beside the table it goes: a stalled chain is worse than a tidy
// floor, and nothing may vanish (sec. 7.3).
return new Job return new Job
{ {
Kind = "drop", Kind = "drop",
@ -574,6 +706,29 @@ namespace RacesOfValheim
}; };
} }
/// <summary>The nearest station that will take something out of the payload, as material or as
/// fuel. No FreeSlots check, for the reason spelled out above the KeyTarget branch: fuel does
/// not go into a slot, and AcceptsAnything already asks the right question of both doors.</summary>
private ButlerStation StationWanting()
{
ButlerStation best = null;
float bestDistance = float.MaxValue;
foreach (ButlerStation station in m_stations)
{
if (!station.Alive || IsPenalised(station.Id)) continue;
if (!station.Operable || !AcceptsAnything(station)) continue;
float distance = Vector3.Distance(transform.position, station.Position);
if (distance >= bestDistance) continue;
bestDistance = distance;
best = station;
}
return best;
}
// ================================================================ execution // ================================================================ execution
private void Execute(float dt) private void Execute(float dt)
@ -691,23 +846,35 @@ namespace RacesOfValheim
/// At a station with something finished. Pull first, sweep second - and the sweep is the only /// At a station with something finished. Pull first, sweep second - and the sweep is the only
/// place the servant ever picks anything up off the ground, which is what keeps it from tidying /// place the servant ever picks anything up off the ground, which is what keeps it from tidying
/// away things the player left lying about on purpose. /// away things the player left lying about on purpose.
///
/// THE ORDER IS THE POINT, and it used to be the other way round. Sweeping first meant every
/// visit collected what the LAST visit had thrown on the floor and then threw a fresh one down;
/// since Plan() hands the servant to PlanDelivery the moment it is carrying anything, it walked
/// off to the chest the instant the sweep landed and abandoned the item it had just pulled.
/// While a hearth kept working there was therefore always exactly one cooked meat lying on the
/// ground - the "loses one per batch, whether that is two or five" the testers reported.
///
/// The loop is the other half of it. RPC_RemoveDoneItem empties ONE slot per call, so a hearth
/// with five done slots needs five calls; one per visit turned one batch into five round trips
/// to the chest. It runs against OutputPulls rather than against HasOutput alone because the
/// fermenter's Ready survives its own tap for the length of the animation.
/// </summary> /// </summary>
private bool DoCollect() private bool DoCollect()
{ {
ButlerStation station = StationById(m_job.Target); ButlerStation station = StationById(m_job.Target);
if (station == null || !station.Alive) return false; if (station == null || !station.Alive) return false;
int before = PayloadCount();
SweepDrops(station.Position);
bool swept = PayloadCount() > before;
bool pulled = false; bool pulled = false;
if (station.HasOutput) for (int i = 0; i < station.OutputPulls && station.HasOutput; i++)
{ {
station.PullOutput(transform.position); station.PullOutput(transform.position);
pulled = true; pulled = true;
} }
int before = PayloadCount();
SweepDrops(station.Position);
bool swept = PayloadCount() > before;
if (swept) if (swept)
{ {
// The product belongs to whoever fed the station. If nothing was written there - the // The product belongs to whoever fed the station. If nothing was written there - the
@ -840,7 +1007,7 @@ namespace RacesOfValheim
return; return;
} }
MoveToPoint(dt, anchor.Value, 2.5f, false); MoveToPoint(dt, anchor.Value, m_homeDistance, false);
} }
// ================================================================ the ground // ================================================================ the ground
@ -921,7 +1088,15 @@ namespace RacesOfValheim
while (left > 0) while (left > 0)
{ {
int stack = Mathf.Min(left, max); int stack = Mathf.Min(left, max);
ItemDrop.DropItem(template.m_itemData.Clone(), stack,
// ItemDrop.DropItem instantiates item.m_dropPrefab - a clone off a raw ObjectDB
// prefab does not carry that (see AswidBloodPotions.MakeFood for the same fix).
// Without this, dropping a payload throws instantiating null and never clears
// it, so the same broken load is retried - and crashes - on every AI tick after.
ItemDrop.ItemData clone = template.m_itemData.Clone();
clone.m_dropPrefab = prefab;
ItemDrop.DropItem(clone, stack,
at + Random.insideUnitSphere * 0.3f, Quaternion.identity); at + Random.insideUnitSphere * 0.3f, Quaternion.identity);
left -= stack; left -= stack;
} }
@ -1265,6 +1440,10 @@ namespace RacesOfValheim
BoneServantAI servant = __instance.GetComponent<BoneServantAI>(); BoneServantAI servant = __instance.GetComponent<BoneServantAI>();
if (servant == null) return true; if (servant == null) return true;
// The one way back into vanilla: a servant that fights back hands over the whole tick for
// as long as there is a fight. Always false for the Bone Servants themselves.
if (servant.HandsToVanilla()) return true;
__result = servant.Tick(__0); __result = servant.Tick(__0);
return false; return false;
} }

View file

@ -65,6 +65,11 @@ namespace RacesOfValheim
/// "RPC_" prefix in this build - "RPC_AddOre", not "AddOre". A wrong name here is a silent no-op, /// "RPC_" prefix in this build - "RPC_AddOre", not "AddOre". A wrong name here is a silent no-op,
/// which is exactly the class of bug that takes an evening to find, so the four names below were /// which is exactly the class of bug that takes an evening to find, so the four names below were
/// read out of each Awake() rather than remembered. /// read out of each Awake() rather than remembered.
///
/// A wrong ARGUMENT LIST is not silent: Valheim 1.0 added a trailing "bool cheated" to every
/// add-item RPC (and the Fermenter's now takes the prefab's stable hash, not its name), and the
/// old calls threw EndOfStreamException on the receiving end, every tick. The servant's goods
/// are real, so cheated is always false.
/// </summary> /// </summary>
public abstract class ButlerStation public abstract class ButlerStation
{ {
@ -155,6 +160,17 @@ namespace RacesOfValheim
/// pickup routine will find them.</summary> /// pickup routine will find them.</summary>
public abstract void PullOutput(Vector3 at); public abstract void PullOutput(Vector3 at);
/// <summary>
/// How many times PullOutput is worth calling in a single visit, which is not the same question
/// as how much is finished.
///
/// One, everywhere except the hearth. The Fermenter is the reason this is not simply "keep
/// pulling while HasOutput": tapping does not clear Ready straight away - DelayedTap waits
/// m_tapDelay for the animation - so a loop on HasOutput would pull the same tap over and over
/// in one frame.
/// </summary>
public virtual int OutputPulls { get { return 1; } }
/// <summary>Seconds until something in here is ruined. float.MaxValue for the two families that /// <summary>Seconds until something in here is ruined. float.MaxValue for the two families that
/// cannot spoil, which is what keeps the urgency comparison honest without special cases.</summary> /// cannot spoil, which is what keeps the urgency comparison honest without special cases.</summary>
public virtual float SecondsToSpoil { get { return float.MaxValue; } } public virtual float SecondsToSpoil { get { return float.MaxValue; } }
@ -188,8 +204,9 @@ namespace RacesOfValheim
public static readonly MethodInfo CookFireLit = AccessTools.Method(typeof(CookingStation), "IsFireLit"); public static readonly MethodInfo CookFireLit = AccessTools.Method(typeof(CookingStation), "IsFireLit");
public static readonly MethodInfo FermenterStatus = AccessTools.Method(typeof(Fermenter), "GetStatus"); public static readonly MethodInfo FermenterStatus = AccessTools.Method(typeof(Fermenter), "GetStatus");
// 1.0 dropped the string overload: the Fermenter matches on GetStableHashCode of the name.
public static readonly MethodInfo FermenterAllowed = public static readonly MethodInfo FermenterAllowed =
AccessTools.Method(typeof(Fermenter), "IsItemAllowed", new[] { typeof(string) }); AccessTools.Method(typeof(Fermenter), "IsItemAllowed", new[] { typeof(int) });
// CookingStation.Status and Fermenter.Status are private nested enums: they cannot be named // CookingStation.Status and Fermenter.Status are private nested enums: they cannot be named
// in source, so they travel as ints. Values read from the assembly, not assumed. // in source, so they travel as ints. Values read from the assembly, not assumed.
@ -259,7 +276,7 @@ namespace RacesOfValheim
public override void Add(string prefabName) public override void Add(string prefabName)
{ {
Claim(); Claim();
Nview.InvokeRPC("RPC_AddOre", prefabName); Nview.InvokeRPC("RPC_AddOre", prefabName, false);
} }
public override bool HasWork { get { return Queued > 0; } } public override bool HasWork { get { return Queued > 0; } }
@ -307,8 +324,9 @@ namespace RacesOfValheim
get { return m_cooking.m_slots != null ? m_cooking.m_slots.Length : 0; } get { return m_cooking.m_slots != null ? m_cooking.m_slots.Length : 0; }
} }
/// <summary>GetSlot hands back three values through out parameters, one of which is a /// <summary>GetSlot hands back four values through out parameters, one of which is a
/// private enum. Through reflection that means an args array and an int.</summary> /// private enum. Through reflection that means an args array and an int. The fourth, a
/// bool "cheated", arrived with 1.0; it is ignored, but the array must have room for it.</summary>
private bool ReadSlot(int index, out string name, out float cooked, out int status) private bool ReadSlot(int index, out string name, out float cooked, out int status)
{ {
name = null; name = null;
@ -317,7 +335,7 @@ namespace RacesOfValheim
if (Vanilla.CookGetSlot == null) return false; if (Vanilla.CookGetSlot == null) return false;
object[] args = new object[] { index, null, null, null }; object[] args = new object[] { index, null, null, null, null };
Vanilla.CookGetSlot.Invoke(m_cooking, args); Vanilla.CookGetSlot.Invoke(m_cooking, args);
name = args[1] as string; name = args[1] as string;
@ -356,7 +374,7 @@ namespace RacesOfValheim
public override void Add(string prefabName) public override void Add(string prefabName)
{ {
Claim(); Claim();
Nview.InvokeRPC("RPC_AddItem", prefabName); Nview.InvokeRPC("RPC_AddItem", prefabName, false);
} }
public override bool HasWork { get { return !Vanilla.Call(Vanilla.CookEmpty, m_cooking, true); } } public override bool HasWork { get { return !Vanilla.Call(Vanilla.CookEmpty, m_cooking, true); } }
@ -394,9 +412,14 @@ namespace RacesOfValheim
public override bool HasOutput { get { return Vanilla.Call(Vanilla.CookHaveDone, m_cooking, false); } } public override bool HasOutput { get { return Vanilla.Call(Vanilla.CookHaveDone, m_cooking, false); } }
/// <summary> /// <summary>
/// ONE per done slot, and the 1 is not a stylistic choice. RPC_RemoveDoneItem spawns the /// ONE CALL, ONE SLOT - and the 1 is the count, not the slot.
/// item <c>amount</c> times PER SLOT (verified in the IL: the inner loop runs to the ///
/// argument), so passing anything above 1 would not collect faster - it would print money. /// Read again off the IL after the cook was reported losing a meat per batch, because the
/// first reading of it was wrong in a way that mattered. RPC_RemoveDoneItem walks the slots,
/// finds the FIRST one that is Done, spawns its item <c>amount</c> times, clears that slot,
/// sends RPC_SetSlotVisual and RETURNS. It does not go on to the other slots. So the
/// argument is a multiplier - anything above 1 prints money - and a hearth with five cooked
/// slots needs five calls, which is what OutputPulls below is for.
/// </summary> /// </summary>
public override void PullOutput(Vector3 at) public override void PullOutput(Vector3 at)
{ {
@ -404,6 +427,10 @@ namespace RacesOfValheim
Nview.InvokeRPC("RPC_RemoveDoneItem", at, 1); Nview.InvokeRPC("RPC_RemoveDoneItem", at, 1);
} }
/// <summary>One call per slot, so a full hearth is emptied in one visit instead of one item
/// per errand. The loop that uses this stops on HasOutput anyway; this is only its bound.</summary>
public override int OutputPulls { get { return Mathf.Max(1, SlotCount); } }
/// <summary> /// <summary>
/// The clock this whole feature exists for. Done at m_cookTime, Burnt at 2x - so what is /// The clock this whole feature exists for. Done at m_cookTime, Burnt at 2x - so what is
/// left is 2*cookTime - cookedTime, and a slot already Done is the urgent one because its /// left is 2*cookTime - cookedTime, and a slot already Done is the urgent one because its
@ -466,13 +493,14 @@ namespace RacesOfValheim
public override bool Accepts(string prefabName) public override bool Accepts(string prefabName)
{ {
return Vanilla.Allowed(Vanilla.FermenterAllowed, m_fermenter, prefabName); if (Vanilla.FermenterAllowed == null || string.IsNullOrEmpty(prefabName)) return false;
return (bool)Vanilla.FermenterAllowed.Invoke(m_fermenter, new object[] { prefabName.GetStableHashCode() });
} }
public override void Add(string prefabName) public override void Add(string prefabName)
{ {
Claim(); Claim();
Nview.InvokeRPC("RPC_AddItem", prefabName); Nview.InvokeRPC("RPC_AddItem", prefabName.GetStableHashCode(), false);
} }
public override bool HasWork { get { return Status != Vanilla.FermentEmpty; } } public override bool HasWork { get { return Status != Vanilla.FermentEmpty; } }

View file

@ -64,12 +64,13 @@ namespace RacesOfValheim
if (item != null) if (item != null)
{ {
player.Message(MessageHud.MessageType.Center, "$msg_wontwork"); player.Message(MessageHud.MessageType.Center, "$msg_wontwork");
return false; // True, not false: false makes Humanoid.UseItem cover the message with $msg_cantuseon.
return true;
} }
if (Servant() != null) if (Servant() != null)
{ {
player.Message(MessageHud.MessageType.Center, "It is already at work."); player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_butler_already_at_work"));
return false; return false;
} }
@ -77,7 +78,7 @@ namespace RacesOfValheim
if (wait > 0f) if (wait > 0f)
{ {
player.Message(MessageHud.MessageType.Center, player.Message(MessageHud.MessageType.Center,
$"The bones are not ready. {Mathf.CeilToInt(wait)}s."); ModText.Get("rov_msg_butler_bones_are_not_ready_s", Mathf.CeilToInt(wait)));
return false; return false;
} }
@ -93,7 +94,7 @@ namespace RacesOfValheim
if (prefab == null) if (prefab == null)
{ {
Jotunn.Logger.LogWarning($"[Butler] No '{m_servantPrefab}' in ZNetScene; nothing was raised."); Jotunn.Logger.LogWarning($"[Butler] No '{m_servantPrefab}' in ZNetScene; nothing was raised.");
player.Message(MessageHud.MessageType.Center, "Nothing answers."); player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_butler_nothing_answers"));
return false; return false;
} }
@ -108,7 +109,7 @@ namespace RacesOfValheim
if (ZNet.instance != null) m_nview.GetZDO().Set(KeyLastRaise, ZNet.instance.GetTime().Ticks); if (ZNet.instance != null) m_nview.GetZDO().Set(KeyLastRaise, ZNet.instance.GetTime().Ticks);
player.Message(MessageHud.MessageType.Center, "The servant rises."); player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_butler_servant_rises"));
return true; return true;
} }
@ -136,14 +137,14 @@ namespace RacesOfValheim
if (servant == null) if (servant == null)
{ {
return m_title + "\nNo servant stands here.\n" + return ModText.Get("rov_hover_butler_no_servant_stands_here_raise", m_title);
"[<color=yellow><b>$KEY_Use</b></color>] Raise one";
} }
string status = servant.Status; string status = servant.Status;
if (string.IsNullOrEmpty(status)) status = "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>

108
JotunnModStub/ConfigSync.cs Normal file
View file

@ -0,0 +1,108 @@
using System;
using System.Linq;
using System.Reflection;
using BepInEx.Configuration;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// Marks every gameplay config entry as admin-only so Jotunn syncs it from the server to the
/// clients (and locks it for non-admins in Configuration Manager).
///
/// Jotunn only recognises ITS OWN ConfigurationManagerAttributes (global namespace, in
/// Jotunn.dll) as a tag - it does an `is` check, not the field-name duck typing Configuration
/// Manager does - so our internal look-alike tag is not enough. This runs once after every
/// Bind() and adds Jotunn's tag beside whatever tags the entry already has, rather than
/// touching each of the ~350 Bind() calls.
///
/// Left local, because they are per-player preferences and syncing them would only take the
/// choice away from the player: keybinds, and the purely cosmetic entries (eye/claw colours,
/// glow, tint, rotation and offset of models, the VFX toggle, the stamina-bar toggle, debug
/// logging). Anything that changes a number the game computes with stays synced.
/// </summary>
internal static class ConfigSync
{
// Whole sections that are cosmetic or per-player.
private static readonly string[] LocalSections =
{
"Alfar - Look",
"Aswid - Claws",
"Aswid - Eyes",
"Fenrir - Appearance",
"Skeleton - Visuals",
// Food and stamina for a Skeleton who wants them: each only gives up an advantage.
"Skeleton - Mortal Habits",
"Sverm - Dorsal Spines",
"Sverm - Emberform",
"Trol - Appearance",
"War Vulture - Model",
"War Vulture - Interface",
};
// Cosmetic entries scattered through otherwise gameplay sections.
private static readonly string[] LocalKeyParts =
{
"marker light", "tint", "colour", "color", "glow", "swarm scale", "log rounds", "debug",
// The Aswid's seasick camera: motion makes some players ill, so a server cannot force it.
"camera sway",
// Each player picks their own True Form: a player model mod (VRM and the like) breaks
// under the troll costume, so a server cannot be allowed to force the costume on.
"legacy true form",
// 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)
{
FieldInfo descField = typeof(ConfigEntryBase)
.GetFields(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public)
.FirstOrDefault(f => f.FieldType == typeof(ConfigDescription));
if (descField == null)
{
Debug.LogWarning("[RacesOfValheim] Config sync skipped: ConfigEntryBase has no ConfigDescription field.");
return;
}
int synced = 0, local = 0;
foreach (ConfigDefinition def in config.Keys.ToList())
{
ConfigEntryBase entry = config[def];
if (!ShouldSync(entry)) { local++; continue; }
ConfigDescription old = entry.Description;
object[] tags = (old.Tags ?? new object[0]).Concat(new object[]
{
new global::ConfigurationManagerAttributes { IsAdminOnly = true }
}).ToArray();
descField.SetValue(entry, new ConfigDescription(old.Description, old.AcceptableValues, tags));
synced++;
}
Debug.Log($"[RacesOfValheim] Config sync: {synced} entries admin-synced, {local} left local.");
}
private static bool ShouldSync(ConfigEntryBase entry)
{
Type type = entry.SettingType;
if (type == typeof(KeyboardShortcut) || type == typeof(KeyCode)) return false;
string section = entry.Definition.Section ?? "";
string key = (entry.Definition.Key ?? "").ToLowerInvariant();
if (section.EndsWith("Keybinds", StringComparison.OrdinalIgnoreCase)) return false;
if (LocalSections.Contains(section, StringComparer.OrdinalIgnoreCase)) return false;
if (LocalKeyParts.Any(key.Contains)) return false;
// Model pose nudges (rotation/offset/yaw) are cosmetic, but "Attack Reach Offset" is a
// real hit-detection distance and must stay in step with the server.
if ((key.Contains("rotation") || key.Contains("offset") || key.Contains("yaw"))
&& !key.Contains("reach")) return false;
// Decorative note lines (CustomDrawer/ReadOnly) carry no value worth sending.
ConfigurationManagerAttributes ours = (entry.Description?.Tags ?? new object[0]).OfType<ConfigurationManagerAttributes>().FirstOrDefault();
if (ours != null && (ours.CustomDrawer != null || ours.ReadOnly == true)) return false;
return true;
}
}
}

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

@ -0,0 +1,263 @@
using System.Reflection;
using HarmonyLib;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// A form that flies on Character's native flying-creature movement (m_flying) and is steered
/// by DirectedFlightPatch. The Skadi's drakes were the first; the Aswid's bat moved onto it from
/// vanilla's debug-fly flag in the 2026 rebalance, so the two share one set of controls and
/// differ only in the numbers each form hands back here.
/// </summary>
public interface IDirectedFlyer
{
/// <summary>False while the form is on the ground on purpose (a landed drake).</summary>
bool IsFlying { get; }
/// <summary>Time.time of the last powered or grounded moment; the hover window counts from it.</summary>
float LastPoweredTime { get; set; }
float TurnSpeed { get; }
float GlideSpeed { get; }
float BoostSpeed { get; }
float SprintSpeed { get; }
float ReverseSpeed { get; }
float LiftoffSpeed { get; }
float HoverSeconds { get; }
/// <summary>Stamina per second for powered flight (forward or reverse). 0 is free.</summary>
float PoweredStaminaPerSecond { get; }
/// <summary>Stamina per second for the sprint, charged on top of the powered cost.</summary>
float SprintStaminaPerSecond { get; }
/// <summary>False forbids powered flight outright, so the form can only glide and sink.</summary>
bool CanPower { get; }
}
public static class DirectedFlight
{
/// <summary>The local player's flying form, if any. Set and cleared by the form itself.</summary>
public static IDirectedFlyer Active { get; private set; }
public static void Register(IDirectedFlyer flyer) { Active = flyer; }
public static void Unregister(IDirectedFlyer flyer)
{
if (Active == flyer) Active = null;
}
/// <summary>The active form, only while it is actually in the air.</summary>
public static IDirectedFlyer Flying => Active != null && Active.IsFlying ? Active : null;
}
// The form flips the player into Character's native flying-creature movement (m_flying = true)
// instead of the debug-fly noclip, which lets us feed it a full 3D move direction.
// Character.UpdateFlying normally reads whatever m_moveDir the vanilla input pipeline last
// wrote (ground-plane WASD relative to camera yaw only); this patch overwrites it every frame
// with the camera's actual look direction (pitch included) so the player always glides toward
// wherever the mouse is aiming, with W powering forward, Shift spending stamina for a burst of
// speed, and S beating backwards away from whatever you are looking at.
[HarmonyPatch(typeof(Character), "UpdateFlying")]
public static class DirectedFlightPatch
{
// Tangent of the unpowered descent angle: 0.4 sinks at roughly 22 degrees below level.
private const float DESCENT_SLOPE = 0.4f;
// How much of the aim heading survives the climb out of water. Mostly up, with enough
// forward in it that the player still chooses which shore they surface towards.
private const float LIFTOFF_HEADING_BLEND = 0.35f;
// How far the left stick has to be pushed before it counts as W or S.
private const float StickThreshold = 0.5f;
/// <summary>
/// True while the local player is beating backwards this frame. Read by
/// SkadiReverseFacingPatch, which keeps the body pointed at the camera while it happens.
/// </summary>
public static bool Reversing { get; private set; }
// The September 2026 hotfix dropped the bool parameter from ZInput.GetJoyLeftStickY.
// A direct call binds to whichever signature we compiled against and throws
// MissingMethodException on the other, so resolve it at runtime and accept either.
private static readonly MethodInfo JoyLeftStickYMethod =
AccessTools.Method(typeof(ZInput), "GetJoyLeftStickY", new System.Type[0]) ??
AccessTools.Method(typeof(ZInput), "GetJoyLeftStickY", new[] { typeof(bool) });
private static float JoyLeftStickY()
{
if (JoyLeftStickYMethod == null) return 0f;
return (float)JoyLeftStickYMethod.Invoke(null, JoyLeftStickYArgs);
}
// Old signature: pass smooth = true, which was its default.
private static readonly object[] JoyLeftStickYArgs =
JoyLeftStickYMethod != null && JoyLeftStickYMethod.GetParameters().Length == 1 ? new object[] { true } : null;
public static void Prefix(Character __instance, float dt)
{
if (__instance != Player.m_localPlayer) return;
IDirectedFlyer form = DirectedFlight.Flying;
if (form == null)
{
Reversing = false;
return;
}
var traverse = Traverse.Create(__instance);
Vector3 lookDir = Player.m_localPlayer.GetLookDir();
bool input = RaceInput.Allowed;
// The pad's half of W/S: the left stick, read with vanilla's own sign -
// PlayerController.FixedUpdate takes forward as the NEGATED GetJoyLeftStickY.
// 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.
float stick = -JoyLeftStickY();
// 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.
bool backward = input && !forward && (ZInput.GetButton("Backward") || stick < -StickThreshold);
// Sprint on a pad is vanilla's run button, wherever the chosen layout puts it.
bool sprintKey = input && (ZInput.GetButton("Run") || ZInput.GetButton("JoyRun"));
bool onGround = __instance.IsOnGround();
// 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
// to take back. Its half-second tail past leaving the water is welcome here - it
// keeps the climb going just long enough to clear the surface properly.
bool inWater = __instance.IsSwimming();
// Powered flight is paid for up front, per frame. A form that cannot pay - out of
// stamina, or barred from powering at all - falls through to the glide below rather
// than out of the sky.
if ((forward || backward) && !(form.CanPower && TrySpendStamina(form.PoweredStaminaPerSecond, dt)))
{
forward = false;
backward = false;
}
Reversing = backward;
// m_run only picks between the two fly speeds. Every mode now has its own speed, so
// leave it off and drive all of them through m_flySlowSpeed.
traverse.Field("m_run").SetValue(false);
// UpdateFlying rotates the body toward m_moveDir on its own, but at m_flyTurnSpeed,
// which sits at Character's 12 deg/s default because the Player prefab was never set
// up as a flying creature - a 90 degree turn would take over seven seconds, so the
// model reads as not turning at all. Give it a speed that suits a flying form.
traverse.Field("m_flyTurnSpeed").SetValue(form.TurnSpeed);
// Powered flight, ground contact and clawing out of water all refresh the hover
// window, so none of them can be followed by an immediate sink.
if (forward || backward || onGround || inWater) form.LastPoweredTime = Time.time;
Vector3 moveDir = lookDir;
float speed;
if (inWater)
{
// Wet wings still beat. Water used to be a trap: UpdateMotion hands a swimming
// character to UpdateSwimming before it ever looks at m_flying, so a form that
// touched the sea was stuck paddling with the flight controls doing nothing.
// DirectedFlightWaterPatch gives the frame back to flight, and this branch spends
// it climbing regardless of where the camera points, so the surface is always
// something you break out of rather than something you sit in. Free on purpose:
// a form that could not pay to leave the water would drown in it.
moveDir = (Vector3.up + FlatHeading(__instance, lookDir) * LIFTOFF_HEADING_BLEND).normalized;
speed = form.LiftoffSpeed;
}
else if (backward)
{
// Straight reverse thrust along the aim, pitch included: look down and beat back
// and you rise away from what you are looking at, which is the whole point of
// having a reverse - you can retreat without taking your eyes (or your breath
// attack, which fires along the same vector) off the target.
moveDir = -lookDir;
speed = form.ReverseSpeed;
}
else if (forward)
{
speed = form.BoostSpeed;
if (sprintKey && TrySpendStamina(form.SprintStaminaPerSecond, dt)) speed = form.SprintSpeed;
}
else if (onGround || Time.time - form.LastPoweredTime < form.HoverSeconds)
{
// Holding station: on the ground this keeps a touchdown from sliding the player
// forward forever, and in the air it gives the beats of level flight before the
// form starts to sink. m_moveDir stays full length so the body still turns to
// face the camera, and zeroing the speed (rather than the rigidbody velocity)
// avoids fighting the AddForce UpdateFlying queues, which caused visible jitter.
speed = 0f;
}
else
{
// Unpowered flight is a glide, not a hover with a joystick: drift along the
// heading the camera faces while losing height, so aiming at the sky without
// holding W no longer climbs.
moveDir = (FlatHeading(__instance, lookDir) + Vector3.down * DESCENT_SLOPE).normalized;
speed = form.GlideSpeed;
}
traverse.Field("m_moveDir").SetValue(moveDir);
traverse.Field("m_flySlowSpeed").SetValue(speed);
}
/// <summary>Aim flattened onto the ground plane, falling back to the body's own facing
/// when the player is looking straight up or down.</summary>
private static Vector3 FlatHeading(Character character, Vector3 lookDir)
{
Vector3 heading = new Vector3(lookDir.x, 0f, lookDir.z);
if (heading.sqrMagnitude < 0.0001f)
{
heading = character.transform.forward;
heading.y = 0f;
}
return heading.normalized;
}
/// <summary>
/// Charges this frame of a per-second cost. Returns false when the player cannot pay.
/// A rate of zero is always paid, so a free mode costs nothing and never fails.
/// </summary>
private static bool TrySpendStamina(float perSecond, float dt)
{
if (perSecond <= 0f) return true;
Player player = Player.m_localPlayer;
if (player == null) return false;
float cost = perSecond * dt;
if (!player.HaveStamina(cost)) return false;
player.UseStamina(cost);
return true;
}
}
/// <summary>
/// Character.UpdateMotion asks IsSwimming before it asks m_flying, so a flying form that
/// touched water was handed to UpdateSwimming every frame: the flight patch above never ran,
/// the form paddled on the surface, and there was no way back into the air short of finding
/// land. Hand those frames back to UpdateFlying, which is the only motion path the two methods
/// contend over: nothing else calls either of them, and everything that merely asks
/// IsSwimming - the Wet status, the animator, stamina - is left alone.
/// </summary>
[HarmonyPatch(typeof(Character), "UpdateSwimming")]
public static class DirectedFlightWaterPatch
{
private static readonly MethodInfo UpdateFlyingMethod = AccessTools.Method(typeof(Character), "UpdateFlying");
public static bool Prefix(Character __instance, float dt)
{
if (__instance != Player.m_localPlayer) return true;
if (DirectedFlight.Flying == null) return true;
// Fail open: if a game update ever renames the method, swim normally rather than
// freezing the player in place with no motion update at all.
if (UpdateFlyingMethod == null) return true;
UpdateFlyingMethod.Invoke(__instance, new object[] { dt });
return false;
}
}
}

View file

@ -33,6 +33,7 @@ namespace RacesOfValheim
// ─── Undead Fortitude (tier 4+: crit on staggered, death aura) ────────── // ─── Undead Fortitude (tier 4+: crit on staggered, death aura) ──────────
public static ConfigEntry<float> StaggerCritMultiplier; public static ConfigEntry<float> StaggerCritMultiplier;
public static ConfigEntry<float> DeathAuraRadius; public static ConfigEntry<float> DeathAuraRadius;
public static ConfigEntry<float> HumanMeatNourishmentMultiplier;
// ─── North Wind (tier 5+: AoE frost on parry, on the same cooldown) ────── // ─── North Wind (tier 5+: AoE frost on parry, on the same cooldown) ──────
public static ConfigEntry<float> NorthWindCooldown; public static ConfigEntry<float> NorthWindCooldown;
@ -79,6 +80,10 @@ namespace RacesOfValheim
new ConfigDescription("Multiplies physical damage dealt to staggered enemies, tier 4+.", new AcceptableValueRange<float>(1f, 3f))); new ConfigDescription("Multiplies physical damage dealt to staggered enemies, tier 4+.", new AcceptableValueRange<float>(1f, 3f)));
DeathAuraRadius = config.Bind(fortitude, "Death Aura Radius", 100f, DeathAuraRadius = config.Bind(fortitude, "Death Aura Radius", 100f,
new ConfigDescription("Meters within which an ally's death drops Human Meat for you, tier 4+.", new AcceptableValueRange<float>(10f, 300f))); new ConfigDescription("Meters within which an ally's death drops Human Meat for you, tier 4+.", new AcceptableValueRange<float>(10f, 300f)));
// A multiplier rather than absolute numbers: Human Meat is built from Blood Pudding's own
// nourishment at start-up, and those are the game's values, not ours to hardcode.
HumanMeatNourishmentMultiplier = config.Bind(fortitude, "Human Meat Nourishment Multiplier", 1f,
new ConfigDescription("Scales Human Meat's health, stamina and eitr against the Blood Pudding it is built from. Read once at start-up.", new AcceptableValueRange<float>(0.1f, 3f)));
const string northWind = "Draugh - North Wind"; const string northWind = "Draugh - North Wind";
NorthWindCooldown = config.Bind(northWind, "Cooldown", 20f, NorthWindCooldown = config.Bind(northWind, "Cooldown", 20f,

View file

@ -18,16 +18,25 @@ namespace RacesOfValheim
{ "NeckTail", "NeckTailGrilled" }, { "NeckTail", "NeckTailGrilled" },
{ "FishRaw", "FishCooked" }, { "FishRaw", "FishCooked" },
{ "LoxMeat", "CookedLoxMeat" }, { "LoxMeat", "CookedLoxMeat" },
{ "SerpentMeatRaw", "SerpentMeatCooked" }, { "SerpentMeat", "SerpentMeatCooked" },
{ "WolfMeat", "CookedWolfMeat" }, { "WolfMeat", "CookedWolfMeat" },
{ "DeerMeat", "CookedDeerMeat" }, { "DeerMeat", "CookedDeerMeat" },
{ "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" },
// 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
// item) and gives the stats of Seal Meat Soup.
{ "SealBlubber", "SealSoup" }
}; };
[HarmonyPatch(typeof(Humanoid), "UseItem")] [HarmonyPatch(typeof(Humanoid), "UseItem")]
@ -42,7 +51,7 @@ namespace RacesOfValheim
{ {
if (!DraughRace.IsDraugh()) if (!DraughRace.IsDraugh())
{ {
player.Message(MessageHud.MessageType.Center, "This rotting flesh is fatal to the living."); player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_draugh_this_rotting_flesh_fatal_living"));
return false; // Block consumption return false; // Block consumption
} }
// If it IS a Draugh, let them consume it via native mechanics // If it IS a Draugh, let them consume it via native mechanics
@ -86,6 +95,11 @@ namespace RacesOfValheim
var zanim = Traverse.Create(player).Field("m_zanim").GetValue<ZSyncAnimation>(); var zanim = Traverse.Create(player).Field("m_zanim").GetValue<ZSyncAnimation>();
if (zanim != null) zanim.SetTrigger("eat"); if (zanim != null) zanim.SetTrigger("eat");
} }
else
{
// Vanilla's refusal message, which EatFood never shows by itself
player.CanEat(customItemDrop.m_itemData, true);
}
return false; // Skip native UseItem return false; // Skip native UseItem
} }
} }
@ -101,7 +115,7 @@ namespace RacesOfValheim
bool isFood = item.m_shared.m_food > 0 || item.m_shared.m_foodStamina > 0 || item.m_shared.m_foodEitr > 0; bool isFood = item.m_shared.m_food > 0 || item.m_shared.m_foodStamina > 0 || item.m_shared.m_foodEitr > 0;
if (isFood) if (isFood)
{ {
player.Message(MessageHud.MessageType.Center, "Draugr consume only raw flesh, eyes, entrails or blood."); player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_draugh_draugr_consume_only_raw_flesh"));
return false; // Block it return false; // Block it
} }
} }
@ -134,16 +148,10 @@ namespace RacesOfValheim
Player.Food f = foodObj as Player.Food; Player.Food f = foodObj as Player.Food;
if (f != null && f.m_item.m_shared.m_name == item.m_shared.m_name && f.CanEatAgain()) if (f != null && f.m_item.m_shared.m_name == item.m_shared.m_name && f.CanEatAgain())
{ {
f.m_time = 0f; // Was `f.m_time = 0f`, which expired the flesh instead of renewing
f.m_item = item.Clone(); // it. This is the original of the copy the Aswid and the Trenta
// both inherited - see RaceFoodRefresh.
var consumeEffects = Traverse.Create(__instance).Field("m_consumeItemEffects").GetValue<EffectList>(); RaceFoodRefresh.Refresh(__instance, f, item);
if (consumeEffects != null) consumeEffects.Create(__instance.transform.position, Quaternion.identity, __instance.transform, 1f, -1);
var zanim = Traverse.Create(__instance).Field("m_zanim").GetValue<ZSyncAnimation>();
if (zanim != null) zanim.SetTrigger("eat");
if (item.m_shared.m_food > 0f) __instance.Heal(item.m_shared.m_food, true);
refreshed = true; refreshed = true;
break; break;
@ -156,9 +164,10 @@ namespace RacesOfValheim
return false; // Skip native EatFood return false; // Skip native EatFood
} }
// Inventory full // Full, and no slot holds this flesh. Native EatFood replaces the most
__result = false; // depleted meal past half its time, or refuses - vanilla's own rule. This
return false; // used to refuse outright, with no message.
return true;
} }
else else
{ {

View file

@ -0,0 +1,140 @@
using Jotunn.Entities;
using Jotunn.Managers;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// Human Meat, the Bonemass-tier reward: an ally who dies near a Draugh leaves a piece of
/// themselves behind, and only a Draugh can stomach it.
///
/// THIS ITEM DID NOT EXIST. Two places in the mod already used it - the drop in
/// DraughProgressionPatches.Draugh_DeathAura_Patch and the "fatal to the living" block in
/// DraughFoodPatches - and both looked it up by the name "HumanMeat", which nothing registered.
/// So the drop never happened and the block never fired: a perk the README has promised since
/// 1.4 with no item behind it. The two consumers are unchanged; what was missing was the
/// producer.
///
/// BUILT FROM TWO VANILLA ITEMS, one for the look and one for the numbers:
///
/// RawMeat gives the clone its model and icon, because that is what a piece of somebody looks
/// like, and because the Draugh's whole food identity is raw flesh.
///
/// BloodPudding gives the nourishment, copied field by field at start-up rather than written
/// down here. Blood Pudding is a real cooked food in the game's own progression, so its
/// numbers are balanced against the rest of it, and reading them means this item follows any
/// change the game makes to them. DraughConfig.HumanMeatNourishmentMultiplier scales them.
/// Its stamina is folded into health rather than copied across - see the note further down.
///
/// RawMeat is a Material in vanilla - raw meat is not edible - so m_itemType is forced to
/// Consumable. That is the one assumption in here worth knowing about: the alternative, which
/// DraughRace.CreateModAssets uses for its EdibleUncooked_ items, is to clone the COOKED item and
/// dress it as the raw one, which gets consumability for free but keeps the cooked model. If the
/// game ever refuses to eat this, that is the fallback, and the log line below prints exactly
/// what was produced so it can be told apart from a missing prefab.
/// </summary>
internal static class DraughHumanMeat
{
/// <summary>The name the two consumers look it up by. Changing it breaks both.</summary>
public const string PrefabName = "HumanMeat";
private const string LookSource = "RawMeat";
private const string NourishmentSource = "BloodPudding";
/// <summary>
/// Darkens the meat and pulls it towards blood, so a stack of Human Meat is not mistaken for
/// the deer meat it is built from. Multiplied into the material's own colour, so it darkens
/// whatever the texture already is rather than replacing it.
/// </summary>
private static readonly Color Tint = new Color(0.62f, 0.34f, 0.38f, 1f);
/// <summary>
/// Called from DraughRace.CreateModAssets, which is to say while vanilla prefabs are
/// available and before anything can ask for this item.
/// </summary>
public static void Register()
{
ItemDrop look = FindItem(LookSource);
ItemDrop nourishment = FindItem(NourishmentSource);
if (look == null || nourishment == null)
{
// Nothing is registered rather than a half-built item: the two consumers both check
// for null, so no meat is a quiet no-op, while a nameless inedible one is not.
Jotunn.Logger.LogWarning(
$"[Draugh] Human Meat not registered: '{LookSource}' " +
$"{(look == null ? "missing" : "ok")}, '{NourishmentSource}' " +
$"{(nourishment == null ? "missing" : "ok")}.");
return;
}
CustomItem item = new CustomItem(PrefabName, LookSource);
ItemDrop.ItemData.SharedData shared = item.ItemDrop.m_itemData.m_shared;
ItemDrop.ItemData.SharedData source = nourishment.m_itemData.m_shared;
shared.m_name = "$rov_item_draugh_humanmeat_name";
shared.m_description = "$rov_item_draugh_humanmeat_desc";
// Raw meat is a Material in vanilla, so none of the food fields below would be read
// without this.
shared.m_itemType = ItemDrop.ItemData.ItemType.Consumable;
// BLOOD PUDDING'S STAMINA GOES ONTO HEALTH, AND STAMINA IS LEFT AT ZERO. A Draugh does
// not use stamina, so nourishment spent there is nourishment thrown away - the food
// slot would look full while giving the race half of what it cost. Adding the two
// together keeps the item worth the same as the pudding it is balanced against, which
// is the point of reading the pudding at all.
float scale = DraughConfig.HumanMeatNourishmentMultiplier.Value;
shared.m_food = (source.m_food + source.m_foodStamina) * scale;
shared.m_foodStamina = 0f;
shared.m_foodEitr = source.m_foodEitr * scale;
shared.m_foodRegen = source.m_foodRegen;
shared.m_foodBurnTime = source.m_foodBurnTime;
shared.m_maxStackSize = source.m_maxStackSize;
shared.m_consumeStatusEffect = source.m_consumeStatusEffect;
Recolour(item.ItemDrop.gameObject);
ItemManager.Instance.AddItem(item);
Jotunn.Logger.LogInfo(
$"[Draugh] Human Meat registered from '{LookSource}' + '{NourishmentSource}': " +
$"type={shared.m_itemType} food={shared.m_food:F0} stamina={shared.m_foodStamina:F0} " +
$"eitr={shared.m_foodEitr:F0} regen={shared.m_foodRegen:F0} " +
$"burn={shared.m_foodBurnTime:F0}s stack={shared.m_maxStackSize}.");
}
private static ItemDrop FindItem(string prefabName)
{
GameObject prefab = PrefabManager.Cache.GetPrefab<GameObject>(prefabName);
return prefab != null ? prefab.GetComponent<ItemDrop>() : null;
}
/// <summary>
/// Tints the clone's own materials, on copies.
///
/// The clone's renderers still point at the vanilla RawMeat materials, which are shared with
/// every piece of raw meat in the world - writing a colour into one of those would tint the
/// lot. Each renderer gets its own copy instead, which this prefab then owns.
/// </summary>
private static void Recolour(GameObject root)
{
foreach (Renderer renderer in root.GetComponentsInChildren<Renderer>(true))
{
Material[] materials = renderer.sharedMaterials;
if (materials == null) continue;
for (int i = 0; i < materials.Length; i++)
{
if (materials[i] == null) continue;
Material copy = new Material(materials[i]);
if (copy.HasProperty("_Color")) copy.color = copy.color * Tint;
materials[i] = copy;
}
renderer.sharedMaterials = materials;
}
}
}
}

View file

@ -22,7 +22,7 @@ namespace RacesOfValheim
// Invert the Wet debuff to actually heal the Draugh // Invert the Wet debuff to actually heal the Draugh
__instance.m_healthRegenMultiplier = DraughConfig.WetHealthRegenMultiplier.Value; __instance.m_healthRegenMultiplier = DraughConfig.WetHealthRegenMultiplier.Value;
__instance.m_staminaRegenMultiplier = 1f; // No stamina penalty __instance.m_staminaRegenMultiplier = 1f; // No stamina penalty
__instance.m_tooltip = "The water restores your rotten flesh. Health regeneration increased."; __instance.m_tooltip = "$rov_se_draugh_wet_tooltip";
} }
} }
} }
@ -98,8 +98,25 @@ namespace RacesOfValheim
attacker.ApplyDamage(poisonSplash, true, false); attacker.ApplyDamage(poisonSplash, true, false);
// Visual effect for splash // Visual effect for splash. "vfx_OozeHit" is not a prefab in this game -
UnityEngine.Object.Instantiate(ZNetScene.instance.GetPrefab("vfx_OozeHit"), attacker.GetCenterPoint(), Quaternion.identity); // the blob's hit effect is vfx_blob_hit - and this was the one dead name
// in the mod that was passed to Instantiate unguarded, so every
// successful parry threw ArgumentException here and took the North Wind
// nova below down with it.
GameObject splashVfx = ZNetScene.instance.GetPrefab("vfx_blob_hit");
if (splashVfx != null)
{
UnityEngine.Object.Instantiate(splashVfx, attacker.GetCenterPoint(), Quaternion.identity);
}
// Said on every parry, which are rare enough not to be noise. A parry has
// to land inside a quarter-second window while blocking, so "nothing looks
// different" is as likely to mean the window was missed as it is to mean
// the splash did not draw - and there was no way to tell the two apart.
Jotunn.Logger.LogInfo(
$"[Draugh] Parry on '{attacker.name}': {DraughConfig.PoisonSplashDamage.Value:F0} poison, " +
$"blockTimer={blockTimer:F3} of {parryTime:F2}, " +
$"splash vfx={(splashVfx != null ? "vfx_blob_hit" : "NOT RESOLVED")}.");
// Stage 5: North Wind (AoE Frost) // Stage 5: North Wind (AoE Frost)
if (state >= 5) if (state >= 5)
@ -136,7 +153,7 @@ namespace RacesOfValheim
} }
} }
Player.m_localPlayer.Message(MessageHud.MessageType.TopLeft, "The northern wind blows"); Player.m_localPlayer.Message(MessageHud.MessageType.TopLeft, ModText.Get("rov_msg_draugh_northern_wind_blows"));
} }
} }
} }
@ -295,7 +312,7 @@ namespace RacesOfValheim
if (prefab != null) if (prefab != null)
{ {
Player.m_localPlayer.Message(MessageHud.MessageType.Center, "Swarm of Terror!"); Player.m_localPlayer.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_draugh_swarm_terror"));
for (int i = 0; i < DraughConfig.SwarmSpawnCount.Value; i++) for (int i = 0; i < DraughConfig.SwarmSpawnCount.Value; i++)
{ {
@ -339,7 +356,7 @@ namespace RacesOfValheim
float healAmount = Player.m_localPlayer.GetMaxHealth() * DraughConfig.StealBreathHealPercent.Value; float healAmount = Player.m_localPlayer.GetMaxHealth() * DraughConfig.StealBreathHealPercent.Value;
Player.m_localPlayer.Heal(healAmount); Player.m_localPlayer.Heal(healAmount);
Player.m_localPlayer.Message(MessageHud.MessageType.Center, "Steal Their Breath! Death is denied."); Player.m_localPlayer.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_draugh_steal_their_breath_death_denied"));
// Restore visuals immediately // Restore visuals immediately
if (Player.m_localPlayer.GetComponent<VisEquipment>() != null) if (Player.m_localPlayer.GetComponent<VisEquipment>() != null)

View file

@ -23,6 +23,10 @@ namespace RacesOfValheim
// Draugr is ever set up as a bench. // Draugr is ever set up as a bench.
DraughSpawner.Register(); DraughSpawner.Register();
// The Bonemass-tier drop. Registered here for the same reason as the pile: two places in
// the mod already look it up by name, and until now nothing created it.
DraughHumanMeat.Register();
// Generate EdibleUncooked prefabs for Draugh raw food logic // Generate EdibleUncooked prefabs for Draugh raw food logic
foreach (var mapping in DraughFoodPatches.rawToCookedMapping) foreach (var mapping in DraughFoodPatches.rawToCookedMapping)
{ {
@ -129,7 +133,7 @@ namespace RacesOfValheim
public System.Collections.IEnumerator UndyingWillRoutine(Player p) public System.Collections.IEnumerator UndyingWillRoutine(Player p)
{ {
p.Message(MessageHud.MessageType.Center, "Zombie Ritual Activated! Your borrowed time is fading..."); p.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_draugh_zombie_ritual_activated_borrowed_time"));
// Trigger a re-evaluation of visuals to apply the ghost effect // Trigger a re-evaluation of visuals to apply the ghost effect
if (p.GetComponent<VisEquipment>() != null) if (p.GetComponent<VisEquipment>() != null)

View file

@ -25,17 +25,17 @@ namespace RacesOfValheim
{ {
// ─── Names ─────────────────────────────────────────────────────────── // ─── Names ───────────────────────────────────────────────────────────
public const string PieceName = "DraughBodyPile"; public const string PieceName = "DraughBodyPile";
public const string PieceDisplayName = "Cursed Body Pile"; public const string PieceDisplayName = "$rov_piece_draugh_bodypile_name";
public const string BoneName = "CursedBone"; public const string BoneName = "CursedBone";
public const string BoneDisplayName = "Cursed Bone"; public const string BoneDisplayName = "$rov_item_draugh_cursedbone_name";
public const string GreaterBoneName = "GreaterCursedBone"; public const string GreaterBoneName = "GreaterCursedBone";
public const string GreaterBoneDisplayName = "Greater Cursed Bone"; public const string GreaterBoneDisplayName = "$rov_item_draugh_greatercursedbone_name";
public const string ThrallName = "DraughThrall_Draugr"; public const string ThrallName = "DraughThrall_Draugr";
public const string ThrallEliteName = "DraughThrall_DraugrElite"; public const string ThrallEliteName = "DraughThrall_DraugrElite";
public const string ThrallDisplayName = "Draugr Thrall"; public const string ThrallDisplayName = "$rov_creature_draugh_thrall_name";
public const string ThrallEliteDisplayName = "Draugr Elite Thrall"; public const string ThrallEliteDisplayName = "$rov_creature_draugh_thrallelite_name";
// RaisedThrall groups by kind for follower caps and for the roster, so these are the strings // RaisedThrall groups by kind for follower caps and for the roster, so these are the strings
// that decide "is this one an officer" - no longer a display-name comparison. // that decide "is this one an officer" - no longer a display-name comparison.
@ -118,9 +118,9 @@ namespace RacesOfValheim
public static void Register() public static void Register()
{ {
RegisterBone(BoneName, BoneDisplayName, BoneTint, RegisterBone(BoneName, BoneDisplayName, BoneTint,
"A bone that will not stay quiet. The dead sell them; the dead do not say why."); "$rov_item_draugh_cursedbone_desc");
RegisterBone(GreaterBoneName, GreaterBoneDisplayName, GreaterBoneTint, RegisterBone(GreaterBoneName, GreaterBoneDisplayName, GreaterBoneTint,
"The same bone, older, and louder. A pile fed one of these starts keeping officers."); "$rov_item_draugh_greatercursedbone_desc");
RegisterThrall(ThrallName, "Draugr", ThrallDisplayName, KindNormal, MaxFollowers); RegisterThrall(ThrallName, "Draugr", ThrallDisplayName, KindNormal, MaxFollowers);
RegisterThrall(ThrallEliteName, "Draugr_Elite", ThrallEliteDisplayName, KindElite, MaxEliteFollowers); RegisterThrall(ThrallEliteName, "Draugr_Elite", ThrallEliteDisplayName, KindElite, MaxEliteFollowers);
@ -129,7 +129,7 @@ namespace RacesOfValheim
PieceDensityLimit.Register(PieceName, PieceDensityLimit.Register(PieceName,
PieceDensityLimit.RadiusForArea(DensityAreaKm2), MaxPilesInRange, PieceDensityLimit.RadiusForArea(DensityAreaKm2), MaxPilesInRange,
"The ground here already carries {0} of these. Find another country."); "rov_msg_build_limit_draugh_bodypile");
} }
// ---------------------------------------------------------------- items // ---------------------------------------------------------------- items
@ -201,7 +201,7 @@ namespace RacesOfValheim
thrall.m_maxFollowers = maxFollowers; thrall.m_maxFollowers = maxFollowers;
thrall.m_witherSeconds = OrphanWitherSeconds; thrall.m_witherSeconds = OrphanWitherSeconds;
thrall.m_homeCheckRange = HomeCheckRange; thrall.m_homeCheckRange = HomeCheckRange;
thrall.m_refusalMessage = "The dead do not take orders from the living."; thrall.m_refusalMessage = "$rov_msg_thrall_refusal_draugh";
PrefabManager.Instance.AddPrefab(prefab); PrefabManager.Instance.AddPrefab(prefab);
} }
@ -251,8 +251,12 @@ namespace RacesOfValheim
piece.m_resources = new Piece.Requirement[0]; piece.m_resources = new Piece.Requirement[0];
piece.m_name = PieceDisplayName; piece.m_name = PieceDisplayName;
piece.m_canBeRemoved = true; piece.m_canBeRemoved = true;
piece.m_groundPiece = true; // Neither flag, like the Bone Pile. m_groundPiece made Player.UpdatePlacementGhost switch
piece.m_groundOnly = true; // the ghost off outright wherever the aim was not terrain - floors, rocks, a troll cave's
// mesh floor - so players saw no ghost at all and could not tell why. A station belongs
// in a house or a cave as much as outside.
piece.m_groundPiece = false;
piece.m_groundOnly = false;
piece.m_icon = BorrowIcon(TrophyDraugr); piece.m_icon = BorrowIcon(TrophyDraugr);
// Learned on the Furling's bushes: a Piece added to world scenery is born with no icon // Learned on the Furling's bushes: a Piece added to world scenery is born with no icon
@ -263,7 +267,7 @@ namespace RacesOfValheim
PieceManager.Instance.AddPiece(new CustomPiece(prefab, fixReference: false, new PieceConfig PieceManager.Instance.AddPiece(new CustomPiece(prefab, fixReference: false, new PieceConfig
{ {
Name = PieceDisplayName, Name = PieceDisplayName,
Description = "Feed it and it answers. The dead here are yours, if you are dead enough to ask.", Description = "$rov_piece_draugh_bodypile_desc",
PieceTable = PieceTables.Hammer, PieceTable = PieceTables.Hammer,
Category = PieceCategories.Crafting, Category = PieceCategories.Crafting,
Icon = BorrowIcon(TrophyDraugr), Icon = BorrowIcon(TrophyDraugr),

View file

@ -65,7 +65,14 @@ namespace RacesOfValheim
/// Raw flesh feeds it, a Draugr trophy is a whole batch, an Elite trophy is an officer, and a /// Raw flesh feeds it, a Draugr trophy is a whole batch, an Elite trophy is an officer, and a
/// Greater Cursed Bone upgrades it. Empty hands just report. /// Greater Cursed Bone upgrades it. Empty hands just report.
/// </summary> /// </summary>
// With an item in hand every outcome counts as handled, refusals included: false makes
// Humanoid.UseItem cover our own message with the generic "$msg_cantuseon".
private bool OnUse(Switch caller, Humanoid user, ItemDrop.ItemData item) private bool OnUse(Switch caller, Humanoid user, ItemDrop.ItemData item)
{
return Use(user, item) || item != null;
}
private bool Use(Humanoid user, ItemDrop.ItemData item)
{ {
if (user == null) return false; if (user == null) return false;
@ -75,7 +82,7 @@ namespace RacesOfValheim
if (item == null) item = FindAnyInput(inventory); if (item == null) item = FindAnyInput(inventory);
if (item == null) if (item == null)
{ {
user.Message(MessageHud.MessageType.Center, "It wants flesh, or the head of one of its own."); user.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_draugh_wants_flesh_or_head_one"));
return false; return false;
} }
@ -86,7 +93,7 @@ namespace RacesOfValheim
if (prefabName == DraughSpawner.TrophyDraugrElite && !IsUpgraded()) if (prefabName == DraughSpawner.TrophyDraugrElite && !IsUpgraded())
{ {
user.Message(MessageHud.MessageType.Center, "This pile keeps no officers yet."); user.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_draugh_this_pile_keeps_no_officers"));
return false; return false;
} }
@ -155,19 +162,19 @@ namespace RacesOfValheim
{ {
if (IsUpgraded()) if (IsUpgraded())
{ {
user.Message(MessageHud.MessageType.Center, "It has already had one."); user.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_draugh_has_already_had_one"));
return false; return false;
} }
if (BossProgressionManager.GetCurrentProgressionState() < DraughSpawner.UpgradeProgressionState) if (BossProgressionManager.GetCurrentProgressionState() < DraughSpawner.UpgradeProgressionState)
{ {
user.Message(MessageHud.MessageType.Center, "The bone will not wake. Something older has to fall first."); user.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_draugh_bone_will_not_wake_something"));
return false; return false;
} }
inventory.RemoveItem(item, 1); inventory.RemoveItem(item, 1);
m_nview.InvokeRPC("RoV_DraughUpgrade"); m_nview.InvokeRPC("RoV_DraughUpgrade");
user.Message(MessageHud.MessageType.Center, "The pile stirs. It will keep officers now."); user.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_draugh_pile_stirs_will_keep_officers"));
return true; return true;
} }
@ -287,7 +294,7 @@ namespace RacesOfValheim
if (bound.Count > 0 && Player.m_localPlayer != null) if (bound.Count > 0 && Player.m_localPlayer != null)
{ {
Player.m_localPlayer.Message(MessageHud.MessageType.Center, Player.m_localPlayer.Message(MessageHud.MessageType.Center,
$"The pile is broken. {bound.Count} will not outlast it by more than a minute."); ModText.Get("rov_msg_draugh_pile_broken_will_not_outlast", bound.Count));
} }
SetFlesh(0f); SetFlesh(0f);
@ -321,21 +328,20 @@ namespace RacesOfValheim
if (thrall.Kind == DraughSpawner.KindElite) aliveElite++; else aliveNormal++; if (thrall.Kind == DraughSpawner.KindElite) aliveElite++; else aliveNormal++;
} }
string body = $"flesh {Mathf.Floor(GetFlesh())}/{DraughSpawner.FleshPerThrall}, " + string body = ModText.Get("rov_hover_draugh_flesh_risen_waiting", Mathf.Floor(GetFlesh()), DraughSpawner.FleshPerThrall, aliveNormal, AliveCap(), GetReserve(), DraughSpawner.ReserveCap);
$"risen {aliveNormal}/{AliveCap()}, waiting {GetReserve()}/{DraughSpawner.ReserveCap}";
if (IsUpgraded()) if (IsUpgraded())
{ {
body += $"\nofficers {aliveElite}/{EliteCap()}, waiting {GetReserveElite()}/{DraughSpawner.ReserveCapElite}"; body += ModText.Get("rov_hover_draugh_officers_waiting", aliveElite, EliteCap(), GetReserveElite(), DraughSpawner.ReserveCapElite);
} }
if (m_respawnTimer > 0f) if (m_respawnTimer > 0f)
{ {
int left = Mathf.Max(1, Mathf.CeilToInt(DraughSpawner.RespawnSeconds - m_respawnTimer)); int left = Mathf.Max(1, Mathf.CeilToInt(DraughSpawner.RespawnSeconds - m_respawnTimer));
body += $"\nnext rises in {left}s"; body += ModText.Get("rov_hover_draugh_next_rises_s", left);
} }
body += "\n[<color=yellow><b>$KEY_Use</b></color>] Feed it flesh, or a draugr's head"; body += ModText.Get("rov_hover_draugh_feed_flesh_or_draugr_s");
return Localization.instance.Localize($"{DraughSpawner.PieceDisplayName} ({body})"); return Localization.instance.Localize($"{DraughSpawner.PieceDisplayName} ({body})");
} }

View file

@ -45,7 +45,7 @@ namespace RacesOfValheim
if (player.GetEitr() < DvergarConfig.RunicPingEitrCost) if (player.GetEitr() < DvergarConfig.RunicPingEitrCost)
{ {
player.Message(MessageHud.MessageType.Center, "Not enough eitr"); player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_dvergar_not_enough_eitr"));
return; return;
} }
@ -55,7 +55,7 @@ namespace RacesOfValheim
int marked = MarkSurroundings(player); int marked = MarkSurroundings(player);
player.Message(MessageHud.MessageType.Center, player.Message(MessageHud.MessageType.Center,
marked > 0 ? $"Runic Ping: {marked} echoes answer" : "Runic Ping: the stone is silent"); (marked > 0 ? ModText.Get("rov_msg_dvergar_runic_ping_echoes_answer", marked) : ModText.Get("rov_msg_dvergar_runic_ping_stone_silent")));
} }
/// <summary> /// <summary>
@ -173,7 +173,7 @@ namespace RacesOfValheim
if (player.GetEitr() < DvergarConfig.RunicOverchargeEitrCost) if (player.GetEitr() < DvergarConfig.RunicOverchargeEitrCost)
{ {
player.Message(MessageHud.MessageType.Center, "Not enough eitr"); player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_dvergar_not_enough_eitr"));
return; return;
} }
@ -186,7 +186,7 @@ namespace RacesOfValheim
// The charge is held, not permanent: it lapses if no favoured blow lands in time. // The charge is held, not permanent: it lapses if no favoured blow lands in time.
if (se != null) se.m_ttl = DvergarConfig.RunicOverchargeWindow; if (se != null) se.m_ttl = DvergarConfig.RunicOverchargeWindow;
player.Message(MessageHud.MessageType.Center, "Runic Overcharge: your next blow is loaded"); player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_dvergar_runic_overcharge_next_blow_loaded"));
} }
/// <summary> /// <summary>

View file

@ -36,7 +36,7 @@ namespace RacesOfValheim
public static class DvergarBanco public static class DvergarBanco
{ {
public const string PieceName = "DvergarContractBank"; public const string PieceName = "DvergarContractBank";
public const string PieceDisplayName = "Contract Bank"; public const string PieceDisplayName = "$rov_piece_dvergar_contractbank_name";
public const string RaceId = DvergarConfig.RaceId; public const string RaceId = DvergarConfig.RaceId;
/// <summary>The Queen's drop, mapped to state 7 in BossProgressionManager. Mistlands money for /// <summary>The Queen's drop, mapped to state 7 in BossProgressionManager. Mistlands money for
@ -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;
@ -99,7 +105,7 @@ namespace RacesOfValheim
{ {
new Troop new Troop
{ {
Id = "escort", Display = "Escort", Price = 400, NeedsUpgrade = false, Icon = "TrophyDvergr", Id = "escort", Display = "$rov_troop_dvergar_escort", Price = 400, NeedsUpgrade = false, Icon = "TrophyDvergr",
Members = new[] Members = new[]
{ {
new KeyValuePair<string, int>("Dverger", 1), new KeyValuePair<string, int>("Dverger", 1),
@ -108,7 +114,7 @@ namespace RacesOfValheim
}, },
new Troop new Troop
{ {
Id = "yard_patrol", Display = "Yard Patrol", Price = 700, NeedsUpgrade = false, Icon = "TrophyDvergr", Id = "yard_patrol", Display = "$rov_troop_dvergar_yard_patrol", Price = 700, NeedsUpgrade = false, Icon = "TrophyDvergr",
Members = new[] Members = new[]
{ {
new KeyValuePair<string, int>("Dverger", 2), new KeyValuePair<string, int>("Dverger", 2),
@ -117,7 +123,7 @@ namespace RacesOfValheim
}, },
new Troop new Troop
{ {
Id = "fire_crew", Display = "Fire Crew", Price = 1000, NeedsUpgrade = false, Icon = "TrophyDvergr", Id = "fire_crew", Display = "$rov_troop_dvergar_fire_crew", Price = 1000, NeedsUpgrade = false, Icon = "TrophyDvergr",
Members = new[] Members = new[]
{ {
new KeyValuePair<string, int>("Dverger", 1), new KeyValuePair<string, int>("Dverger", 1),
@ -127,7 +133,7 @@ namespace RacesOfValheim
}, },
new Troop new Troop
{ {
Id = "runic_crew", Display = "Runic Crew", Price = 1500, NeedsUpgrade = true, Icon = "TrophyDvergr", Id = "runic_crew", Display = "$rov_troop_dvergar_runic_crew", Price = 1500, NeedsUpgrade = true, Icon = "TrophyDvergr",
Members = new[] Members = new[]
{ {
new KeyValuePair<string, int>("Dverger", 2), new KeyValuePair<string, int>("Dverger", 2),
@ -137,7 +143,7 @@ namespace RacesOfValheim
}, },
new Troop new Troop
{ {
Id = "ash_guard", Display = "Ash Guard", Price = 2000, NeedsUpgrade = true, Icon = "TrophySeekerBrute", Id = "ash_guard", Display = "$rov_troop_dvergar_ash_guard", Price = 2000, NeedsUpgrade = true, Icon = "TrophySeekerBrute",
Members = new[] Members = new[]
{ {
new KeyValuePair<string, int>("DvergerAshlands", 2), new KeyValuePair<string, int>("DvergerAshlands", 2),
@ -195,7 +201,7 @@ namespace RacesOfValheim
PieceDensityLimit.Register(PieceName, PieceDensityLimit.Register(PieceName,
PieceDensityLimit.RadiusForArea(DensityAreaKm2), MaxBanksInRange, PieceDensityLimit.RadiusForArea(DensityAreaKm2), MaxBanksInRange,
"There is already {0} contract bank within a day's walk. One ledger per valley."); "rov_msg_build_limit_dvergar_contractbank");
} }
// ---------------------------------------------------------------- the hired // ---------------------------------------------------------------- the hired
@ -233,7 +239,7 @@ namespace RacesOfValheim
thrall.m_maxFollowers = MaxFollowers; thrall.m_maxFollowers = MaxFollowers;
thrall.m_witherSeconds = WitherSeconds; thrall.m_witherSeconds = WitherSeconds;
thrall.m_homeCheckRange = HomeCheckRange; thrall.m_homeCheckRange = HomeCheckRange;
thrall.m_refusalMessage = "Your name is not on the contract."; thrall.m_refusalMessage = "$rov_msg_thrall_refusal_dvergar";
// Ten seconds unhurt, then two percent a second - the sentry's regeneration, shared with // Ten seconds unhurt, then two percent a second - the sentry's regeneration, shared with
// the Trol's troops and the Fenrir's pack. A dead mercenary still stays dead. // the Trol's troops and the Fenrir's pack. A dead mercenary still stays dead.
@ -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))
@ -335,8 +347,12 @@ namespace RacesOfValheim
piece.m_resources = new Piece.Requirement[0]; piece.m_resources = new Piece.Requirement[0];
piece.m_name = PieceDisplayName; piece.m_name = PieceDisplayName;
piece.m_canBeRemoved = true; piece.m_canBeRemoved = true;
piece.m_groundPiece = true; // Neither flag, like the Bone Pile. m_groundPiece made Player.UpdatePlacementGhost switch
piece.m_groundOnly = true; // the ghost off outright wherever the aim was not terrain - floors, rocks, a troll cave's
// mesh floor - so players saw no ghost at all and could not tell why. A station belongs
// in a house or a cave as much as outside.
piece.m_groundPiece = false;
piece.m_groundOnly = false;
piece.m_icon = BorrowIcon("TrophyDvergr"); piece.m_icon = BorrowIcon("TrophyDvergr");
Piece template = PrefabManager.Cache.GetPrefab<Piece>("piece_workbench"); Piece template = PrefabManager.Cache.GetPrefab<Piece>("piece_workbench");
@ -348,7 +364,7 @@ namespace RacesOfValheim
PieceManager.Instance.AddPiece(new CustomPiece(prefab, fixReference: false, new PieceConfig PieceManager.Instance.AddPiece(new CustomPiece(prefab, fixReference: false, new PieceConfig
{ {
Name = PieceDisplayName, Name = PieceDisplayName,
Description = "A ledger, a seal and a heap of coin. Sign here and someone else does the dying.", Description = "$rov_piece_dvergar_contractbank_desc",
PieceTable = PieceTables.Hammer, PieceTable = PieceTables.Hammer,
Category = PieceCategories.Crafting, Category = PieceCategories.Crafting,
Icon = BorrowIcon("TrophyDvergr"), Icon = BorrowIcon("TrophyDvergr"),
@ -400,8 +416,10 @@ namespace RacesOfValheim
/// The same shape as TrolTotemRaceLockPatch - the second station in the mod that refuses the hammer /// The same shape as TrolTotemRaceLockPatch - the second station in the mod that refuses the hammer
/// outright, because hiring dvergr with dvergr money is the race's identity and not a tool it owns. /// outright, because hiring dvergr with dvergr money is the race's identity and not a tool it owns.
/// </summary> /// </summary>
// Valheim 1.0 appended a 'bool cheated' parameter to this overload. The type array has to
// match it exactly or the patch silently fails to bind and PatchAll throws.
[HarmonyPatch(typeof(Player), "PlacePiece", [HarmonyPatch(typeof(Player), "PlacePiece",
new[] { typeof(Piece), typeof(Vector3), typeof(Quaternion), typeof(bool) })] new[] { typeof(Piece), typeof(Vector3), typeof(Quaternion), typeof(bool), typeof(bool) })]
public static class DvergarBancoRaceLockPatch public static class DvergarBancoRaceLockPatch
{ {
public static bool Prefix(Player __instance, Piece __0) public static bool Prefix(Player __instance, Piece __0)
@ -410,7 +428,7 @@ namespace RacesOfValheim
if (Utils.GetPrefabName(__0.gameObject) != DvergarBanco.PieceName) return true; if (Utils.GetPrefabName(__0.gameObject) != DvergarBanco.PieceName) return true;
if (DvergarRace.IsDvergar()) return true; if (DvergarRace.IsDvergar()) return true;
__instance.Message(MessageHud.MessageType.Center, "The contract is in runic. You do not sign it."); __instance.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_dvergar_contract_runic_do_not_sign"));
return false; return false;
} }
} }

View file

@ -66,8 +66,10 @@ namespace RacesOfValheim
if (!DvergarRace.IsDvergar()) if (!DvergarRace.IsDvergar())
{ {
player.Message(MessageHud.MessageType.Center, "The ledger is not written for you."); player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_dvergar_ledger_not_written"));
return false; // With an item in hand, false makes Humanoid.UseItem cover this message with its
// generic "$msg_cantuseon"; true tells it the use was handled here.
return item != null;
} }
// The Queen's drop in hand rewrites the ledger: coin on the table, and two more crews. // The Queen's drop in hand rewrites the ledger: coin on the table, and two more crews.
@ -79,29 +81,31 @@ namespace RacesOfValheim
if (item != null) if (item != null)
{ {
player.Message(MessageHud.MessageType.Center, "$msg_wontwork"); player.Message(MessageHud.MessageType.Center, "$msg_wontwork");
return false; return true;
} }
return OpenStore(player); return OpenStore(player);
} }
// Every refusal still returns true: this only runs from an item use, where false would
// make Humanoid.UseItem replace our message with the generic "$msg_cantuseon".
private bool TryUpgrade(Player player, ItemDrop.ItemData item) private bool TryUpgrade(Player player, ItemDrop.ItemData item)
{ {
if (IsUpgraded()) if (IsUpgraded())
{ {
player.Message(MessageHud.MessageType.Center, "It has already had one."); player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_dvergar_has_already_had_one"));
return false; return true;
} }
if (BossProgressionManager.GetCurrentProgressionState() < DvergarBanco.UpgradeProgressionState) if (BossProgressionManager.GetCurrentProgressionState() < DvergarBanco.UpgradeProgressionState)
{ {
player.Message(MessageHud.MessageType.Center, "Not while she still sits under the mist."); player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_dvergar_not_while_she_still_sits"));
return false; return true;
} }
player.GetInventory().RemoveItem(item, 1); player.GetInventory().RemoveItem(item, 1);
m_nview.InvokeRPC("RoV_DvergarUpgrade"); m_nview.InvokeRPC("RoV_DvergarUpgrade");
player.Message(MessageHud.MessageType.Center, "The ledger is rewritten. Better names sign it now."); player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_dvergar_ledger_rewritten_better_names_sign"));
return true; return true;
} }
@ -115,7 +119,7 @@ namespace RacesOfValheim
Trader trader = GetComponent<Trader>(); Trader trader = GetComponent<Trader>();
if (trader == null || StoreGui.instance == null) if (trader == null || StoreGui.instance == null)
{ {
player.Message(MessageHud.MessageType.Center, "The ledger is shut."); player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_dvergar_ledger_shut"));
return false; return false;
} }
@ -140,7 +144,7 @@ namespace RacesOfValheim
if (CountGroups() >= DvergarBanco.MaxTroops) if (CountGroups() >= DvergarBanco.MaxTroops)
{ {
player.Message(MessageHud.MessageType.Center, "Five contracts is all the ledger holds."); player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_dvergar_five_contracts_all_ledger_holds"));
return; return;
} }
@ -153,13 +157,13 @@ namespace RacesOfValheim
if (CountCoins(inventory) < price) if (CountCoins(inventory) < price)
{ {
player.Message(MessageHud.MessageType.Center, "$msg_notenoughmoney"); player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_not_enough_coins"));
return; return;
} }
TakeCoins(inventory, price); TakeCoins(inventory, price);
m_nview.InvokeRPC("RoV_DvergarHire", troop.Id); m_nview.InvokeRPC("RoV_DvergarHire", troop.Id);
player.Message(MessageHud.MessageType.Center, $"{troop.Display} signs on."); player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_dvergar_signs", troop.Display));
} }
private const string CoinsPrefab = "Coins"; private const string CoinsPrefab = "Coins";
@ -273,16 +277,16 @@ namespace RacesOfValheim
private string Hover() private string Hover()
{ {
string body = $"contracts {CountGroups()}/{DvergarBanco.MaxTroops}"; string body = ModText.Get("rov_hover_dvergar_contracts", CountGroups(), DvergarBanco.MaxTroops);
// Said in as many words: a player who cannot see their own discount will read the lower // Said in as many words: a player who cannot see their own discount will read the lower
// number in the window as a mistake. // number in the window as a mistake.
float discount = Mathf.Clamp01(DvergarProgression.Current.TraderBuyDiscount); float discount = Mathf.Clamp01(DvergarProgression.Current.TraderBuyDiscount);
if (discount > 0f) body += $"\nyour seal is worth {Mathf.RoundToInt(discount * 100f)}% off"; if (discount > 0f) body += ModText.Get("rov_hover_dvergar_seal_worth_off", Mathf.RoundToInt(discount * 100f));
if (!IsUpgraded()) body += "\n(what the Queen left behind buys two more crews)"; if (!IsUpgraded()) body += ModText.Get("rov_hover_dvergar_what_queen_left_behind_buys");
body += "\n[<color=yellow><b>$KEY_Use</b></color>] Read the ledger"; body += ModText.Get("rov_hover_dvergar_read_ledger");
return Localization.instance.Localize($"{DvergarBanco.PieceDisplayName} ({body})"); return Localization.instance.Localize($"{DvergarBanco.PieceDisplayName} ({body})");
} }

View file

@ -123,14 +123,14 @@ namespace RacesOfValheim
else Jotunn.Logger.LogWarning($"[Dvergar] No icon on '{troop.Icon}' for {troop.Display}; the row " + else Jotunn.Logger.LogWarning($"[Dvergar] No icon on '{troop.Icon}' for {troop.Display}; the row " +
"keeps whatever the cloned element was showing."); "keeps whatever the cloned element was showing.");
element.transform.Find("name").GetComponent<TMP_Text>().text = troop.Display; element.transform.Find("name").GetComponent<TMP_Text>().text = Localization.instance.Localize(troop.Display);
// The DISCOUNTED price, because that is what will actually leave the player's pocket. // The DISCOUNTED price, because that is what will actually leave the player's pocket.
TMP_Text price = FindDescendant<TMP_Text>(element.transform, "price"); TMP_Text price = FindDescendant<TMP_Text>(element.transform, "price");
if (price != null) price.text = DvergarBanco.PriceFor(troop).ToString(); if (price != null) price.text = DvergarBanco.PriceFor(troop).ToString();
UITooltip tooltip = element.GetComponent<UITooltip>(); UITooltip tooltip = element.GetComponent<UITooltip>();
if (tooltip != null) tooltip.Set(troop.Display, Composition(troop), gui.m_tooltipAnchor, default(Vector2)); if (tooltip != null) tooltip.Set(Localization.instance.Localize(troop.Display), Composition(troop), gui.m_tooltipAnchor, default(Vector2));
string id = troop.Id; string id = troop.Id;
element.GetComponent<Button>().onClick.AddListener(() => element.GetComponent<Button>().onClick.AddListener(() =>
@ -154,10 +154,9 @@ namespace RacesOfValheim
int full = troop.Price; int full = troop.Price;
int paid = DvergarBanco.PriceFor(troop); int paid = DvergarBanco.PriceFor(troop);
if (paid < full) text.Append("\n\nList price ").Append(full).Append(" - your seal takes it to ").Append(paid).Append('.'); if (paid < full) text.Append("\n\n").Append(ModText.Get("rov_troop_dvergar_seal_price", full, paid));
text.Append("\n\nThey answer the follow command, knit their own wounds shut, keep your truce with " + text.Append("\n\n").Append(ModText.Get("rov_troop_dvergar_terms"));
"the mountain's dvergr, drop nothing, and do not come back. A dead crew is money spent.");
return text.ToString(); return text.ToString();
} }

View file

@ -33,7 +33,7 @@ namespace RacesOfValheim
public static class DvergarBotte public static class DvergarBotte
{ {
public const string PieceName = "DvergarRuneBarrel"; public const string PieceName = "DvergarRuneBarrel";
public const string PieceDisplayName = "Rune Barrel"; public const string PieceDisplayName = "$rov_piece_dvergar_runebarrel_name";
public const string RaceId = DvergarConfig.RaceId; public const string RaceId = DvergarConfig.RaceId;
/// <summary>How many drinks it holds. One dose is one mercenary served, so twenty is four /// <summary>How many drinks it holds. One dose is one mercenary served, so twenty is four
@ -90,8 +90,12 @@ namespace RacesOfValheim
piece.m_resources = new Piece.Requirement[0]; piece.m_resources = new Piece.Requirement[0];
piece.m_name = PieceDisplayName; piece.m_name = PieceDisplayName;
piece.m_canBeRemoved = true; piece.m_canBeRemoved = true;
piece.m_groundPiece = true; // Neither flag, like the Bone Pile. m_groundPiece made Player.UpdatePlacementGhost switch
piece.m_groundOnly = true; // the ghost off outright wherever the aim was not terrain - floors, rocks, a troll cave's
// mesh floor - so players saw no ghost at all and could not tell why. A station belongs
// in a house or a cave as much as outside.
piece.m_groundPiece = false;
piece.m_groundOnly = false;
piece.m_icon = BorrowIcon("MeadHealthMinor") ?? BorrowIcon("TrophyDvergr"); piece.m_icon = BorrowIcon("MeadHealthMinor") ?? BorrowIcon("TrophyDvergr");
Piece template = PrefabManager.Cache.GetPrefab<Piece>("piece_workbench"); Piece template = PrefabManager.Cache.GetPrefab<Piece>("piece_workbench");
@ -101,8 +105,7 @@ namespace RacesOfValheim
PieceManager.Instance.AddPiece(new CustomPiece(prefab, fixReference: false, new PieceConfig PieceManager.Instance.AddPiece(new CustomPiece(prefab, fixReference: false, new PieceConfig
{ {
Name = PieceDisplayName, Name = PieceDisplayName,
Description = "Pour a brew in and the crew drinks. What it does to them is whatever it " + Description = "$rov_piece_dvergar_runebarrel_desc",
"would have done to you - if they have the parts for it.",
PieceTable = PieceTables.Hammer, PieceTable = PieceTables.Hammer,
Category = PieceCategories.Crafting, Category = PieceCategories.Crafting,
Icon = BorrowIcon("MeadHealthMinor") ?? BorrowIcon("TrophyDvergr"), Icon = BorrowIcon("MeadHealthMinor") ?? BorrowIcon("TrophyDvergr"),
@ -192,8 +195,10 @@ namespace RacesOfValheim
} }
} }
// Valheim 1.0 appended a 'bool cheated' parameter to this overload. The type array has to
// match it exactly or the patch silently fails to bind and PatchAll throws.
[HarmonyPatch(typeof(Player), "PlacePiece", [HarmonyPatch(typeof(Player), "PlacePiece",
new[] { typeof(Piece), typeof(Vector3), typeof(Quaternion), typeof(bool) })] new[] { typeof(Piece), typeof(Vector3), typeof(Quaternion), typeof(bool), typeof(bool) })]
public static class DvergarBotteRaceLockPatch public static class DvergarBotteRaceLockPatch
{ {
public static bool Prefix(Player __instance, Piece __0) public static bool Prefix(Player __instance, Piece __0)
@ -202,7 +207,7 @@ namespace RacesOfValheim
if (Utils.GetPrefabName(__0.gameObject) != DvergarBotte.PieceName) return true; if (Utils.GetPrefabName(__0.gameObject) != DvergarBotte.PieceName) return true;
if (DvergarRace.IsDvergar()) return true; if (DvergarRace.IsDvergar()) return true;
__instance.Message(MessageHud.MessageType.Center, "You do not know what goes in it."); __instance.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_dvergar_do_not_know_what_goes"));
return false; return false;
} }
} }

View file

@ -63,9 +63,12 @@ namespace RacesOfValheim
if (!DvergarBotte.IsBrew(prefabName)) if (!DvergarBotte.IsBrew(prefabName))
{ {
player.Message(MessageHud.MessageType.Center, "$msg_wontwork"); player.Message(MessageHud.MessageType.Center, "$msg_wontwork");
return false; return true;
} }
return Fill(player, inventory, item, prefabName); // Always true from an item use, refusals included: false makes Humanoid.UseItem
// cover Fill's own message with the generic $msg_cantuseon.
Fill(player, inventory, item, prefabName);
return true;
} }
// Bare hands: pour a round if there is one, otherwise go looking for something to pour. // Bare hands: pour a round if there is one, otherwise go looking for something to pour.
@ -74,7 +77,7 @@ namespace RacesOfValheim
ItemDrop.ItemData found = FindAnyBrew(inventory); ItemDrop.ItemData found = FindAnyBrew(inventory);
if (found == null) if (found == null)
{ {
player.Message(MessageHud.MessageType.Center, "It is empty, and so are you."); player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_dvergar_empty_so_are"));
return false; return false;
} }
@ -103,7 +106,7 @@ namespace RacesOfValheim
if (!string.IsNullOrEmpty(current) && current != prefabName && GetDoses() > 0) if (!string.IsNullOrEmpty(current) && current != prefabName && GetDoses() > 0)
{ {
player.Message(MessageHud.MessageType.Center, player.Message(MessageHud.MessageType.Center,
$"There is still {DvergarBotte.BrewDisplayName(current)} in it."); ModText.Get("rov_msg_dvergar_there_still", DvergarBotte.BrewDisplayName(current)));
return false; return false;
} }
@ -148,14 +151,14 @@ namespace RacesOfValheim
StatusEffect effect = DvergarBotte.BrewEffect(brew); StatusEffect effect = DvergarBotte.BrewEffect(brew);
if (effect == null) if (effect == null)
{ {
player.Message(MessageHud.MessageType.Center, "Whatever is in it does nothing to anyone."); player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_dvergar_whatever_does_nothing_anyone"));
return false; return false;
} }
List<RaisedThrall> drinkers = InRange(); List<RaisedThrall> drinkers = InRange();
if (drinkers.Count == 0) if (drinkers.Count == 0)
{ {
player.Message(MessageHud.MessageType.Center, "Nobody is at the barrel."); player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_dvergar_nobody_at_barrel"));
return false; return false;
} }
@ -170,16 +173,14 @@ namespace RacesOfValheim
if (served == 0) if (served == 0)
{ {
player.Message(MessageHud.MessageType.Center, "Not a drop went down."); player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_dvergar_not_drop_went_down"));
return false; return false;
} }
m_nview.InvokeRPC("RoV_DvergarBotteSpend", served); m_nview.InvokeRPC("RoV_DvergarBotteSpend", served);
string what = DvergarBotte.BrewDisplayName(brew); string what = DvergarBotte.BrewDisplayName(brew);
player.Message(MessageHud.MessageType.Center, served < drinkers.Count player.Message(MessageHud.MessageType.Center, (served < drinkers.Count ? ModText.Get("rov_msg_dvergar_drink_barrel_runs_dry", served, what) : ModText.Get("rov_msg_dvergar_drink", served, what)));
? $"{served} drink {what}. The barrel runs dry."
: $"{served} drink {what}.");
return true; return true;
} }
@ -251,14 +252,12 @@ namespace RacesOfValheim
string body; string body;
if (doses <= 0 || string.IsNullOrEmpty(brew)) if (doses <= 0 || string.IsNullOrEmpty(brew))
{ {
body = "empty\n[<color=yellow><b>$KEY_Use</b></color>] Pour a brew in"; body = ModText.Get("rov_hover_dvergar_empty_pour_brew");
} }
else else
{ {
int waiting = InRange().Count; int waiting = InRange().Count;
body = $"{DvergarBotte.BrewDisplayName(brew)} {doses}/{DvergarBotte.MaxDoses}" + body = ModText.Get("rov_hover_dvergar_at_barrel_pour_round", DvergarBotte.BrewDisplayName(brew), doses, DvergarBotte.MaxDoses, waiting);
$"\n{waiting} at the barrel" +
$"\n[<color=yellow><b>$KEY_Use</b></color>] Pour a round";
} }
return Localization.instance.Localize($"{DvergarBotte.PieceDisplayName} ({body})"); return Localization.instance.Localize($"{DvergarBotte.PieceDisplayName} ({body})");

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

@ -124,9 +124,11 @@ namespace RacesOfValheim
// still clearing by about 2mm. Same size of eye, sitting deeper, and the cap is flatter // still clearing by about 2mm. Same size of eye, sitting deeper, and the cap is flatter
// for it - which is what reads as set into the skull rather than resting on it. // for it - which is what reads as set into the skull rather than resting on it.
public static readonly float EyeSeparation = 0.032f; // half the distance between them public static readonly float EyeSeparation = 0.032f; // half the distance between them
public static readonly float EyeForward = 0.081f; // centre ~63mm out public static readonly float EyeForward = 0.085f; // 0.081 left the smaller ball buried
public static readonly float EyeHeight = 0.181f; // ~15mm lower than before public static readonly float EyeHeight = 0.181f; // ~15mm lower than before
public static readonly float EyeSize = 0.062f; // ~48mm across, so a 24mm radius // Then cut down after playtest: at 0.062 the cap read as two lamps covering the face. An
// 18mm radius at the same depth leaves a cap of about 22mm on a 0.78 Dvergar.
public static readonly float EyeSize = 0.036f;
// How hard the eyes burn. The colours the game gives a starred dverger are HDR - one star // How hard the eyes burn. The colours the game gives a starred dverger are HDR - one star
// is (0, 4, 3.3) - and anything past 1 clips to white on the way to the bloom pass, which // is (0, 4, 3.3) - and anything past 1 clips to white on the way to the bloom pass, which
@ -254,7 +256,7 @@ namespace RacesOfValheim
FlatDamageType = HitData.DamageType.Blunt, FlatDamageType = HitData.DamageType.Blunt,
FlatDamage = 0f, DamagePercent = 0.15f, FlatDamage = 0f, DamagePercent = 0.15f,
StaminaPercent = 0.20f, StaminaFlat = 0f, StaminaPercent = 0.20f, StaminaFlat = 0f,
DisplayName = "Hammer" DisplayName = "$rov_compendium_dvergar_weapon_hammer"
}, },
new WeaponAffinity new WeaponAffinity
{ {
@ -262,7 +264,7 @@ namespace RacesOfValheim
FlatDamageType = HitData.DamageType.Pierce, FlatDamageType = HitData.DamageType.Pierce,
FlatDamage = 0f, DamagePercent = 0.15f, FlatDamage = 0f, DamagePercent = 0.15f,
StaminaPercent = 0.20f, StaminaFlat = 0f, StaminaPercent = 0.20f, StaminaFlat = 0f,
DisplayName = "Bow" DisplayName = "$rov_compendium_dvergar_weapon_bow"
}, },
new WeaponAffinity new WeaponAffinity
{ {
@ -270,7 +272,7 @@ namespace RacesOfValheim
FlatDamageType = HitData.DamageType.Slash, FlatDamageType = HitData.DamageType.Slash,
FlatDamage = 0f, DamagePercent = 0.15f, FlatDamage = 0f, DamagePercent = 0.15f,
StaminaPercent = 0.20f, StaminaFlat = 0f, StaminaPercent = 0.20f, StaminaFlat = 0f,
DisplayName = "Axe" DisplayName = "$rov_compendium_dvergar_weapon_axe"
}, },
new WeaponAffinity new WeaponAffinity
{ {
@ -278,7 +280,7 @@ namespace RacesOfValheim
FlatDamageType = HitData.DamageType.Pierce, FlatDamageType = HitData.DamageType.Pierce,
FlatDamage = 0f, DamagePercent = 0.15f, FlatDamage = 0f, DamagePercent = 0.15f,
StaminaPercent = 0.20f, StaminaFlat = 0f, StaminaPercent = 0.20f, StaminaFlat = 0f,
DisplayName = "Crossbow" DisplayName = "$rov_compendium_dvergar_weapon_crossbow"
} }
}; };

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

@ -1,5 +1,6 @@
using System.Collections.Generic; using System.Collections.Generic;
using System.Reflection; using System.Reflection;
using System.Reflection.Emit;
using HarmonyLib; using HarmonyLib;
using UnityEngine; using UnityEngine;
@ -110,7 +111,7 @@ namespace RacesOfValheim
DvergarAbilities.ConsumeOvercharge(Player.m_localPlayer)) DvergarAbilities.ConsumeOvercharge(Player.m_localPlayer))
{ {
ScalePhysical(hit, DvergarConfig.RunicOverchargeMultiplier); ScalePhysical(hit, DvergarConfig.RunicOverchargeMultiplier);
Player.m_localPlayer.Message(MessageHud.MessageType.TopLeft, "Runic Overcharge discharges"); Player.m_localPlayer.Message(MessageHud.MessageType.TopLeft, ModText.Get("rov_msg_dvergar_runic_overcharge_discharges"));
} }
} }
@ -220,9 +221,13 @@ namespace RacesOfValheim
// ─── Smithing and jewelry ──────────────────────────────────────────── // ─── Smithing and jewelry ────────────────────────────────────────────
/// <summary> /// <summary>
/// Metal saved when crafting and upgrading. Requirement.GetAmount is the single point both /// Metal saved when crafting, upgrading and building. Requirement.GetAmount is what the
/// the crafting panel and Player.ConsumeResources go through, so the figure the player is /// crafting panel, the build menu and Player.ConsumeResources all read, so the figure the
/// quoted and the figure they are charged can never drift apart. /// player is quoted and the figure they are charged can never drift apart.
///
/// Two vanilla paths read m_amount directly and skip GetAmount, both for build pieces:
/// Player.HaveRequirements(Piece) and Piece.DropResources. The two transpilers below route
/// them through the discount too.
/// ///
/// Scoped to the metals and gems in DvergarConfig.DiscountedResourceNames, which is what /// Scoped to the metals and gems in DvergarConfig.DiscountedResourceNames, which is what
/// keeps this a smithing perk rather than a blanket discount on every wooden wall. /// keeps this a smithing perk rather than a blanket discount on every wooden wall.
@ -232,16 +237,24 @@ namespace RacesOfValheim
{ {
public static void Postfix(Piece.Requirement __instance, ref int __result) public static void Postfix(Piece.Requirement __instance, ref int __result)
{ {
if (__result <= 1 || Player.m_localPlayer == null) return; if (Player.m_localPlayer == null) return;
if (!DvergarRace.IsDvergar()) return; if (!DvergarRace.IsDvergar()) return;
float discount = DvergarProgression.Current.SmithingDiscount; __result = DiscountedAmount(__instance, __result, DvergarProgression.Current.SmithingDiscount);
if (discount <= 0f) return; }
}
if (__instance == null || __instance.m_resItem == null) return; /// <summary>
if (!IsDiscounted(__instance.m_resItem.gameObject.name)) return; /// The single rounding rule for the smithing discount. The price a Dvergar pays and the
/// refund their piece drops both go through here, so they can't end up one ingot apart.
/// </summary>
internal static int DiscountedAmount(Piece.Requirement requirement, int amount, float discount)
{
if (amount <= 1 || discount <= 0f) return amount;
if (requirement == null || requirement.m_resItem == null) return amount;
if (!IsDiscounted(requirement.m_resItem.gameObject.name)) return amount;
__result = Mathf.Max(1, Mathf.RoundToInt(__result * (1f - discount))); return Mathf.Max(1, Mathf.RoundToInt(amount * (1f - discount)));
} }
private static bool IsDiscounted(string prefabName) private static bool IsDiscounted(string prefabName)
@ -253,6 +266,109 @@ namespace RacesOfValheim
} }
return false; return false;
} }
private static readonly FieldInfo RequirementAmountField =
AccessTools.Field(typeof(Piece.Requirement), nameof(Piece.Requirement.m_amount));
/// <summary>
/// The build check. Vanilla compares the inventory against requirement.m_amount here, so
/// the menu quoted 6 tin for a cauldron while the hammer still refused to place it with
/// fewer than 10. Every m_amount read becomes GetAmount(1), which returns m_amount for
/// everyone else and the discounted figure for a Dvergar.
/// </summary>
[HarmonyPatch(typeof(Player), nameof(Player.HaveRequirements), typeof(Piece), typeof(Player.RequirementMode))]
public static class Dvergar_HaveRequirements_Piece_Patch
{
private static readonly MethodInfo GetAmountMethod =
AccessTools.Method(typeof(Piece.Requirement), nameof(Piece.Requirement.GetAmount));
public static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)
{
int replaced = 0;
foreach (CodeInstruction instruction in instructions)
{
if (instruction.LoadsField(RequirementAmountField))
{
replaced++;
yield return new CodeInstruction(OpCodes.Ldc_I4_1).MoveLabelsFrom(instruction);
yield return new CodeInstruction(OpCodes.Callvirt, GetAmountMethod);
continue;
}
yield return instruction;
}
if (replaced == 0)
Jotunn.Logger.LogWarning("[Dvergar] HaveRequirements(Piece) no longer reads m_amount; build discount check not patched.");
}
}
/// <summary>
/// ZDO key holding the discount a Dvergar paid for a piece. Stored rather than read off
/// the builder at teardown, because anyone can smash the piece and the builder's discount
/// grows with progression.
/// </summary>
private const string PaidDiscountKey = "Dvergar_PaidDiscount";
/// <summary>
/// Stamps the discount on a piece the local Dvergar just placed. Player.PlacePiece calls
/// SetCreator on the new instance right after spawning it, and ConsumeResources charges
/// the discounted price straight after.
/// </summary>
[HarmonyPatch(typeof(Piece), nameof(Piece.SetCreator))]
public static class Dvergar_Piece_SetCreator_Patch
{
public static void Postfix(Piece __instance, long uid)
{
Player player = Player.m_localPlayer;
if (player == null || uid != player.GetPlayerID()) return;
if (!DvergarRace.IsDvergar()) return;
float discount = DvergarProgression.Current.SmithingDiscount;
if (discount <= 0f) return;
ZNetView nview = __instance.GetComponent<ZNetView>();
if (nview == null || !nview.IsValid() || !nview.IsOwner()) return;
nview.GetZDO().Set(PaidDiscountKey, discount);
}
}
/// <summary>
/// The refund. Vanilla drops requirement.m_amount when a piece is removed or destroyed,
/// which handed a Dvergar back 10 tin for a cauldron that cost 6: build, smash, repeat.
/// The drop now uses the discount stamped on the piece, so it returns what was paid.
/// </summary>
[HarmonyPatch(typeof(Piece), nameof(Piece.DropResources))]
public static class Dvergar_Piece_DropResources_Patch
{
private static readonly MethodInfo PaidAmountMethod =
AccessTools.Method(typeof(Dvergar_Piece_DropResources_Patch), nameof(PaidAmount));
public static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)
{
int replaced = 0;
foreach (CodeInstruction instruction in instructions)
{
if (instruction.LoadsField(RequirementAmountField))
{
replaced++;
yield return new CodeInstruction(OpCodes.Ldarg_0).MoveLabelsFrom(instruction);
yield return new CodeInstruction(OpCodes.Call, PaidAmountMethod);
continue;
}
yield return instruction;
}
if (replaced == 0)
Jotunn.Logger.LogWarning("[Dvergar] DropResources no longer reads m_amount; build discount refund not patched.");
}
public static int PaidAmount(Piece.Requirement requirement, Piece piece)
{
int amount = requirement.m_amount;
ZNetView nview = piece.GetComponent<ZNetView>();
if (nview == null || !nview.IsValid()) return amount;
float discount = nview.GetZDO().GetFloat(PaidDiscountKey, 0f);
return DiscountedAmount(requirement, amount, discount);
}
} }
// ─── Haldor and Hildir's favour ────────────────────────────────────── // ─── Haldor and Hildir's favour ──────────────────────────────────────
@ -281,17 +397,19 @@ namespace RacesOfValheim
{ {
if (item == null) continue; if (item == null) continue;
discounted.Add(new Trader.TradeItem // A full copy, not a hand-picked one: Valheim 1.0 hangs name, tooltip, icon,
{ // buy/increment keys and buy effects off TradeItem, and StoreGui reads some
m_prefab = item.m_prefab, // of them without null checks. Only the price is ours to change.
m_stack = item.m_stack, var copy = (Trader.TradeItem)MemberwiseCloneMethod.Invoke(item, null);
m_price = Mathf.Max(1, Mathf.RoundToInt(item.m_price * (1f - discount))), copy.m_price = Mathf.Max(1, Mathf.RoundToInt(item.m_price * (1f - discount)));
m_requiredGlobalKey = item.m_requiredGlobalKey discounted.Add(copy);
});
} }
__result = discounted; __result = discounted;
} }
private static readonly System.Reflection.MethodInfo MemberwiseCloneMethod =
AccessTools.Method(typeof(object), "MemberwiseClone");
} }
/// <summary> /// <summary>

View file

@ -16,8 +16,8 @@ namespace RacesOfValheim
{ {
base.Setup(character); base.Setup(character);
name = DvergarConfig.StatsSE; name = DvergarConfig.StatsSE;
m_name = "Stone and Forge"; m_name = "$rov_se_dvergar_stats_name";
m_tooltip = "Small, sturdy, and born to the anvil."; m_tooltip = "$rov_se_dvergar_stats_tooltip";
} }
public override void ModifyAttackStaminaUsage(float baseStaminaUse, ref float staminaUse) public override void ModifyAttackStaminaUsage(float baseStaminaUse, ref float staminaUse)
@ -80,7 +80,7 @@ namespace RacesOfValheim
var stats = ScriptableObject.CreateInstance<SE_DvergarStats>(); var stats = ScriptableObject.CreateInstance<SE_DvergarStats>();
stats.name = DvergarConfig.StatsSE; stats.name = DvergarConfig.StatsSE;
stats.m_name = "Stone and Forge"; stats.m_name = "$rov_se_dvergar_stats_name";
stats.m_icon = icon; stats.m_icon = icon;
CustomStatusEffect customStats = new CustomStatusEffect(stats, fixReference: false); CustomStatusEffect customStats = new CustomStatusEffect(stats, fixReference: false);
ItemManager.Instance.AddStatusEffect(customStats); ItemManager.Instance.AddStatusEffect(customStats);
@ -88,22 +88,22 @@ namespace RacesOfValheim
var overcharge = ScriptableObject.CreateInstance<SE_DvergarOvercharge>(); var overcharge = ScriptableObject.CreateInstance<SE_DvergarOvercharge>();
overcharge.name = DvergarConfig.OverchargeSE; overcharge.name = DvergarConfig.OverchargeSE;
overcharge.m_name = "Runic Overcharge"; overcharge.m_name = "$rov_se_dvergar_overcharge_name";
overcharge.m_tooltip = "Your next blow with a favoured weapon carries the whole of the charge."; overcharge.m_tooltip = "$rov_se_dvergar_overcharge_tooltip";
overcharge.m_icon = GetItemIcon("Eitr") ?? icon; overcharge.m_icon = GetItemIcon("Eitr") ?? icon;
ItemManager.Instance.AddStatusEffect(new CustomStatusEffect(overcharge, fixReference: false)); ItemManager.Instance.AddStatusEffect(new CustomStatusEffect(overcharge, fixReference: false));
var pingCd = ScriptableObject.CreateInstance<SE_DvergarAbilityCooldown>(); var pingCd = ScriptableObject.CreateInstance<SE_DvergarAbilityCooldown>();
pingCd.name = DvergarConfig.RunicPingCdSE; pingCd.name = DvergarConfig.RunicPingCdSE;
pingCd.m_name = "Runic Ping"; pingCd.m_name = "$rov_se_dvergar_pingcd_name";
pingCd.m_tooltip = "The runes must settle before you may call on them again."; pingCd.m_tooltip = "$rov_se_dvergar_pingcd_tooltip";
pingCd.m_icon = GetItemIcon("DvergrKeyFragment") ?? icon; pingCd.m_icon = GetItemIcon("DvergrKeyFragment") ?? icon;
ItemManager.Instance.AddStatusEffect(new CustomStatusEffect(pingCd, fixReference: false)); ItemManager.Instance.AddStatusEffect(new CustomStatusEffect(pingCd, fixReference: false));
var overchargeCd = ScriptableObject.CreateInstance<SE_DvergarAbilityCooldown>(); var overchargeCd = ScriptableObject.CreateInstance<SE_DvergarAbilityCooldown>();
overchargeCd.name = DvergarConfig.OverchargeCdSE; overchargeCd.name = DvergarConfig.OverchargeCdSE;
overchargeCd.m_name = "Overcharge Cooldown"; overchargeCd.m_name = "$rov_se_dvergar_overchargecd_name";
overchargeCd.m_tooltip = "The runes are spent."; overchargeCd.m_tooltip = "$rov_se_dvergar_overchargecd_tooltip";
overchargeCd.m_icon = GetItemIcon("Eitr") ?? icon; overchargeCd.m_icon = GetItemIcon("Eitr") ?? icon;
ItemManager.Instance.AddStatusEffect(new CustomStatusEffect(overchargeCd, fixReference: false)); ItemManager.Instance.AddStatusEffect(new CustomStatusEffect(overchargeCd, fixReference: false));
} }

View file

@ -277,10 +277,11 @@ namespace RacesOfValheim
// metre was the entire drift: the offsets below are under a centimetre in local units // metre was the entire drift: the offsets below are under a centimetre in local units
// and never stood a chance of mattering next to it. // and never stood a chance of mattering next to it.
float raceScale = GetVisualScale(player); float raceScale = GetVisualScale(player);
Vector3 baseLocal = localForward * (DvergarConfig.EyeForward * raceScale * toLocal)
+ localUp * (DvergarConfig.EyeHeight * raceScale * toLocal);
float eyeLocalSize = DvergarConfig.EyeSize * raceScale * toLocal; float height = DvergarConfig.EyeHeight;
float separation = DvergarConfig.EyeSeparation;
float eyeSize = DvergarConfig.EyeSize;
PlayerFace.AdjustEyes(player, ref height, ref separation, ref eyeSize);
for (int i = 0; i < holder.childCount; i++) for (int i = 0; i < holder.childCount; i++)
{ {
@ -291,9 +292,25 @@ namespace RacesOfValheim
// curved and the two sides do not present the same surface to a ball of this // curved and the two sides do not present the same surface to a ball of this
// radius. // radius.
float side = i == 0 ? -1f : 1f; float side = i == 0 ? -1f : 1f;
float size = i == 0 ? eyeLocalSize * DvergarConfig.LeftEyeSizeMultiplier : eyeLocalSize;
eye.localPosition = baseLocal + localRight * (side * DvergarConfig.EyeSeparation * raceScale * toLocal); // This eye's hand corrections (RaceEyeTuning).
float forward = DvergarConfig.EyeForward;
float eyeHeight = height;
float eyeSeparation = separation;
float size = eyeSize * raceScale * toLocal;
RaceEyeTuning.Eye tuning = RaceEyeTuning.For(DvergarConfig.RaceId, player, side);
if (tuning != null)
{
forward += tuning.Forward;
eyeHeight += tuning.Height;
eyeSeparation += tuning.Separation;
size *= tuning.Size;
}
if (i == 0) size *= DvergarConfig.LeftEyeSizeMultiplier;
eye.localPosition = localForward * (forward * raceScale * toLocal)
+ localUp * (eyeHeight * raceScale * toLocal)
+ localRight * (side * eyeSeparation * raceScale * toLocal);
eye.localScale = Vector3.one * size; eye.localScale = Vector3.one * size;
} }
} }

View file

@ -24,8 +24,15 @@ namespace RacesOfValheim
// is the same as no truce at all - the unexempted Fulings open fire, the player defends // is the same as no truce at all - the unexempted Fulings open fire, the player defends
// themselves, and every Berserker in earshot joins in through damage retaliation, which // themselves, and every Berserker in earshot joins in through damage retaliation, which
// IsEnemy has no say over. Verified against the asset manifest, not the wiki's display names. // IsEnemy has no say over. Verified against the asset manifest, not the wiki's display names.
// Matching is by exact prefab name, so every variant of a creature has to be named here in
// its own right - a family left half-listed is what made the truce look random by biome
// (see PaludeMobs below for the report that turned this up). "Greyling" is the Meadows
// greydwarf and was missing outright: a Trol or a Furling was at peace with the whole
// Black Forest and still fought the smallest thing in it. The Trenta never noticed,
// because its own list in RaceHostilityManager matches on substrings instead.
private static readonly HashSet<string> NeraForestaMobs = new HashSet<string> private static readonly HashSet<string> NeraForestaMobs = new HashSet<string>
{ {
"Greyling",
"Greydwarf", "Greydwarf_Elite", "Greydwarf_Shaman", "Greydwarf", "Greydwarf_Elite", "Greydwarf_Shaman",
"Goblin", "GoblinArcher", "GoblinBrute", "GoblinShaman", "Goblin", "GoblinArcher", "GoblinBrute", "GoblinShaman",
"Troll", "Troll",
@ -38,10 +45,27 @@ namespace RacesOfValheim
"Dverger", "DvergerMageFire", "DvergerMageIce", "DvergerMageSupport", "DvergerAshlands", "Dverger", "DvergerMageFire", "DvergerMageIce", "DvergerMageSupport", "DvergerAshlands",
}; };
// Skeleton_NoArcher and Draugr_Ranged are the two that were missing, and they are why an
// Aswid reported skeletons that were peaceful in one biome and hostile in another: it was
// never the biome, it was which variant that particular spawner places. Skeleton_NoArcher
// is vanilla's guaranteed-melee skeleton (the same one SkeletonBonePile borrows), so a
// spawner using it produced hostile skeletons standing next to peaceful ones. Draugr_Ranged
// is the bow draugr, left out while the melee and elite ones were exempt.
//
// 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.
//
// 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_Poison", // Skeleton, Rancid remains "Ghost", "Skeleton", "Skeleton_NoArcher", "Skeleton_Poison", // Skeleton, Rancid remains
"Draugr", "Draugr_Elite", "Skeleton_Meadows", "Skeleton_Meadows_noarcher",
"Skeleton_Swamps", "Skeleton_Swamps_noarcher",
"Skeleton_Mountains", "Skeleton_Mountains_noarcher",
"Skeleton_DeepNorth",
"Draugr", "Draugr_Elite", "Draugr_Ranged",
"Wraith", "Leech", "Abomination", "Wraith", "Leech", "Abomination",
"Blob", "BlobElite", "BlobTar", // Blob, Oozer, Growth "Blob", "BlobElite", "BlobTar", // Blob, Oozer, Growth
}; };
@ -70,22 +94,95 @@ namespace RacesOfValheim
public static bool IsSameFaction(Player player, Character monster) public static bool IsSameFaction(Player player, Character monster)
{ {
if (player == null || monster == null) return false; if (player == null || monster == null) return false;
if (!player.m_customData.TryGetValue("Race", out string race)) return false; return IsFactionMob(GetPlayerRace(player), monster.gameObject.name);
if (!RaceFactionMobs.TryGetValue(race, out HashSet<string> mobs)) return false; }
string prefabName = monster.gameObject.name.Replace("(Clone)", "").Trim(); // The same answer by name alone, for callers that only have a prefab and no live creature -
return mobs.Contains(prefabName); // the raid filter reads RandomEvent.m_spawn, which holds prefabs that were never spawned.
public static bool IsFactionMob(string race, string prefabName)
{
if (race == null || prefabName == null) return false;
if (!RaceFactionMobs.TryGetValue(race, out HashSet<string> mobs)) return false;
return mobs.Contains(prefabName.Replace("(Clone)", "").Trim());
}
// Faction set or per-race list, whichever says yes: the two questions IsEnemy is asked
// through these two files, answered without a Character. Grudges are not in here - a grudge
// is held by one creature, not by a prefab.
public static bool IsAlliedMob(string race, string prefabName)
{
if (race == null || prefabName == null) return false;
return IsFactionMob(race, prefabName) || RaceHostilityManager.IsRaceKin(race, prefabName);
}
// m_customData is the local save file's dictionary: it is only ever populated for
// the client's own m_localPlayer, so IsEnemy running on a remote AI owner (a
// dedicated server, or any other nearby player who ends up owning the mob's ZDO)
// read an empty dictionary here and treated every truce as hostile. Every other
// race-aware patch in this project reads "RacesOfValheim_Race" off the ZDO instead
// because that field actually replicates - check it first, and only fall back to
// m_customData for the single-player/local-owner case where the ZDO hasn't been
// written yet (e.g. brand new character before the race pick's Set() call runs).
public static string GetPlayerRace(Player player)
{
ZNetView nview = player.GetComponent<ZNetView>();
if (nview != null && nview.IsValid())
{
string zdoRace = nview.GetZDO().GetString("RacesOfValheim_Race", "");
if (!string.IsNullOrEmpty(zdoRace)) return zdoRace;
}
return player.m_customData.TryGetValue("Race", out string race) ? race : null;
}
// The truce used to cover the player only. A thrall is tamed, so it sits in the Players
// faction, and a wild mob of the player's own faction still saw it as fair game: a wild
// Rancid Remains walked up to a Skeleton's bone pile, ignored the Skeleton and tore into
// the garrison. The thrall's own race is on the prefab (m_commandingRace), so the same
// faction sets answer for it without needing its owner nearby.
//
// The truce breaks the moment that wild mob holds a grudge against any player: it is
// fighting the thralls' master, and the thralls should fight back.
private static bool IsThrallTruce(Character thrallSide, Character wildSide)
{
if (wildSide.IsPlayer() || wildSide.IsTamed()) return false;
RaisedThrall thrall = thrallSide.GetComponent<RaisedThrall>();
if (thrall == null || string.IsNullOrEmpty(thrall.m_commandingRace)) return false;
if (wildSide.GetComponent<RaisedThrall>() != null) return false;
if (!IsAlliedMob(thrall.m_commandingRace, wildSide.gameObject.name)) return false;
foreach (Player player in Player.GetAllPlayers())
{
if (RaceGrudge.Holds(wildSide, player)) return false;
}
return true;
} }
public static void Postfix(Character a, Character b, ref bool __result) public static void Postfix(Character a, Character b, ref bool __result)
{ {
if (!FactionsConfig.Hostility) return;
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))
{
__result = false;
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);
if (!(playerCharacter is Player p) || monster == null) return; if (!(playerCharacter is Player p) || monster == null) return;
// Same stand-down as the per-race truces get: hit your own faction and it hits back
// until the grudge runs out. See RaceGrudge.
if (RaceGrudge.Holds(monster, p)) return;
if (IsSameFaction(p, monster)) if (IsSameFaction(p, monster))
{ {
__result = false; __result = false;
@ -110,26 +207,79 @@ namespace RacesOfValheim
[HarmonyPatch(typeof(MonsterAI), "UpdateTarget")] [HarmonyPatch(typeof(MonsterAI), "UpdateTarget")]
public static class FactionStaticTargetPatch public static class FactionStaticTargetPatch
{ {
// Comfortably past FindRandomStaticTarget's own 10 m search radius, so a truce holds for // This used to be 20 m, sized against FindRandomStaticTarget's 10 m search. The other pick,
// any piece the mob could have picked in the first place. // FindClosestStaticPriorityTarget, searches the mob's whole m_viewRange, so a skeleton 25 m
private const float FactionCheckRange = 20f; // from an Aswid could still lock onto a piece and the veto never ran - and it never ran at
// all once the player stepped away from the base mid-raid. The rule is now "an ally is
// around, the whole base is safe": 100 m is roughly a raid's own area (RandomEvent's
// m_eventRange), so anyone still inside the raid covers every piece in it, whoever built it.
private const float FactionCheckRange = 100f;
public static void Postfix(MonsterAI __instance) public static void Postfix(MonsterAI __instance)
{ {
if (!FactionsConfig.Hostility) return;
Traverse targetStatic = Traverse.Create(__instance).Field("m_targetStatic"); Traverse targetStatic = Traverse.Create(__instance).Field("m_targetStatic");
if (targetStatic.GetValue() == null) return; // GetValue() hands back a plain object, and object == null skips Unity's destroyed
// check: a piece smashed or removed while targeted stays non-null here, and touching
// its gameObject throws. That throw escapes into MonoUpdaters.FixedUpdate and stops
// every AI after this one for the frame, every frame, until the field changes.
Component target = targetStatic.GetValue() as Component;
if (target == null)
{
if (targetStatic.GetValue() != null) targetStatic.SetValue(null);
return;
}
Character monster = Traverse.Create(__instance).Field<Character>("m_character").Value; Character monster = Traverse.Create(__instance).Field<Character>("m_character").Value;
if (monster == null) return; if (monster == null) return;
// A piece an allied race built is never a target, with or without anyone around.
// See FactionPieceTruce.
if (FactionPieceTruce.Protects(target.gameObject, monster))
{
targetStatic.SetValue(null);
return;
}
foreach (Player player in Player.GetAllPlayers()) foreach (Player player in Player.GetAllPlayers())
{ {
if (Vector3.Distance(player.transform.position, monster.transform.position) > FactionCheckRange) continue; if (Vector3.Distance(player.transform.position, monster.transform.position) > FactionCheckRange) continue;
if (!FactionHostilityPatch.IsSameFaction(player, monster)) continue; // A player this creature holds a grudge against is no ally of it right now.
if (RaceGrudge.Holds(monster, player)) continue;
if (!FactionHostilityPatch.IsAlliedMob(FactionHostilityPatch.GetPlayerRace(player), monster.gameObject.name)) continue;
targetStatic.SetValue(null); targetStatic.SetValue(null);
return; return;
} }
} }
} }
// IsEnemy is not the only way a mob picks the player, and the other way ignores it
// completely. BaseAI.FindEnemy() walks every character asking IsEnemy - which both truce
// patches above answer - but when that walk comes up empty and the creature HuntPlayer()s,
// it falls through to Player.GetClosestPlayer(transform.position, 200f) and returns whoever
// it finds, without asking anything about factions.
//
// That fall-through is why the Black Forest truce looked broken to the Trol's testers:
// MonsterAI.UpdateAI turns hunting on for every IsEventCreature() while an event is running,
// and the events that reach a Trol are "the forest is moving" (Greydwarves), "you are being
// hunted" (Trolls) and the Fuling army - the exact three they named. Anything a SpawnSystem
// entry or a TriggerSpawner flags with huntPlayer arrives by the same door.
//
// Filtering the RESULT rather than restating the rule keeps one source of truth: the public
// instance IsEnemy(Character) calls the static overload both postfixes above hook, so this
// honours whatever the faction sets and RaceHostilityManager's per-race lists already agree
// on. Retaliation does not come through here either way - a mob the player hits is targeted
// through BaseAI.OnDamaged/SetTarget, which never goes near FindEnemy. That target only
// SURVIVES because of RaceGrudge, though: UpdateTarget drops anything IsEnemy refuses.
[HarmonyPatch(typeof(BaseAI), "FindEnemy")]
public static class FactionHuntPlayerPatch
{
public static void Postfix(BaseAI __instance, ref Character __result)
{
if (!FactionsConfig.Hostility) return;
if (__result == null || !__result.IsPlayer()) return;
if (!__instance.IsEnemy(__result)) __result = null;
}
}
} }

View file

@ -69,7 +69,7 @@ namespace RacesOfValheim
private static readonly ShopDefinition GreydwarfShop = new ShopDefinition private static readonly ShopDefinition GreydwarfShop = new ShopDefinition
{ {
DisplayName = "Greydwarf", DisplayName = "$enemy_greydwarf",
JokeCategory = JokeLegnoFalegname, JokeCategory = JokeLegnoFalegname,
Items = WithDefaults(new List<CatalogEntry> Items = WithDefaults(new List<CatalogEntry>
{ {
@ -92,7 +92,7 @@ namespace RacesOfValheim
private static readonly ShopDefinition TrollShop = new ShopDefinition private static readonly ShopDefinition TrollShop = new ShopDefinition
{ {
DisplayName = "Troll", DisplayName = "$enemy_troll",
JokeCategory = JokeTroll, JokeCategory = JokeTroll,
Items = WithDefaults(new List<CatalogEntry> Items = WithDefaults(new List<CatalogEntry>
{ {
@ -111,13 +111,12 @@ namespace RacesOfValheim
private static readonly ShopDefinition FulingShop = new ShopDefinition private static readonly ShopDefinition FulingShop = new ShopDefinition
{ {
DisplayName = "Fuling", DisplayName = "$enemy_goblin",
JokeCategory = JokeGoblin, JokeCategory = JokeGoblin,
Items = WithDefaults(new List<CatalogEntry> Items = WithDefaults(new List<CatalogEntry>
{ {
new CatalogEntry("BlackMetalScrap", 1), new CatalogEntry("BlackMetalScrap", 1),
new CatalogEntry("LoxMeat", 1), new CatalogEntry("LoxMeat", 1),
new CatalogEntry("SerpentMeat", 1),
new CatalogEntry("SerpentScale", 1), new CatalogEntry("SerpentScale", 1),
new CatalogEntry("LoxPelt", 2), new CatalogEntry("LoxPelt", 2),
new CatalogEntry("Flax", 5), new CatalogEntry("Flax", 5),
@ -133,6 +132,7 @@ namespace RacesOfValheim
// runtime, so hovering a Fuling merchant once will name them in the log. // runtime, so hovering a Fuling merchant once will name them in the log.
new CatalogEntry("Tuna", 50), new CatalogEntry("Tuna", 50),
new CatalogEntry("CoralCod", 70), new CatalogEntry("CoralCod", 70),
new CatalogEntry("SerpentMeat", 200),
new CatalogEntry("GoblinTotem", 350), new CatalogEntry("GoblinTotem", 350),
new CatalogEntry("TrophyGoblin", 350), new CatalogEntry("TrophyGoblin", 350),
new CatalogEntry("TrophyGoblinShaman", 350), new CatalogEntry("TrophyGoblinShaman", 350),
@ -152,7 +152,7 @@ namespace RacesOfValheim
// in declaration order. // in declaration order.
private static readonly ShopDefinition GoblinShamanShop = new ShopDefinition private static readonly ShopDefinition GoblinShamanShop = new ShopDefinition
{ {
DisplayName = "Fuling Shaman", DisplayName = "$enemy_goblinshaman",
JokeCategory = JokeGoblin, JokeCategory = JokeGoblin,
Items = new List<CatalogEntry>(FulingShop.Items) Items = new List<CatalogEntry>(FulingShop.Items)
{ {
@ -185,7 +185,7 @@ namespace RacesOfValheim
/// </summary> /// </summary>
private static readonly ShopDefinition UlvShop = new ShopDefinition private static readonly ShopDefinition UlvShop = new ShopDefinition
{ {
DisplayName = "Ulv", DisplayName = "$enemy_ulv",
JokeCategory = JokeLupoLicantropo, JokeCategory = JokeLupoLicantropo,
Items = WithDefaults(new List<CatalogEntry> Items = WithDefaults(new List<CatalogEntry>
{ {
@ -203,7 +203,7 @@ namespace RacesOfValheim
private static readonly ShopDefinition FenringShop = new ShopDefinition private static readonly ShopDefinition FenringShop = new ShopDefinition
{ {
DisplayName = "Fenring", DisplayName = "$enemy_fenring",
JokeCategory = JokeLupoLicantropo, JokeCategory = JokeLupoLicantropo,
Items = WithDefaults(new List<CatalogEntry> Items = WithDefaults(new List<CatalogEntry>
{ {
@ -216,7 +216,7 @@ namespace RacesOfValheim
private static readonly ShopDefinition CultistShop = new ShopDefinition private static readonly ShopDefinition CultistShop = new ShopDefinition
{ {
DisplayName = "Cultist", DisplayName = "$enemy_fenringcultist",
JokeCategory = JokeStrega, JokeCategory = JokeStrega,
Items = WithDefaults(new List<CatalogEntry> Items = WithDefaults(new List<CatalogEntry>
{ {
@ -228,7 +228,7 @@ namespace RacesOfValheim
private static readonly ShopDefinition DvergShop = new ShopDefinition private static readonly ShopDefinition DvergShop = new ShopDefinition
{ {
DisplayName = "Dverg", DisplayName = "$rov_merchant_dverg_name",
JokeCategory = JokeNano, JokeCategory = JokeNano,
Items = WithDefaults(new List<CatalogEntry> Items = WithDefaults(new List<CatalogEntry>
{ {
@ -241,7 +241,7 @@ namespace RacesOfValheim
private static readonly ShopDefinition DraugrShop = new ShopDefinition private static readonly ShopDefinition DraugrShop = new ShopDefinition
{ {
DisplayName = "Draugr", DisplayName = "$enemy_draugr",
JokeCategory = JokeNonMortoZombie, JokeCategory = JokeNonMortoZombie,
Items = WithDefaults(new List<CatalogEntry> Items = WithDefaults(new List<CatalogEntry>
{ {
@ -266,7 +266,7 @@ namespace RacesOfValheim
private static readonly ShopDefinition SkeletonShop = new ShopDefinition private static readonly ShopDefinition SkeletonShop = new ShopDefinition
{ {
DisplayName = "Skeleton", DisplayName = "$enemy_skeleton",
JokeCategory = JokeScheletro, JokeCategory = JokeScheletro,
Items = WithDefaults(new List<CatalogEntry> Items = WithDefaults(new List<CatalogEntry>
{ {
@ -284,7 +284,7 @@ namespace RacesOfValheim
private static readonly ShopDefinition GhostShop = new ShopDefinition private static readonly ShopDefinition GhostShop = new ShopDefinition
{ {
DisplayName = "Ghost", DisplayName = "$enemy_ghost",
JokeCategory = JokeFantasma, JokeCategory = JokeFantasma,
Items = WithDefaults(new List<CatalogEntry> Items = WithDefaults(new List<CatalogEntry>
{ {
@ -295,7 +295,7 @@ namespace RacesOfValheim
private static readonly ShopDefinition WraithShop = new ShopDefinition private static readonly ShopDefinition WraithShop = new ShopDefinition
{ {
DisplayName = "Wraith", DisplayName = "$enemy_wraith",
JokeCategory = JokeFantasma, JokeCategory = JokeFantasma,
Items = WithDefaults(new List<CatalogEntry> Items = WithDefaults(new List<CatalogEntry>
{ {
@ -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 },

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