Compare commits

..

90 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
2125e71682 feat: a rare Trol surprise 2026-10-30 23:37:19 +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
2147c892b0 Merge remote-tracking branch 'origin/main' into localisation 2026-10-29 19:35:45 +01:00
9117c0b251 Merge remote-tracking branch 'origin/main' into localisation 2026-10-29 16:22:58 +01:00
356e0f44d8 Merge remote-tracking branch 'origin/main' into localisation 2026-10-28 13:57:19 +01:00
4fe7a9787d Merge remote-tracking branch 'origin/main' into localisation 2026-10-27 19:36:18 +01:00
76085f14b0 Merge remote-tracking branch 'origin/main' into localisation 2026-10-26 16:09:04 +01:00
68b87d181a Merge remote-tracking branch 'origin/main' into localisation 2026-10-25 18:25:22 +01:00
4fcfe6fd7c Merge remote-tracking branch 'origin/main' into localisation 2026-10-25 17:58:37 +01:00
d689834070 Merge remote-tracking branch 'origin/main' into localisation 2026-10-24 18:28:28 +02:00
fe8b3ea270 Merge remote-tracking branch 'origin/main' into localisation 2026-10-23 22:27:37 +02:00
cacc8ead4a Merge branch 'main' into localisation 2026-10-23 19:07:23 +02:00
99f409c8be Merge remote-tracking branch 'origin/main' into localisation 2026-10-19 14:30:42 +02:00
b3bdb0f75a Merge remote-tracking branch 'origin/main' into localisation 2026-10-19 14:26:56 +02:00
92c80e3b87 Merge branch 'main' into localisation 2026-10-18 00:19:25 +02:00
589127b7df Merge branch 'main' into localisation 2026-10-17 20:30:37 +02:00
174e615ed9 Merge branch 'main' into localisation 2026-10-17 20:28:54 +02:00
20e08432b8 Merge branch 'main' into localisation 2026-10-17 19:39:13 +02:00
a28fb19845 Merge branch 'main' into localisation 2026-10-17 19:33:39 +02:00
d28f9e353a Merge branch 'main' into localisation 2026-10-17 19:07:01 +02:00
d120ec8dc2 Merge branch 'main' into localisation 2026-10-17 17:15:54 +02:00
a2a4bcf451 Merge branch 'main' into localisation 2026-10-17 16:24:09 +02:00
b6e085e378 Merge branch 'main' into localisation 2026-10-17 16:22:29 +02:00
268ed47589 Merge branch 'main' into localisation 2026-10-17 15:59:09 +02:00
03cca64a48 Merge branch 'main' into localisation 2026-10-17 15:51:54 +02:00
e38df0b7e0 Merge branch 'main' into localisation 2026-10-17 15:32:06 +02:00
bf63b790f1 Merge branch 'main' into localisation 2026-10-14 16:41:52 +02:00
358b537cef Merge branch 'main' into localisation 2026-10-08 18:22:13 +02:00
79 changed files with 3072 additions and 383 deletions

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -148,12 +148,17 @@ namespace RacesOfValheim
} }
/// <summary>A pulse of lightning on every hostile creature within a radius of the Alfr.</summary> /// <summary>A pulse of lightning on every hostile creature within a radius of the Alfr.</summary>
public static void Pulse(Player player, float radius, float damage) /// <returns>True if it struck at least one creature.</returns>
public static bool Pulse(Player player, float radius, float damage)
{ {
bool struck = false;
foreach (Character character in CharactersIn(player.transform.position, radius)) foreach (Character character in CharactersIn(player.transform.position, radius))
{ {
if (IsHostile(player, character)) Strike(player, character, damage, character.GetCenterPoint()); if (!IsHostile(player, character)) continue;
Strike(player, character, damage, character.GetCenterPoint());
struck = true;
} }
return struck;
} }
private static IEnumerable<Character> CharactersIn(Vector3 center, float radius) private static IEnumerable<Character> CharactersIn(Vector3 center, float radius)
@ -177,35 +182,64 @@ namespace RacesOfValheim
Vector3 direction = aim.forward; Vector3 direction = aim.forward;
float distance = AlfarPowerConfig.SkridDistance.Value; float distance = AlfarPowerConfig.SkridDistance.Value;
if (!Pay(player, AlfarPowerConfig.SkridCost.Value)) return;
// Stop short of whatever is in the way, so the blink never ends inside a wall. // Stop short of whatever is in the way, so the blink never ends inside a wall.
Vector3 destination = origin + direction * distance; Vector3 destination = origin + direction * distance;
RaycastHit[] hits = Physics.RaycastAll(origin, direction, distance, ~0, QueryTriggerInteraction.Ignore); if (NearestHit(player, origin, direction, distance, out RaycastHit wall))
float nearest = float.MaxValue;
foreach (RaycastHit hit in hits)
{ {
if (hit.collider.GetComponentInParent<Player>() == player) continue; destination = wall.point - direction * 0.6f;
if (hit.distance < nearest)
{
nearest = hit.distance;
destination = hit.point - direction * 0.6f;
}
} }
// Back down to the player's own height: the origin was at the chest. // Back down to the player's own height: the origin was at the chest. The floor is found
// with a short ray down from the landing point, never with GetSolidHeight: that one casts
// from 1000 m up, so under any roof (a crypt, a cave, a house) it returned the roof and
// put the Alfr on top of it. A flat 1 m drop also sank the feet under the floor when the
// blink was aimed at it.
const float FloorSearch = 3f;
if (NearestHit(player, destination, Vector3.down, FloorSearch, out RaycastHit floor))
{
destination.y = floor.point.y + 0.05f;
}
else if (player.InInterior())
{
// No floor under the landing point inside a dungeon: it would end in the void the
// dungeon floats in. Cancel before paying.
return;
}
else
{
destination.y -= 1.0f; destination.y -= 1.0f;
if (ZoneSystem.instance != null) if (ZoneSystem.instance != null)
{ {
float ground = ZoneSystem.instance.GetSolidHeight(destination); // Terrain only, so a roof overhead is never mistaken for the ground.
float ground = ZoneSystem.instance.GetGroundHeight(destination);
if (destination.y < ground) destination.y = ground + 0.1f; if (destination.y < ground) destination.y = ground + 0.1f;
} }
}
if (!Pay(player, AlfarPowerConfig.SkridCost.Value)) return;
Teleport(player, destination); Teleport(player, destination);
StartCooldown("skrid", AlfarPowerConfig.SkridCooldown.Value); StartCooldown("skrid", AlfarPowerConfig.SkridCooldown.Value);
AlfarFx.Spawn("fx_JotunWitch_LightningBolt_Explosion", origin); AlfarFx.Spawn("fx_JotunWitch_LightningBolt_Explosion", origin);
} }
/// <summary>The nearest solid hit along a ray, skipping the caster's own colliders.</summary>
private static bool NearestHit(Player player, Vector3 origin, Vector3 direction, float distance, out RaycastHit nearest)
{
nearest = default;
bool found = false;
foreach (RaycastHit hit in Physics.RaycastAll(origin, direction, distance, ~0, QueryTriggerInteraction.Ignore))
{
if (hit.collider.GetComponentInParent<Player>() == player) continue;
if (!found || hit.distance < nearest.distance)
{
nearest = hit;
found = true;
}
}
return found;
}
/// <summary> /// <summary>
/// Moves the body without the teleport fade: the rigidbody is repositioned and its velocity /// Moves the body without the teleport fade: the rigidbody is repositioned and its velocity
/// zeroed, and the fall tracker is reset so a blink up a cliff does not count as a fall. /// zeroed, and the fall tracker is reset so a blink up a cliff does not count as a fall.
@ -396,7 +430,11 @@ namespace RacesOfValheim
AlfarEitr.Spend(player, cost); AlfarEitr.Spend(player, cost);
} }
if (IsHostile(player, target)) Strike(player, target, AlfarPowerConfig.BeamDps.Value * tick, end); if (IsHostile(player, target))
{
Strike(player, target, AlfarPowerConfig.BeamDps.Value * tick, end);
FormMelee.RaiseSkill(Skills.SkillType.ElementalMagic, tick); // a full hit per second on target
}
} }
private static void RaiseHand(Player player) private static void RaiseHand(Player player)
@ -548,14 +586,19 @@ namespace RacesOfValheim
const float tick = 0.5f; const float tick = 0.5f;
nextTick = Time.time + tick; nextTick = Time.time + tick;
bool struck = false;
foreach (Collider collider in Physics.OverlapSphere(transform.position, Radius, ~0, QueryTriggerInteraction.Ignore)) foreach (Collider collider in Physics.OverlapSphere(transform.position, Radius, ~0, QueryTriggerInteraction.Ignore))
{ {
Character character = collider.GetComponentInParent<Character>(); Character character = collider.GetComponentInParent<Character>();
if (character == null || character == Owner || character.IsDead() || character.IsTamed()) continue; if (character == null || character == Owner || character.IsDead() || character.IsTamed()) continue;
if (!BaseAI.IsEnemy(Owner, character)) continue; if (!BaseAI.IsEnemy(Owner, character)) continue;
AlfarPowers.Strike(Owner, character, DamagePerSecond * tick, character.GetCenterPoint()); AlfarPowers.Strike(Owner, character, DamagePerSecond * tick, character.GetCenterPoint());
struck = true;
} }
// Once per tick, not per creature: a full hit per second the storm strikes something.
if (struck && Owner == Player.m_localPlayer) FormMelee.RaiseSkill(Skills.SkillType.ElementalMagic, tick);
Vector2 offset = Random.insideUnitCircle * Radius; Vector2 offset = Random.insideUnitCircle * Radius;
AlfarFx.Spawn("fx_JotunWitch_LightningBolt_Explosion", transform.position + new Vector3(offset.x, 0f, offset.y)); AlfarFx.Spawn("fx_JotunWitch_LightningBolt_Explosion", transform.position + new Vector3(offset.x, 0f, offset.y));
} }

Binary file not shown.

After

Width:  |  Height:  |  Size: 53 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 216 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 259 KiB

View file

@ -118,6 +118,27 @@ namespace RacesOfValheim
} }
} }
/// <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> /// <summary>
/// Sleepers. UpdateSleep picks the closest player itself, possibly a remote bat, so the counter /// 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 /// goes up for the whole call and the bat test happens in the IsDebugFlying postfix, which only

View file

@ -107,6 +107,7 @@ namespace RacesOfValheim
public static ConfigEntry<float> BatMaxDuration; public static ConfigEntry<float> BatMaxDuration;
public static ConfigEntry<float> BatDurationPerState; public static ConfigEntry<float> BatDurationPerState;
public static ConfigEntry<float> BatCooldown; public static ConfigEntry<float> BatCooldown;
public static ConfigEntry<float> BatCombatLock;
// ─── Vampiric Aura (passive, always active) ────────────────────────────── // ─── Vampiric Aura (passive, always active) ──────────────────────────────
public static ConfigEntry<float> AuraTickInterval; public static ConfigEntry<float> AuraTickInterval;
@ -292,6 +293,8 @@ namespace RacesOfValheim
new ConfigDescription("Seconds added to the max duration per progression state. Does nothing while the max duration is 0.", new AcceptableValueRange<float>(0f, 600f))); new ConfigDescription("Seconds added to the max duration per progression state. Does nothing while the max duration is 0.", new AcceptableValueRange<float>(0f, 600f)));
BatCooldown = config.Bind(batform, "Cooldown", 0f, BatCooldown = config.Bind(batform, "Cooldown", 0f,
new ConfigDescription("Seconds after leaving bat form before you can take it again. 0 means none.", new AcceptableValueRange<float>(0f, 3600f))); new ConfigDescription("Seconds after leaving bat form before you can take it again. 0 means none.", new AcceptableValueRange<float>(0f, 3600f)));
BatCombatLock = config.Bind(batform, "Combat Lock", 2.5f,
new ConfigDescription("Seconds after you last lost health (a hit, or a tick of fire, poison or bleeding) before you can take bat form. Turning back from bat form is never blocked. 0 means none.", new AcceptableValueRange<float>(0f, 30f)));
const string aura = "Aswid - Vampiric Aura"; const string aura = "Aswid - Vampiric Aura";
AuraTickInterval = config.Bind(aura, "Tick Interval", 0.25f, AuraTickInterval = config.Bind(aura, "Tick Interval", 0.25f,

View file

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

View file

@ -615,6 +615,14 @@ namespace RacesOfValheim
return; return;
} }
// No escaping a fight by taking wing mid-blow: the form waits until the hits stop.
float hurtLeft = AswidConfig.BatCombatLock.Value - (Time.time - LastHurtTime);
if (hurtLeft > 0f)
{
Player.m_localPlayer.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_aswid_bat_combat_lock", Mathf.CeilToInt(hurtLeft)));
return;
}
float cooldownLeft = AswidConfig.BatCooldown.Value - (Time.time - lastBatEndTime); float cooldownLeft = AswidConfig.BatCooldown.Value - (Time.time - lastBatEndTime);
if (cooldownLeft > 0f) if (cooldownLeft > 0f)
{ {
@ -629,6 +637,10 @@ namespace RacesOfValheim
// fresh session never begins on cooldown. // fresh session never begins on cooldown.
private float lastBatEndTime = -100000f; private float lastBatEndTime = -100000f;
// When the local player last lost health, for the bat's combat lock. Written by
// Aswid_BatCombatLock_Patch for every race; only the Aswid reads it.
public static float LastHurtTime = -100000f;
// The one bat or mist routine in flight, if any. Kept so ResetRace can stop it: a // The one bat or mist routine in flight, if any. Kept so ResetRace can stop it: a
// TransformIntoBatRoutine left running through a reset finishes its 1.1s gesture and // TransformIntoBatRoutine left running through a reset finishes its 1.1s gesture and
// turns a freshly reset Human into a bat. // turns a freshly reset Human into a bat.
@ -1179,6 +1191,7 @@ namespace RacesOfValheim
int layerMask = LayerMask.GetMask("character", "character_net", "character_ghost"); int layerMask = LayerMask.GetMask("character", "character_net", "character_ghost");
var colliders = Physics.OverlapSphere(center, radius, layerMask); var colliders = Physics.OverlapSphere(center, radius, layerMask);
bool hitCreature = false;
foreach (var col in colliders) foreach (var col in colliders)
{ {
@ -1229,10 +1242,16 @@ namespace RacesOfValheim
// kill). ApplyDamage() skipped all of that: it edited the local copy of a // kill). ApplyDamage() skipped all of that: it edited the local copy of a
// character we usually do not own, and the owner overwrote it on the next sync. // character we usually do not own, and the owner overwrote it on the next sync.
c.Damage(hd); c.Damage(hd);
hitCreature = true;
SpawnBloodVFX(c); SpawnBloodVFX(c);
} }
} }
// The aura scales with Blood Magic but called Damage directly, so it never paid
// the skill back. Passive and always on, so it earns what the Skadi's Frost Aura
// does: a tenth of a hit per second of draining, once per tick, not per victim.
if (hitCreature) FormMelee.RaiseSkill(Skills.SkillType.BloodMagic, 0.1f * AswidConfig.AuraTickInterval.Value);
} }
catch (Exception ex) catch (Exception ex)
{ {

Binary file not shown.

Binary file not shown.

View file

@ -363,8 +363,22 @@ namespace RacesOfValheim
Scan(anchor.Value); Scan(anchor.Value);
ExpirePenalties(); ExpirePenalties();
if (m_payload.Count > 0) { m_job = PlanDelivery(anchor.Value); return; } // A delivery gets its own clock like any other job. Returning early here left it with the
// load's deadline: a slow trip, or a fight on the way, made it late before it started, and
// it timed out and was planned again on every tick, frozen with the goods in hand.
Job job;
if (m_payload.Count > 0) job = PlanDelivery(anchor.Value);
else job = PlanWork();
if (job != null && (m_job == null || m_job.Kind != job.Kind || m_job.Target != job.Target))
{
m_jobDeadline = Time.time + JobTimeout;
}
m_job = job;
}
private Job PlanWork()
{
// The forge has no clock: a smelter holds its ore indefinitely and puts its own output on // The forge has no clock: a smelter holds its ore indefinitely and puts its own output on
// the floor, so PlanRescue would ask a question whose answer is always no. The smith is a // the floor, so PlanRescue would ask a question whose answer is always no. The smith is a
// four-state machine and the cook is a five-state one, and that is the whole of the // four-state machine and the cook is a five-state one, and that is the whole of the
@ -376,13 +390,7 @@ namespace RacesOfValheim
// in return, because FuelWanted is zero for a station with no work: an empty furnace asks // in return, because FuelWanted is zero for a station with no work: an empty furnace asks
// for no coal, gets filled, and only then becomes worth stoking. // for no coal, gets filled, and only then becomes worth stoking.
Job job = m_family == ButlerFamily.Kitchen ? PlanRescue() : null; Job job = m_family == ButlerFamily.Kitchen ? PlanRescue() : null;
job = job ?? PlanCollect() ?? PlanFuel() ?? PlanLoad(); return job ?? PlanCollect() ?? PlanFuel() ?? PlanLoad();
if (job != null && (m_job == null || m_job.Kind != job.Kind || m_job.Target != job.Target))
{
m_jobDeadline = Time.time + JobTimeout;
}
m_job = job;
} }
/// <summary> /// <summary>
@ -634,8 +642,10 @@ namespace RacesOfValheim
// coal, so gating the delivery on free slots sent the servant back to the chest with // coal, so gating the delivery on free slots sent the servant back to the chest with
// the coal it had just fetched - and then PlanFuel sent it out for the same coal again, // the coal it had just fetched - and then PlanFuel sent it out for the same coal again,
// forever. AcceptsAnything already asks the right question of both doors. // forever. AcceptsAnything already asks the right question of both doors.
// A station it could not reach is in the penalty box: asking it again straight away
// is the same failed trip.
ButlerStation station = StationById(target); ButlerStation station = StationById(target);
if (station != null && station.Alive && station.Operable && AcceptsAnything(station)) if (station != null && station.Alive && station.Operable && AcceptsAnything(station) && !IsPenalised(target))
{ {
return new Job return new Job
{ {

View file

@ -31,6 +31,8 @@ namespace RacesOfValheim
"Aswid - Eyes", "Aswid - Eyes",
"Fenrir - Appearance", "Fenrir - Appearance",
"Skeleton - Visuals", "Skeleton - Visuals",
// Food and stamina for a Skeleton who wants them: each only gives up an advantage.
"Skeleton - Mortal Habits",
"Sverm - Dorsal Spines", "Sverm - Dorsal Spines",
"Sverm - Emberform", "Sverm - Emberform",
"Trol - Appearance", "Trol - Appearance",

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

View file

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

View file

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

View file

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

View file

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

View file

@ -774,6 +774,7 @@ namespace RacesOfValheim
Collider[] hits = Physics.OverlapSphere(attackPoint, attackRadius, layerMask); Collider[] hits = Physics.OverlapSphere(attackPoint, attackRadius, layerMask);
FormMelee.LogSwing(FormLabel, hits.Length); FormMelee.LogSwing(FormLabel, hits.Length);
System.Collections.Generic.HashSet<GameObject> hitObjects = new System.Collections.Generic.HashSet<GameObject>(); System.Collections.Generic.HashSet<GameObject> hitObjects = new System.Collections.Generic.HashSet<GameObject>();
bool hitCreature = false;
foreach (Collider hit in hits) foreach (Collider hit in hits)
{ {
@ -823,10 +824,13 @@ namespace RacesOfValheim
FormMelee.LogHit(FormLabel, target, totalDamage); FormMelee.LogHit(FormLabel, target, totalDamage);
target.Damage(hitData); target.Damage(hitData);
FormMelee.GrantAdrenaline(target); FormMelee.GrantAdrenaline(target);
if (target is Character) hitCreature = true;
} }
} }
} }
} }
if (hitCreature) FormMelee.RaiseSkill(Skills.SkillType.Unarmed);
} }
} }
@ -1067,6 +1071,7 @@ namespace RacesOfValheim
Collider[] hits = Physics.OverlapSphere(attackPoint, attackRadius, layerMask); Collider[] hits = Physics.OverlapSphere(attackPoint, attackRadius, layerMask);
FormMelee.LogSwing(FormLabel, hits.Length); FormMelee.LogSwing(FormLabel, hits.Length);
System.Collections.Generic.HashSet<GameObject> hitObjects = new System.Collections.Generic.HashSet<GameObject>(); System.Collections.Generic.HashSet<GameObject> hitObjects = new System.Collections.Generic.HashSet<GameObject>();
bool hitCreature = false;
foreach (Collider hit in hits) foreach (Collider hit in hits)
{ {
@ -1106,6 +1111,7 @@ namespace RacesOfValheim
FormMelee.LogHit(FormLabel, target, totalDamage); FormMelee.LogHit(FormLabel, target, totalDamage);
target.Damage(hitData); target.Damage(hitData);
FormMelee.GrantAdrenaline(target, 0.2f); // one 0.2s tick: a full hit per second of breath FormMelee.GrantAdrenaline(target, 0.2f); // one 0.2s tick: a full hit per second of breath
if (target is Character) hitCreature = true;
if (ZNetScene.instance != null) if (ZNetScene.instance != null)
{ {
@ -1115,6 +1121,8 @@ namespace RacesOfValheim
} }
} }
} }
if (hitCreature) FormMelee.RaiseSkill(Skills.SkillType.ElementalMagic, 0.2f); // one 0.2s tick: a full swing's worth per second of breath
} }
private IEnumerator ClawRoutine() private IEnumerator ClawRoutine()
@ -1231,6 +1239,7 @@ namespace RacesOfValheim
Collider[] hits = Physics.OverlapSphere(attackPoint, attackRadius, layerMask); Collider[] hits = Physics.OverlapSphere(attackPoint, attackRadius, layerMask);
FormMelee.LogSwing(FormLabel, hits.Length); FormMelee.LogSwing(FormLabel, hits.Length);
System.Collections.Generic.HashSet<GameObject> hitObjects = new System.Collections.Generic.HashSet<GameObject>(); System.Collections.Generic.HashSet<GameObject> hitObjects = new System.Collections.Generic.HashSet<GameObject>();
bool hitCreature = false;
foreach (Collider hit in hits) foreach (Collider hit in hits)
{ {
@ -1280,10 +1289,13 @@ namespace RacesOfValheim
FormMelee.LogHit(FormLabel, target, totalDamage); FormMelee.LogHit(FormLabel, target, totalDamage);
target.Damage(hitData); target.Damage(hitData);
FormMelee.GrantAdrenaline(target); FormMelee.GrantAdrenaline(target);
if (target is Character) hitCreature = true;
} }
} }
} }
} }
if (hitCreature) FormMelee.RaiseSkill(Skills.SkillType.Unarmed);
} }
} }
@ -1446,6 +1458,7 @@ namespace RacesOfValheim
Collider[] hits = Physics.OverlapSphere(attackPoint, attackRadius, layerMask); Collider[] hits = Physics.OverlapSphere(attackPoint, attackRadius, layerMask);
FormMelee.LogSwing(FormLabel, hits.Length); FormMelee.LogSwing(FormLabel, hits.Length);
System.Collections.Generic.HashSet<GameObject> hitObjects = new System.Collections.Generic.HashSet<GameObject>(); System.Collections.Generic.HashSet<GameObject> hitObjects = new System.Collections.Generic.HashSet<GameObject>();
bool hitCreature = false;
foreach (Collider hit in hits) foreach (Collider hit in hits)
{ {
@ -1495,10 +1508,13 @@ namespace RacesOfValheim
FormMelee.LogHit(FormLabel, target, totalDamage); FormMelee.LogHit(FormLabel, target, totalDamage);
target.Damage(hitData); target.Damage(hitData);
FormMelee.GrantAdrenaline(target); FormMelee.GrantAdrenaline(target);
if (target is Character) hitCreature = true;
} }
} }
} }
} }
if (hitCreature) FormMelee.RaiseSkill(Skills.SkillType.Unarmed);
} }
} }
@ -1654,6 +1670,7 @@ namespace RacesOfValheim
Collider[] hits = Physics.OverlapSphere(attackPoint, attackRadius, layerMask); Collider[] hits = Physics.OverlapSphere(attackPoint, attackRadius, layerMask);
FormMelee.LogSwing(FormLabel, hits.Length); FormMelee.LogSwing(FormLabel, hits.Length);
System.Collections.Generic.HashSet<GameObject> hitObjects = new System.Collections.Generic.HashSet<GameObject>(); System.Collections.Generic.HashSet<GameObject> hitObjects = new System.Collections.Generic.HashSet<GameObject>();
bool hitCreature = false;
foreach (Collider hit in hits) foreach (Collider hit in hits)
{ {
@ -1703,10 +1720,13 @@ namespace RacesOfValheim
FormMelee.LogHit(FormLabel, target, totalDamage); FormMelee.LogHit(FormLabel, target, totalDamage);
target.Damage(hitData); target.Damage(hitData);
FormMelee.GrantAdrenaline(target); FormMelee.GrantAdrenaline(target);
if (target is Character) hitCreature = true;
} }
} }
} }
} }
if (hitCreature) FormMelee.RaiseSkill(Skills.SkillType.Unarmed);
} }
private IEnumerator UlvJumpAttackRoutine() private IEnumerator UlvJumpAttackRoutine()

View file

@ -45,6 +45,9 @@ namespace RacesOfValheim
public static ConfigEntry<float> FullFormJumpBonus; public static ConfigEntry<float> FullFormJumpBonus;
public static ConfigEntry<float> FullFormFallDamageReduction; public static ConfigEntry<float> FullFormFallDamageReduction;
public static ConfigEntry<float> WolfFormSpeedBonus; public static ConfigEntry<float> WolfFormSpeedBonus;
public static ConfigEntry<float> UlvFormSpeedBonus;
public static ConfigEntry<float> FenringDamageReduction;
public static ConfigEntry<float> CultistExtraDamageTaken;
public static ConfigEntry<float> WolfFormFallDamageReduction; public static ConfigEntry<float> WolfFormFallDamageReduction;
public static ConfigEntry<float> FormStaminaRegenMultiplier; public static ConfigEntry<float> FormStaminaRegenMultiplier;
public static ConfigEntry<float> FormStaminaDrainReduction; public static ConfigEntry<float> FormStaminaDrainReduction;
@ -97,9 +100,6 @@ namespace RacesOfValheim
public static ConfigEntry<float> UlvAttackRadius; public static ConfigEntry<float> UlvAttackRadius;
public static ConfigEntry<float> UlvPushForce; public static ConfigEntry<float> UlvPushForce;
// ─── Debug ─────────────────────────────────────────────────────────────
public static ConfigEntry<bool> DebugFormHits;
// ─── Appearance (per player, never synced) ────────────────────────────── // ─── Appearance (per player, never synced) ──────────────────────────────
public static ConfigEntry<bool> ReadyMessage; public static ConfigEntry<bool> ReadyMessage;
public static ConfigEntry<bool> EyeGlow; public static ConfigEntry<bool> EyeGlow;
@ -138,14 +138,24 @@ namespace RacesOfValheim
const string buffs = "Fenrir - Form Buffs"; const string buffs = "Fenrir - Form Buffs";
BindNote(config, buffs, "Note: these values need a relog to take effect."); BindNote(config, buffs, "Note: these values need a relog to take effect.");
FullFormSpeedBonus = config.Bind(buffs, "Full Form Speed Bonus", 1.0f, // Each form has a job once all three are unlocked (Lexsonn's suggestion): the Ulv
new ConfigDescription("Speed multiplier bonus while in Fenring or Cultist form.", new AcceptableValueRange<float>(0f, 3f))); // travels, the Fenring holds the line, the Cultist burns. The speed keys were renamed
// from "Full Form Speed Bonus" and "Wolf Form Speed Bonus" so a saved .cfg cannot keep
// the old order, where the Fenring outran the Ulv.
FullFormSpeedBonus = config.Bind(buffs, "Fenring And Cultist Speed Bonus", 0.5f,
new ConfigDescription("Speed multiplier bonus while in Fenring or Cultist form. 0.5 = 50% faster.", new AcceptableValueRange<float>(0f, 3f)));
FullFormJumpBonus = config.Bind(buffs, "Full Form Jump Bonus", 1.0f, FullFormJumpBonus = config.Bind(buffs, "Full Form Jump Bonus", 1.0f,
new ConfigDescription("Jump multiplier bonus while in Fenring or Cultist form.", new AcceptableValueRange<float>(0f, 3f))); new ConfigDescription("Jump multiplier bonus while in Fenring or Cultist form.", new AcceptableValueRange<float>(0f, 3f)));
FullFormFallDamageReduction = config.Bind(buffs, "Full Form Fall Damage Reduction", 1.0f, FullFormFallDamageReduction = config.Bind(buffs, "Full Form Fall Damage Reduction", 1.0f,
new ConfigDescription("Fall damage reduction while in Fenring or Cultist form (1 = immune).", new AcceptableValueRange<float>(0f, 1f))); new ConfigDescription("Fall damage reduction while in Fenring or Cultist form (1 = immune).", new AcceptableValueRange<float>(0f, 1f)));
WolfFormSpeedBonus = config.Bind(buffs, "Wolf Form Speed Bonus", 0.5f, WolfFormSpeedBonus = config.Bind(buffs, "Wolf Speed Bonus", 0.5f,
new ConfigDescription("Speed multiplier bonus while in Wolf or Ulv form.", new AcceptableValueRange<float>(0f, 3f))); new ConfigDescription("Speed multiplier bonus while in Wolf form, the G form before Moder.", new AcceptableValueRange<float>(0f, 3f)));
UlvFormSpeedBonus = config.Bind(buffs, "Ulv Speed Bonus", 1.0f,
new ConfigDescription("Speed multiplier bonus while in Ulv form. The fastest form by default: the one to travel in.", new AcceptableValueRange<float>(0f, 3f)));
FenringDamageReduction = config.Bind(buffs, "Fenring Damage Reduction", 0.3f,
new ConfigDescription("Share of every hit the Fenring shrugs off. 0.3 = 30% less damage taken.", new AcceptableValueRange<float>(0f, 0.9f)));
CultistExtraDamageTaken = config.Bind(buffs, "Cultist Extra Damage Taken", 0.25f,
new ConfigDescription("How much harder hits land on the Cultist. 0.25 = 25% more damage taken.", new AcceptableValueRange<float>(0f, 2f)));
WolfFormFallDamageReduction = config.Bind(buffs, "Wolf Form Fall Damage Reduction", 0.5f, WolfFormFallDamageReduction = config.Bind(buffs, "Wolf Form Fall Damage Reduction", 0.5f,
new ConfigDescription("Fall damage reduction while in Wolf or Ulv form.", new AcceptableValueRange<float>(0f, 1f))); new ConfigDescription("Fall damage reduction while in Wolf or Ulv form.", new AcceptableValueRange<float>(0f, 1f)));
FormStaminaRegenMultiplier = config.Bind(buffs, "Stamina Regen Multiplier", 1.3f, FormStaminaRegenMultiplier = config.Bind(buffs, "Stamina Regen Multiplier", 1.3f,
@ -255,10 +265,6 @@ namespace RacesOfValheim
// Tried at 1.2 in game: the orange was too strong. 0.9 checked and kept. // Tried at 1.2 in game: the orange was too strong. 0.9 checked and kept.
EyeReadyStrength = config.Bind(appearance, "Eye Ready Strength", 0.9f, EyeReadyStrength = config.Bind(appearance, "Eye Ready Strength", 0.9f,
new ConfigDescription("Glow at night while a form is ready.", new AcceptableValueRange<float>(0f, 3f))); new ConfigDescription("Glow at night while a form is ready.", new AcceptableValueRange<float>(0f, 3f)));
// "debug" in the key keeps it local - see ConfigSync.
DebugFormHits = config.Bind("Fenrir - Debug", "Debug: Log Form Hits", false,
new ConfigDescription("Writes one log line per claw or bite: what was in reach, what it hit, and why anything was skipped. For bug reports about attacks that do no damage."));
} }
/// <summary> /// <summary>

View file

@ -342,7 +342,7 @@ namespace RacesOfValheim
/// </summary> /// </summary>
public static void LogMiss(string form, Collider hit, string reason) public static void LogMiss(string form, Collider hit, string reason)
{ {
if (!FenrirConfig.DebugFormHits.Value) return; if (!DebugConfig.LogFormHits.Value) return;
Jotunn.Logger.LogInfo($"[FenrirForm] {form} swing skipped '{hit.name}' (layer {LayerMask.LayerToName(hit.gameObject.layer)}): {reason}."); Jotunn.Logger.LogInfo($"[FenrirForm] {form} swing skipped '{hit.name}' (layer {LayerMask.LayerToName(hit.gameObject.layer)}): {reason}.");
} }
@ -368,6 +368,21 @@ namespace RacesOfValheim
player.AddAdrenaline(perHit * character.m_enemyAdrenalineMultiplier * scale); player.AddAdrenaline(perHit * character.m_enemyAdrenalineMultiplier * scale);
} }
/// <summary>
/// The skill experience vanilla gives for a weapon hit, which a hand-built hit never got.
/// Vanilla raises the skill inside Attack (once per swing that landed on a creature) and
/// inside Projectile.OnHit; Character.Damage never does, so a form that calls Damage
/// directly left its skill at whatever level the player brought in. Call it once per
/// swing or tick, after the loop, never once per target. amount lets a damage-over-time
/// tick pay a fraction of a swing.
/// </summary>
public static void RaiseSkill(Skills.SkillType skill, float amount = 1f)
{
Player player = Player.m_localPlayer;
if (player == null || amount <= 0f) return;
player.RaiseSkill(skill, amount);
}
/// <summary> /// <summary>
/// Charges a form attack's stamina the way vanilla charges a weapon's (Attack.GetAttackStamina): /// Charges a form attack's stamina the way vanilla charges a weapon's (Attack.GetAttackStamina):
/// the equipment modifier, status effects (meads, race passives), then up to a third off with /// the equipment modifier, status effects (meads, race passives), then up to a third off with
@ -398,16 +413,37 @@ namespace RacesOfValheim
return true; return true;
} }
private static readonly System.Collections.Generic.Dictionary<string, ItemDrop.ItemData.SharedData> weapons =
new System.Collections.Generic.Dictionary<string, ItemDrop.ItemData.SharedData>();
/// <summary>
/// A creature's own attack item (dragon_bite, SeekerBrute_ram...), read once and cached,
/// null if the game has none by that name. A hand-built swing skips Attack, and Attack is
/// where vanilla plays the item's m_triggerEffect and m_hitEffect, so a form that wants the
/// creature's real swing and impact sounds plays them from here.
/// </summary>
public static ItemDrop.ItemData.SharedData CreatureWeapon(string prefabName)
{
if (string.IsNullOrEmpty(prefabName)) return null;
if (weapons.TryGetValue(prefabName, out ItemDrop.ItemData.SharedData cached)) return cached;
GameObject prefab = Jotunn.Managers.PrefabManager.Cache.GetPrefab<GameObject>(prefabName);
ItemDrop.ItemData.SharedData shared = prefab != null ? prefab.GetComponent<ItemDrop>()?.m_itemData?.m_shared : null;
if (shared == null) Jotunn.Logger.LogWarning($"[FormMelee] No attack item '{prefabName}'; that swing stays silent.");
weapons[prefabName] = shared;
return shared;
}
public static void LogHit(string form, IDestructible target, float damage) public static void LogHit(string form, IDestructible target, float damage)
{ {
if (!FenrirConfig.DebugFormHits.Value) return; if (!DebugConfig.LogFormHits.Value) return;
string name = target is MonoBehaviour behaviour && behaviour != null ? behaviour.name : target.ToString(); string name = target is MonoBehaviour behaviour && behaviour != null ? behaviour.name : target.ToString();
Jotunn.Logger.LogInfo($"[FenrirForm] {form} swing hit '{name}' for {damage:0}."); Jotunn.Logger.LogInfo($"[FenrirForm] {form} swing hit '{name}' for {damage:0}.");
} }
public static void LogSwing(string form, int candidates) public static void LogSwing(string form, int candidates)
{ {
if (!FenrirConfig.DebugFormHits.Value) return; if (!DebugConfig.LogFormHits.Value) return;
Jotunn.Logger.LogInfo($"[FenrirForm] {form} swing: {candidates} collider(s) in reach."); Jotunn.Logger.LogInfo($"[FenrirForm] {form} swing: {candidates} collider(s) in reach.");
} }
} }

View file

@ -76,7 +76,7 @@ namespace RacesOfValheim {
cultistCdSE.m_icon = fenringTrophyIcon; cultistCdSE.m_icon = fenringTrophyIcon;
ItemManager.Instance.AddStatusEffect(new CustomStatusEffect(cultistCdSE, fixReference: false)); ItemManager.Instance.AddStatusEffect(new CustomStatusEffect(cultistCdSE, fixReference: false));
formBuffSE = ScriptableObject.CreateInstance<SE_Stats>(); formBuffSE = ScriptableObject.CreateInstance<SE_FenrirFormBuff>();
formBuffSE.name = "SE_FenrirForm"; formBuffSE.name = "SE_FenrirForm";
formBuffSE.m_name = "$rov_se_fenrir_form_name"; formBuffSE.m_name = "$rov_se_fenrir_form_name";
formBuffSE.m_speedModifier = FenrirConfig.FullFormSpeedBonus.Value; formBuffSE.m_speedModifier = FenrirConfig.FullFormSpeedBonus.Value;
@ -87,7 +87,7 @@ namespace RacesOfValheim {
formBuffSE.m_icon = fenringTrophyIcon; formBuffSE.m_icon = fenringTrophyIcon;
ItemManager.Instance.AddStatusEffect(new CustomStatusEffect(formBuffSE, fixReference: false)); ItemManager.Instance.AddStatusEffect(new CustomStatusEffect(formBuffSE, fixReference: false));
cultistFormBuffSE = ScriptableObject.CreateInstance<SE_Stats>(); cultistFormBuffSE = ScriptableObject.CreateInstance<SE_FenrirFormBuff>();
cultistFormBuffSE.name = "SE_CultistForm"; cultistFormBuffSE.name = "SE_CultistForm";
cultistFormBuffSE.m_name = "$rov_se_fenrir_cultistform_name"; cultistFormBuffSE.m_name = "$rov_se_fenrir_cultistform_name";
cultistFormBuffSE.m_speedModifier = FenrirConfig.FullFormSpeedBonus.Value; cultistFormBuffSE.m_speedModifier = FenrirConfig.FullFormSpeedBonus.Value;
@ -98,7 +98,7 @@ namespace RacesOfValheim {
cultistFormBuffSE.m_icon = fenringTrophyIcon; cultistFormBuffSE.m_icon = fenringTrophyIcon;
ItemManager.Instance.AddStatusEffect(new CustomStatusEffect(cultistFormBuffSE, fixReference: false)); ItemManager.Instance.AddStatusEffect(new CustomStatusEffect(cultistFormBuffSE, fixReference: false));
wolfFormBuffSE = ScriptableObject.CreateInstance<SE_Stats>(); wolfFormBuffSE = ScriptableObject.CreateInstance<SE_FenrirFormBuff>();
wolfFormBuffSE.name = "SE_WolfForm"; wolfFormBuffSE.name = "SE_WolfForm";
wolfFormBuffSE.m_name = "$rov_se_fenrir_wolfform_name"; wolfFormBuffSE.m_name = "$rov_se_fenrir_wolfform_name";
wolfFormBuffSE.m_speedModifier = FenrirConfig.WolfFormSpeedBonus.Value; wolfFormBuffSE.m_speedModifier = FenrirConfig.WolfFormSpeedBonus.Value;
@ -109,6 +109,16 @@ namespace RacesOfValheim {
ItemManager.Instance.AddStatusEffect(new CustomStatusEffect(wolfFormBuffSE, fixReference: false)); ItemManager.Instance.AddStatusEffect(new CustomStatusEffect(wolfFormBuffSE, fixReference: false));
} }
// Set on the live copy each time a form is taken, not on the registered template: the Wolf
// and the Ulv share SE_WolfForm but not a speed, and a changed value applies at the next
// transform instead of after a relog.
private static void SetFormBuff(StatusEffect se, float speedBonus, float damageTakenFactor)
{
if (!(se is SE_FenrirFormBuff buff)) return;
buff.m_speedModifier = speedBonus;
buff.m_damageTakenFactor = damageTakenFactor;
}
private void Update() private void Update()
{ {
if (Player.m_localPlayer == null || EnvMan.instance == null) return; if (Player.m_localPlayer == null || EnvMan.instance == null) return;
@ -550,6 +560,7 @@ namespace RacesOfValheim {
Player.m_localPlayer.GetSEMan().AddStatusEffect("SE_WolfForm".GetStableHashCode(), true); Player.m_localPlayer.GetSEMan().AddStatusEffect("SE_WolfForm".GetStableHashCode(), true);
var se = Player.m_localPlayer.GetSEMan().GetStatusEffect("SE_WolfForm".GetStableHashCode()); var se = Player.m_localPlayer.GetSEMan().GetStatusEffect("SE_WolfForm".GetStableHashCode());
if (se != null) se.m_ttl = ttl; if (se != null) se.m_ttl = ttl;
SetFormBuff(se, FenrirConfig.UlvFormSpeedBonus.Value, 1f);
Player.m_localPlayer.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_fenrir_are_ulv")); Player.m_localPlayer.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_fenrir_are_ulv"));
} }
else if (prefabName == "Wolf") else if (prefabName == "Wolf")
@ -558,6 +569,7 @@ namespace RacesOfValheim {
Player.m_localPlayer.GetSEMan().AddStatusEffect("SE_WolfForm".GetStableHashCode(), true); Player.m_localPlayer.GetSEMan().AddStatusEffect("SE_WolfForm".GetStableHashCode(), true);
var se = Player.m_localPlayer.GetSEMan().GetStatusEffect("SE_WolfForm".GetStableHashCode()); var se = Player.m_localPlayer.GetSEMan().GetStatusEffect("SE_WolfForm".GetStableHashCode());
if (se != null) se.m_ttl = ttl; if (se != null) se.m_ttl = ttl;
SetFormBuff(se, FenrirConfig.WolfFormSpeedBonus.Value, 1f);
Player.m_localPlayer.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_fenrir_are_wolf")); Player.m_localPlayer.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_fenrir_are_wolf"));
} }
else if (prefabName == "Fenring_Cultist") else if (prefabName == "Fenring_Cultist")
@ -566,6 +578,7 @@ namespace RacesOfValheim {
Player.m_localPlayer.GetSEMan().AddStatusEffect("SE_CultistForm".GetStableHashCode(), true); Player.m_localPlayer.GetSEMan().AddStatusEffect("SE_CultistForm".GetStableHashCode(), true);
var se = Player.m_localPlayer.GetSEMan().GetStatusEffect("SE_CultistForm".GetStableHashCode()); var se = Player.m_localPlayer.GetSEMan().GetStatusEffect("SE_CultistForm".GetStableHashCode());
if (se != null) se.m_ttl = ttl; if (se != null) se.m_ttl = ttl;
SetFormBuff(se, FenrirConfig.FullFormSpeedBonus.Value, 1f + FenrirConfig.CultistExtraDamageTaken.Value);
Player.m_localPlayer.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_fenrir_are_cultist")); Player.m_localPlayer.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_fenrir_are_cultist"));
} }
else else
@ -574,6 +587,7 @@ namespace RacesOfValheim {
Player.m_localPlayer.GetSEMan().AddStatusEffect("SE_FenrirForm".GetStableHashCode(), true); Player.m_localPlayer.GetSEMan().AddStatusEffect("SE_FenrirForm".GetStableHashCode(), true);
var se = Player.m_localPlayer.GetSEMan().GetStatusEffect("SE_FenrirForm".GetStableHashCode()); var se = Player.m_localPlayer.GetSEMan().GetStatusEffect("SE_FenrirForm".GetStableHashCode());
if (se != null) se.m_ttl = ttl; if (se != null) se.m_ttl = ttl;
SetFormBuff(se, FenrirConfig.FullFormSpeedBonus.Value, 1f - FenrirConfig.FenringDamageReduction.Value);
Player.m_localPlayer.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_fenrir_are_fenring")); Player.m_localPlayer.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_fenrir_are_fenring"));
} }

View file

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

View file

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

View file

@ -725,7 +725,18 @@ namespace RacesOfValheim
sb.AppendLine((state <= BossProgressionManager.MinState ? ModText.Get("rov_compendium_skeleton_stand_at_first_eight_standings") : ModText.Get("rov_compendium_skeleton_stand_at_eight_standings_earned", state, BossProgressionManager.GetBossTokenForState(state)))); sb.AppendLine((state <= BossProgressionManager.MinState ? ModText.Get("rov_compendium_skeleton_stand_at_first_eight_standings") : ModText.Get("rov_compendium_skeleton_stand_at_eight_standings_earned", state, BossProgressionManager.GetBossTokenForState(state))));
sb.AppendLine(ModText.Get("rov_compendium_skeleton_undead_diet")); sb.AppendLine(ModText.Get("rov_compendium_skeleton_undead_diet"));
bool eats = SkeletonConfig.EatsMortalFood.Value, tires = SkeletonConfig.FeelsFatigue.Value;
if (!eats && !tires)
{
sb.AppendLine(ModText.Get("rov_compendium_skeleton_no_hunger_moves_no_meal", (health).ToString("0"))); sb.AppendLine(ModText.Get("rov_compendium_skeleton_no_hunger_moves_no_meal", (health).ToString("0")));
}
else
{
// A player who picked one of the "Mortal Habits" reads what they actually have.
string diet = eats ? ModText.Get("rov_compendium_skeleton_diet_mortal") : ModText.Get("rov_compendium_skeleton_diet_bones", (health).ToString("0"));
string effort = tires ? ModText.Get("rov_compendium_skeleton_effort_mortal") : ModText.Get("rov_compendium_skeleton_effort_none");
sb.AppendLine(diet + " " + effort + "\n");
}
sb.AppendLine(ModText.Get("rov_compendium_skeleton_bones_blades")); sb.AppendLine(ModText.Get("rov_compendium_skeleton_bones_blades"));
sb.AppendLine(ModText.Get("rov_compendium_skeleton_blades_points_find_little_cut")); sb.AppendLine(ModText.Get("rov_compendium_skeleton_blades_points_find_little_cut"));
@ -863,8 +874,8 @@ namespace RacesOfValheim
int foodDuration = Mathf.RoundToInt(TrentaConfig.FoodDurationMultiplier); int foodDuration = Mathf.RoundToInt(TrentaConfig.FoodDurationMultiplier);
int purpleRainRadius = Mathf.RoundToInt(TrentaConfig.PurpleRainRadius); int purpleRainRadius = Mathf.RoundToInt(TrentaConfig.PurpleRainRadius);
int purpleRainHeal = Mathf.RoundToInt(TrentaConfig.PurpleRainHealAmount); int purpleRainHeal = Mathf.RoundToInt(TrentaConfig.PurpleRainHealFor(Player.m_localPlayer));
int purpleRainPoison = Mathf.RoundToInt(TrentaConfig.PurpleRainPoisonDamage); int purpleRainPoison = Mathf.RoundToInt(TrentaConfig.PurpleRainPoisonFor(Player.m_localPlayer));
int purpleRainCooldown = Mathf.RoundToInt(TrentaConfigManagement.PurpleRainCooldown.Value); int purpleRainCooldown = Mathf.RoundToInt(TrentaConfigManagement.PurpleRainCooldown.Value);
int purpleRainMuspellCooldown = Mathf.RoundToInt(TrentaConfigManagement.MuspellPurpleRainCooldown.Value); int purpleRainMuspellCooldown = Mathf.RoundToInt(TrentaConfigManagement.MuspellPurpleRainCooldown.Value);

View file

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

View file

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

View file

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

View file

@ -16,7 +16,7 @@ namespace RacesOfValheim
{ {
public const string PluginGUID = "com.nandor.racesofvalheim"; public const string PluginGUID = "com.nandor.racesofvalheim";
public const string PluginName = "Races Of Valheim"; public const string PluginName = "Races Of Valheim";
public const string PluginVersion = "1.6.5"; public const string PluginVersion = "1.6.11";
private readonly Harmony harmony = new Harmony(PluginGUID); private readonly Harmony harmony = new Harmony(PluginGUID);
@ -57,6 +57,8 @@ namespace RacesOfValheim
// Not a race either: the faction truce and the faction merchants, which cut across // Not a race either: the faction truce and the faction merchants, which cut across
// every race at once, so they bind last rather than inside the alphabetical run above. // every race at once, so they bind last rather than inside the alphabetical run above.
FactionsConfig.Bind(Config); FactionsConfig.Bind(Config);
// The mod-wide debug switches, at the bottom of the list on purpose.
DebugConfig.Bind(Config);
// After every Bind above: tags the gameplay entries for Jotunn's server-to-client sync. // After every Bind above: tags the gameplay entries for Jotunn's server-to-client sync.
ConfigSync.Apply(Config); ConfigSync.Apply(Config);
harmony.PatchAll(); harmony.PatchAll();
@ -76,6 +78,9 @@ namespace RacesOfValheim
PrefabManager.OnVanillaPrefabsAvailable += CreateAllModAssets; PrefabManager.OnVanillaPrefabsAvailable += CreateAllModAssets;
CommandManager.Instance.AddConsoleCommand(new ResetRaceCommand()); CommandManager.Instance.AddConsoleCommand(new ResetRaceCommand());
CommandManager.Instance.AddConsoleCommand(new CheckProgressionCommand()); CommandManager.Instance.AddConsoleCommand(new CheckProgressionCommand());
CommandManager.Instance.AddConsoleCommand(new TrolSoundCommand("rovsnd1", TrolSounds.Death));
CommandManager.Instance.AddConsoleCommand(new TrolSoundCommand("rovsnd2", TrolSounds.Building));
StartCoroutine(TrolSounds.Load());
CommandManager.Instance.AddConsoleCommand(new IncreaseProgressionCommand()); CommandManager.Instance.AddConsoleCommand(new IncreaseProgressionCommand());
CommandManager.Instance.AddConsoleCommand(new ResetProgressionCommand()); CommandManager.Instance.AddConsoleCommand(new ResetProgressionCommand());
CommandManager.Instance.AddConsoleCommand(new DumpDvergerCommand()); CommandManager.Instance.AddConsoleCommand(new DumpDvergerCommand());

View file

@ -57,6 +57,7 @@
manager has no extra folder to flatten. Loaded by name: PieceLook.LoadTexture("CookCloth_d.png"). --> manager has no extra folder to flatten. Loaded by name: PieceLook.LoadTexture("CookCloth_d.png"). -->
<ItemGroup> <ItemGroup>
<EmbeddedResource Include="Assets\**\*.png" LogicalName="%(Filename)%(Extension)" /> <EmbeddedResource Include="Assets\**\*.png" LogicalName="%(Filename)%(Extension)" />
<EmbeddedResource Include="Audio\*.ogg" LogicalName="%(Filename)%(Extension)" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>

View file

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

View file

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

View file

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

View file

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

View file

@ -79,11 +79,11 @@ namespace RacesOfValheim
// drake one used for the passive blessing. // drake one used for the passive blessing.
Sprite dragonIcon = GetItemIcon("TrophyDragonQueen") ?? GetItemIcon("TrophyHatchling"); Sprite dragonIcon = GetItemIcon("TrophyDragonQueen") ?? GetItemIcon("TrophyHatchling");
skadiCdSE = ScriptableObject.CreateInstance<SE_FormCooldown>(); // One cooldown per form, so a Drake cooldown set in the config never holds the Moder
skadiCdSE.name = "SE_SkadiCooldown"; // back, nor the other way round. The Moder keeps the original name.
skadiCdSE.m_name = "$rov_se_skadi_formcd_name"; skadiCdSE = RegisterFormCooldown(SkadiProgression.FormType.Moder, "$rov_se_skadi_formcd_name", dragonIcon);
skadiCdSE.m_icon = dragonIcon; RegisterFormCooldown(SkadiProgression.FormType.Drake, "$rov_se_skadi_drakecd_name", GetItemIcon("TrophyHatchling") ?? dragonIcon);
ItemManager.Instance.AddStatusEffect(new CustomStatusEffect(skadiCdSE, fixReference: false)); RegisterFormCooldown(SkadiProgression.FormType.SkeletonDragon, "$rov_se_skadi_fadercd_name", GetItemIcon("TrophyFader") ?? dragonIcon);
skadiFormSE = ScriptableObject.CreateInstance<SE_SkadiForm>(); skadiFormSE = ScriptableObject.CreateInstance<SE_SkadiForm>();
skadiFormSE.name = "SE_SkadiForm"; skadiFormSE.name = "SE_SkadiForm";
@ -124,6 +124,26 @@ namespace RacesOfValheim
if (se != null) se.m_ttl = seconds; if (se != null) se.m_ttl = seconds;
} }
private static SE_FormCooldown RegisterFormCooldown(SkadiProgression.FormType form, string displayName, Sprite icon)
{
SE_FormCooldown cd = ScriptableObject.CreateInstance<SE_FormCooldown>();
cd.name = CooldownSEName(form);
cd.m_name = displayName;
cd.m_icon = icon;
ItemManager.Instance.AddStatusEffect(new CustomStatusEffect(cd, fixReference: false));
return cd;
}
private static string CooldownSEName(SkadiProgression.FormType form)
{
switch (form)
{
case SkadiProgression.FormType.Drake: return "SE_SkadiCooldown_Drake";
case SkadiProgression.FormType.SkeletonDragon: return "SE_SkadiCooldown_Fader";
default: return "SE_SkadiCooldown";
}
}
private static Sprite GetItemIcon(string prefabName) private static Sprite GetItemIcon(string prefabName)
{ {
GameObject trophy = PrefabManager.Cache.GetPrefab<ItemDrop>(prefabName)?.gameObject; GameObject trophy = PrefabManager.Cache.GetPrefab<ItemDrop>(prefabName)?.gameObject;
@ -687,7 +707,7 @@ namespace RacesOfValheim
if (rules.CooldownMinutes > 0) if (rules.CooldownMinutes > 0)
{ {
var cdSE = Player.m_localPlayer.GetSEMan().GetStatusEffect("SE_SkadiCooldown".GetStableHashCode()); var cdSE = Player.m_localPlayer.GetSEMan().GetStatusEffect(CooldownSEName(rules.Form).GetStableHashCode());
if (cdSE != null) if (cdSE != null)
{ {
float m_time = HarmonyLib.Traverse.Create(cdSE).Field<float>("m_time").Value; float m_time = HarmonyLib.Traverse.Create(cdSE).Field<float>("m_time").Value;
@ -983,8 +1003,9 @@ namespace RacesOfValheim
if (activeRules != null && activeRules.CooldownMinutes > 0) if (activeRules != null && activeRules.CooldownMinutes > 0)
{ {
Player.m_localPlayer.GetSEMan().AddStatusEffect("SE_SkadiCooldown".GetStableHashCode(), true); int cdHash = CooldownSEName(activeRules.Form).GetStableHashCode();
var cdSE = Player.m_localPlayer.GetSEMan().GetStatusEffect("SE_SkadiCooldown".GetStableHashCode()); Player.m_localPlayer.GetSEMan().AddStatusEffect(cdHash, true);
var cdSE = Player.m_localPlayer.GetSEMan().GetStatusEffect(cdHash);
if (cdSE != null) cdSE.m_ttl = activeRules.CooldownMinutes * 60f; if (cdSE != null) cdSE.m_ttl = activeRules.CooldownMinutes * 60f;
} }
activeRules = null; activeRules = null;

View file

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

View file

@ -44,16 +44,26 @@ namespace RacesOfValheim
/// GetTotalFoodValue has exactly one caller, Player.UpdateFood, which passes the result /// GetTotalFoodValue has exactly one caller, Player.UpdateFood, which passes the result
/// straight to SetMaxHealth - so this is the single point where the number is decided, and /// straight to SetMaxHealth - so this is the single point where the number is decided, and
/// it now comes from the progression table rather than from three scaled sausages. /// it now comes from the progression table rather than from three scaled sausages.
///
/// A Skeleton with "Eats Mortal Food" is left to vanilla: its real meals decide both
/// numbers, and the tier's health, which stands in for those meals, does not stack on top.
/// One with "Feels Fatigue" who does not eat gets the stand-in meals' stamina, which the
/// fake foods themselves never deliver.
/// </summary> /// </summary>
[HarmonyPatch(typeof(Player), "GetTotalFoodValue")] [HarmonyPatch(typeof(Player), "GetTotalFoodValue")]
public static class Player_GetTotalFoodValue_SkeletonHealth_Patch public static class Player_GetTotalFoodValue_SkeletonHealth_Patch
{ {
public static void Postfix(Player __instance, ref float hp) public static void Postfix(Player __instance, ref float hp, ref float stamina)
{ {
if (__instance != Player.m_localPlayer || !SkeletonRace.IsSkeleton()) return; if (__instance != Player.m_localPlayer || !SkeletonRace.IsSkeleton()) return;
if (SkeletonConfig.EatsMortalFood.Value) return;
int state = BossProgressionManager.GetCurrentProgressionState(); int state = BossProgressionManager.GetCurrentProgressionState();
hp = __instance.m_baseHP + SkeletonProgression.GetMaxHealthBonus(state); hp = __instance.m_baseHP + SkeletonProgression.GetMaxHealthBonus(state);
if (SkeletonConfig.FeelsFatigue.Value)
{
stamina = __instance.m_baseStamina + SkeletonRace.GetStandInStamina(state);
}
} }
} }
@ -63,7 +73,7 @@ namespace RacesOfValheim
public static bool Prefix(Player __instance) public static bool Prefix(Player __instance)
{ {
// The Aswid used to be on this list. It spends stamina now, see Aswid_UseStamina_Patch. // The Aswid used to be on this list. It spends stamina now, see Aswid_UseStamina_Patch.
if ((SkeletonRace.IsSkeleton() || DraughRace.IsDraugh()) && __instance == Player.m_localPlayer) if (((SkeletonRace.IsSkeleton() && !SkeletonConfig.FeelsFatigue.Value) || DraughRace.IsDraugh()) && __instance == Player.m_localPlayer)
{ {
// Infinite stamina: skip the original UseStamina method // Infinite stamina: skip the original UseStamina method
return false; return false;
@ -79,7 +89,7 @@ namespace RacesOfValheim
{ {
if (__instance == Player.m_localPlayer) if (__instance == Player.m_localPlayer)
{ {
if (SkeletonRace.IsSkeleton() && item.m_shared.m_itemType == ItemDrop.ItemData.ItemType.Consumable && (item.m_shared.m_food > 0 || item.m_shared.m_foodStamina > 0 || item.m_shared.m_foodEitr > 0)) if (SkeletonRace.IsSkeleton() && !SkeletonConfig.EatsMortalFood.Value && item.m_shared.m_itemType == ItemDrop.ItemData.ItemType.Consumable && (item.m_shared.m_food > 0 || item.m_shared.m_foodStamina > 0 || item.m_shared.m_foodEitr > 0))
{ {
__instance.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_skeleton_skeletons_do_not_need_eat")); __instance.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_skeleton_skeletons_do_not_need_eat"));
__result = false; __result = false;
@ -194,7 +204,7 @@ namespace RacesOfValheim
{ {
try try
{ {
if (player == Player.m_localPlayer && SkeletonRace.IsSkeleton()) if (player == Player.m_localPlayer && SkeletonRace.IsSkeleton() && !SkeletonConfig.EatsMortalFood.Value)
{ {
if (__instance.m_foodBarRoot != null && __instance.m_foodBarRoot.gameObject.activeSelf) if (__instance.m_foodBarRoot != null && __instance.m_foodBarRoot.gameObject.activeSelf)
{ {
@ -233,7 +243,7 @@ namespace RacesOfValheim
} }
catch (System.Exception e) catch (System.Exception e)
{ {
if (player == Player.m_localPlayer && SkeletonRace.IsSkeleton()) return false; if (player == Player.m_localPlayer && SkeletonRace.IsSkeleton() && !SkeletonConfig.EatsMortalFood.Value) return false;
return true; return true;
} }
} }
@ -862,6 +872,10 @@ namespace RacesOfValheim
if (name == "skeleton" || if (name == "skeleton" ||
name == "skeleton_noarcher" || name == "skeleton_noarcher" ||
name == "skeleton_poison" || name == "skeleton_poison" ||
name == "skeleton_meadows" || name == "skeleton_meadows_noarcher" ||
name == "skeleton_swamps" || name == "skeleton_swamps_noarcher" ||
name == "skeleton_mountains" || name == "skeleton_mountains_noarcher" ||
name == "skeleton_deepnorth" ||
name == "skeleton_friendly" || name == "skeleton_friendly" ||
name.StartsWith("draugr") || name.StartsWith("draugr") ||
name == "ghost" || name == "ghost" ||

View file

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

View file

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

View file

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

View file

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

View file

@ -86,14 +86,14 @@
"rov_compendium_dvergar_weapon_crossbow": "Crossbow", "rov_compendium_dvergar_weapon_crossbow": "Crossbow",
"rov_compendium_dvergar_weapon_hammer": "Hammer", "rov_compendium_dvergar_weapon_hammer": "Hammer",
"rov_compendium_fenrir_beast_within_physical_stats_scale": "[Base Passive] The Beast Within: Your physical stats scale with every boss you defeat: +$1 Armor, +$2 Damage, +$3% Speed, +$4% Jump, and -$5% Fall Damage.\n", "rov_compendium_fenrir_beast_within_physical_stats_scale": "[Base Passive] The Beast Within: Your physical stats scale with every boss you defeat: +$1 Armor, +$2 Damage, +$3% Speed, +$4% Jump, and -$5% Fall Damage.\n",
"rov_compendium_fenrir_cultist_form_j_key_night": "[Yagluth Unlock] Cultist Form ('J' Key, night only): A robed shape that claws and channels fire. Lasts 1 minute, 10-minute cooldown.\n", "rov_compendium_fenrir_cultist_form_j_key_night": "[Yagluth Unlock] Cultist Form ('J' Key, night only): A robed shape that claws and channels fire, and pays for it: every hit on it lands 25% harder. Lasts 1 minute, 10-minute cooldown.\n",
"rov_compendium_fenrir_cultist_form_now_answers_by": "[Fader Unlock] Cultist Form now answers by day as well as night, and may be held as long as you wish.\n", "rov_compendium_fenrir_cultist_form_now_answers_by": "[Fader Unlock] Cultist Form now answers by day as well as night, and may be held as long as you wish.\n",
"rov_compendium_fenrir_cultist_form_s_cooldown_falls": "[The Queen Unlock] Cultist Form's cooldown falls to 5 minutes (still night only, still 1 minute).\n", "rov_compendium_fenrir_cultist_form_s_cooldown_falls": "[The Queen Unlock] Cultist Form's cooldown falls to 5 minutes (still night only, still 1 minute).\n",
"rov_compendium_fenrir_curse_pack": "The Curse of the Pack\n", "rov_compendium_fenrir_curse_pack": "The Curse of the Pack\n",
"rov_compendium_fenrir_cursed_claws_s_wolf_s": "[Base Passive] Cursed Claws ([K], $1s): The wolf's hands, kept on in the man's shape for a limited time instead of a weapon. Bare-handed blows land at $2% of a full-grown pair's weight, all of it as slash, and they grow with every boss that falls. Draw a sword and they wait, sheathe it and they are back, until the timer runs out and they retract on their own - no slot wasted between casts. They cannot be dropped, traded or stolen while grown - and in beast form the jaws do the work instead.\n", "rov_compendium_fenrir_cursed_claws_s_wolf_s": "[Base Passive] Cursed Claws ([K], $1s): The wolf's hands, kept on in the man's shape for a limited time instead of a weapon. Bare-handed blows land at $2% of a full-grown pair's weight, all of it as slash, and they grow with every boss that falls. Draw a sword and they wait, sheathe it and they are back, until the timer runs out and they retract on their own - no slot wasted between casts. They cannot be dropped, traded or stolen while grown - and in beast form the jaws do the work instead.\n",
"rov_compendium_fenrir_fenring_form_h_key_night": "[Moder Unlock] Fenring Form ('H' Key, night only): Stand as a true Fenring - heavy claws and a leaping strike, and the strongest of the four shapes so far.\n", "rov_compendium_fenrir_fenring_form_h_key_night": "[Moder Unlock] Fenring Form ('H' Key, night only): Stand as a true Fenring - heavy claws and a leaping strike, and the strongest of the four shapes so far. It is the one that holds the line: every hit on it lands 30% lighter.\n",
"rov_compendium_fenrir_fenring_form_now_answers_by": "[The Queen Unlock] Fenring Form now answers by day as well as night.\n", "rov_compendium_fenrir_fenring_form_now_answers_by": "[The Queen Unlock] Fenring Form now answers by day as well as night.\n",
"rov_compendium_fenrir_g_now_calls_ulv_form": "[Moder Unlock] 'G' now calls Ulv Form instead of Wolf, and answers by day as well as night.\n", "rov_compendium_fenrir_g_now_calls_ulv_form": "[Moder Unlock] 'G' now calls Ulv Form instead of Wolf, and answers by day as well as night. The Ulv is the fastest of your shapes, the one to travel in.\n",
"rov_compendium_fenrir_senses_in_form": "In any form you sense every untamed creature within $1m, marking it with a telltale glow, as the Aswid do.\n", "rov_compendium_fenrir_senses_in_form": "In any form you sense every untamed creature within $1m, marking it with a telltale glow, as the Aswid do.\n",
"rov_compendium_fenrir_sunrise_breaks_any_night_bound": "Sunrise breaks any night-bound form early and leaves the beast too tired to change shape again for a short while after.\n", "rov_compendium_fenrir_sunrise_breaks_any_night_bound": "Sunrise breaks any night-bound form early and leaves the beast too tired to change shape again for a short while after.\n",
"rov_compendium_fenrir_title": "Fenrir Secrets", "rov_compendium_fenrir_title": "Fenrir Secrets",
@ -142,7 +142,7 @@
"rov_compendium_skadi_one_stonecutter_holds_them_no": "One stonecutter holds $1 of them, and no more than $2 may stand within a day's walk of each other. Break the stonecutter and what it cut goes still $3 seconds later.\n", "rov_compendium_skadi_one_stonecutter_holds_them_no": "One stonecutter holds $1 of them, and no more than $2 may stand within a day's walk of each other. Break the stonecutter and what it cut goes still $3 seconds later.\n",
"rov_compendium_skadi_secrets_winter": "The Secrets of Winter\n", "rov_compendium_skadi_secrets_winter": "The Secrets of Winter\n",
"rov_compendium_skadi_skeleton_dragon_form_j_key": "[Fader Unlock] Skeleton Dragon Form ('J' Key):", "rov_compendium_skadi_skeleton_dragon_form_j_key": "[Fader Unlock] Skeleton Dragon Form ('J' Key):",
"rov_compendium_skadi_take_shape_frost_drake_right": "Take the shape of a frost drake. Right Mouse lifts you into flight: you glide wherever you aim, hold W to climb and gather speed, hold Shift with it to spend stamina on a burst of speed, and press S to beat backwards along your aim while your gaze stays where it was. Release everything and you hold level for five seconds before settling into a slow descent. Water cannot hold you - your wings drag you free of the sea as readily as they lift you from the shore. In this shape you cannot yet strike.\n", "rov_compendium_skadi_take_shape_frost_drake_right": "Take the shape of a frost drake. Right Mouse lifts you into flight: you glide wherever you aim, hold W to climb and gather speed, hold Shift with it to spend stamina on a burst of speed, and press S to beat backwards along your aim while your gaze stays where it was. Release everything and you hold level for a few seconds before settling into a slow descent. Water cannot hold you - your wings drag you free of the sea as readily as they lift you from the shore. Carry too much and they will not lift you at all. In this shape you cannot yet strike.\n",
"rov_compendium_skadi_tear_cold_nothing_wakes_stone": "The tear is cold. Nothing wakes in the stone until the mountain's queen has fallen.\n", "rov_compendium_skadi_tear_cold_nothing_wakes_stone": "The tear is cold. Nothing wakes in the stone until the mountain's queen has fallen.\n",
"rov_compendium_skadi_title": "Skadi Secrets", "rov_compendium_skadi_title": "Skadi Secrets",
"rov_compendium_skadi_winter_incarnate_passive": "[The Queen Unlock] Winter Incarnate (Passive):", "rov_compendium_skadi_winter_incarnate_passive": "[The Queen Unlock] Winter Incarnate (Passive):",
@ -240,5 +240,9 @@
"rov_compendium_warvulture_goes_where_look_goes_as": "It goes where you look, and it goes as long as you care to stay up: $1 meters a second costs it nothing at all. Hold your run key and it gives you $2 for $3 seconds and not a moment longer - there is only so much haste in a bird. Let go and the wind comes back into it in $4 seconds, in the air. You never have to land for it.\n", "rov_compendium_warvulture_goes_where_look_goes_as": "It goes where you look, and it goes as long as you care to stay up: $1 meters a second costs it nothing at all. Hold your run key and it gives you $2 for $3 seconds and not a moment longer - there is only so much haste in a bird. Let go and the wind comes back into it in $4 seconds, in the air. You never have to land for it.\n",
"rov_compendium_warvulture_vulture_s_head_kept_stick": "A vulture's head kept on a stick, and the bird answers to it. Raise it and the vulture comes back under you. Raise it again and it carries you down, deaf to you until the ground arrives - and a third time lets go of it where you are.\n", "rov_compendium_warvulture_vulture_s_head_kept_stick": "A vulture's head kept on a stick, and the bird answers to it. Raise it and the vulture comes back under you. Raise it again and it carries you down, deaf to you until the ground arrives - and a third time lets go of it where you are.\n",
"rov_compendium_warvulture_war_vulture": "\n-- THE WAR VULTURE --\n", "rov_compendium_warvulture_war_vulture": "\n-- THE WAR VULTURE --\n",
"rov_compendium_warvulture_what_bird_has_left_bar": "What the bird has left is the bar under your own.\n" "rov_compendium_warvulture_what_bird_has_left_bar": "What the bird has left is the bar under your own.\n",
"rov_compendium_skeleton_diet_bones": "No hunger moves you and no meal can help you - mortal food is nothing to dry bones. In its place the dead grow strong as their betters fall: you carry +$1 Maximum Health at your present standing.",
"rov_compendium_skeleton_diet_mortal": "You kept the habits of the flesh: you eat as the living do, and your health comes from your meals, not from your standing.",
"rov_compendium_skeleton_effort_none": "Nor does effort tire you; you have no stamina to spend at all.",
"rov_compendium_skeleton_effort_mortal": "Effort tires you as it tires the living, and you spend stamina like anyone else."
} }

View file

@ -52,5 +52,7 @@
"rov_hover_ward_race_menu_ward_progression_open": "$rov_piece_racemenuward_name\n$1 progression - $2 ($3/$4)\n[<color=yellow><b>$KEY_Use</b></color>] Open\n[<color=yellow><b>Use item</b></color>] Offer a boss relic", "rov_hover_ward_race_menu_ward_progression_open": "$rov_piece_racemenuward_name\n$1 progression - $2 ($3/$4)\n[<color=yellow><b>$KEY_Use</b></color>] Open\n[<color=yellow><b>Use item</b></color>] Offer a boss relic",
"rov_hover_ward_world": "World", "rov_hover_ward_world": "World",
"rov_hover_boneship_roster": "\nmelee $1/$2 of $3\narchers $4/$5 of $6\naboard $7", "rov_hover_boneship_roster": "\nmelee $1/$2 of $3\narchers $4/$5 of $6\naboard $7",
"rov_hover_boneship_bone_hand": "\nbone in hand to buy a place" "rov_hover_boneship_bone_hand": "\nbone in hand to buy a place",
"rov_hover_alfar_inngangskista": "Inngangskista (input)",
"rov_hover_alfar_eldividarkista": "Eldividarkista (fuel)"
} }

View file

@ -18,6 +18,7 @@
"rov_msg_aswid_vae_victis": "Vae Victis", "rov_msg_aswid_vae_victis": "Vae Victis",
"rov_msg_aswid_what_horrible_night_have_curse": "what a horrible night to have a curse", "rov_msg_aswid_what_horrible_night_have_curse": "what a horrible night to have a curse",
"rov_msg_aswid_bat_cooldown": "Your blood is not ready to take wing again ($1s)", "rov_msg_aswid_bat_cooldown": "Your blood is not ready to take wing again ($1s)",
"rov_msg_aswid_bat_combat_lock": "Your blood runs too hot from the fight to take wing ($1s)",
"rov_msg_aswid_bat_form_fades": "The bat form fades", "rov_msg_aswid_bat_form_fades": "The bat form fades",
"rov_msg_aswid_bat_too_heavy_to_beat": "Too heavy to beat your wings. You can only glide", "rov_msg_aswid_bat_too_heavy_to_beat": "Too heavy to beat your wings. You can only glide",
"rov_msg_aswid_too_heavy_for_bat": "You carry too much to take bat form", "rov_msg_aswid_too_heavy_for_bat": "You carry too much to take bat form",
@ -117,6 +118,7 @@
"rov_msg_skadi_are_moder": "You are Moder!", "rov_msg_skadi_are_moder": "You are Moder!",
"rov_msg_skadi_dragon_form_cooldown": "Dragon Form is on cooldown ($1:$2).", "rov_msg_skadi_dragon_form_cooldown": "Dragon Form is on cooldown ($1:$2).",
"rov_msg_skadi_dragon_form_fades": "Your dragon form fades.", "rov_msg_skadi_dragon_form_fades": "Your dragon form fades.",
"rov_msg_skadi_too_heavy_to_fly": "You carry too much for the Drake to take off",
"rov_msg_skadi_dumped_dragon_drake_fader_debug": "Dumped Dragon/Drake/Fader debug info to console!", "rov_msg_skadi_dumped_dragon_drake_fader_debug": "Dumped Dragon/Drake/Fader debug info to console!",
"rov_msg_skadi_needs_stonecutter_cut_at": "It needs a stonecutter to be cut at.", "rov_msg_skadi_needs_stonecutter_cut_at": "It needs a stonecutter to be cut at.",
"rov_msg_skadi_not_enough_stamina": "Not enough stamina", "rov_msg_skadi_not_enough_stamina": "Not enough stamina",
@ -239,6 +241,9 @@
"rov_msg_build_limit_alfar_ljosgard": "This core already has its Ljosgard." "rov_msg_build_limit_alfar_ljosgard": "This core already has its Ljosgard."
, ,
"rov_msg_alfar_nexus_no_store": "The nucleus has nothing to offer right now.", "rov_msg_alfar_nexus_no_store": "The nucleus has nothing to offer right now.",
"rov_msg_alfar_drone_sort_nowhere": "I have nowhere to put $1. Give me an empty chest, or one that already holds $1.",
"rov_msg_alfar_drone_sort_keep": "I leave $1 in the $2: a station here works with it.",
"rov_msg_alfar_drone_kiln_wood": "The $4 is idle. I only burn wood from the $3, and the $1 is in another chest.",
"rov_msg_build_scale": "Size $1", "rov_msg_build_scale": "Size $1",
"rov_hint_build_scale": "Alt: Size" "rov_hint_build_scale": "Alt: Size"
} }

View file

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

View file

@ -86,14 +86,14 @@
"rov_compendium_dvergar_weapon_crossbow": "Balestra", "rov_compendium_dvergar_weapon_crossbow": "Balestra",
"rov_compendium_dvergar_weapon_hammer": "Martello", "rov_compendium_dvergar_weapon_hammer": "Martello",
"rov_compendium_fenrir_beast_within_physical_stats_scale": "[Passiva base] La bestia dentro: le tue statistiche fisiche crescono con ogni boss sconfitto: +$1 armatura, +$2 danni, +$3% velocità, +$4% salto e -$5% danni da caduta.\n", "rov_compendium_fenrir_beast_within_physical_stats_scale": "[Passiva base] La bestia dentro: le tue statistiche fisiche crescono con ogni boss sconfitto: +$1 armatura, +$2 danni, +$3% velocità, +$4% salto e -$5% danni da caduta.\n",
"rov_compendium_fenrir_cultist_form_j_key_night": "[Sblocco Yagluth] Forma di Cultista (tasto 'J', solo di notte): una figura incappucciata che artiglia e incanala il fuoco. Dura 1 minuto, ricarica di 10 minuti.\n", "rov_compendium_fenrir_cultist_form_j_key_night": "[Sblocco Yagluth] Forma di Cultista (tasto 'J', solo di notte): una figura incappucciata che artiglia e incanala il fuoco, e lo paga: ogni colpo che subisce arriva più forte del 25%. Dura 1 minuto, ricarica di 10 minuti.\n",
"rov_compendium_fenrir_cultist_form_now_answers_by": "[Sblocco Fader] La forma di Cultista ora risponde di giorno come di notte, e puoi tenerla quanto vuoi.\n", "rov_compendium_fenrir_cultist_form_now_answers_by": "[Sblocco Fader] La forma di Cultista ora risponde di giorno come di notte, e puoi tenerla quanto vuoi.\n",
"rov_compendium_fenrir_cultist_form_s_cooldown_falls": "[Sblocco Regina] La ricarica della forma di Cultista scende a 5 minuti (sempre solo di notte, sempre 1 minuto).\n", "rov_compendium_fenrir_cultist_form_s_cooldown_falls": "[Sblocco Regina] La ricarica della forma di Cultista scende a 5 minuti (sempre solo di notte, sempre 1 minuto).\n",
"rov_compendium_fenrir_curse_pack": "La maledizione del branco\n", "rov_compendium_fenrir_curse_pack": "La maledizione del branco\n",
"rov_compendium_fenrir_cursed_claws_s_wolf_s": "[Passiva base] Artigli maledetti ([K], $1s): le mani del lupo, tenute nella forma dell'uomo per un tempo limitato al posto di un'arma. I colpi a mani nude valgono il $2% del peso di un paio adulto, tutto come danno da taglio, e crescono con ogni boss che cade. Sfodera una spada e aspettano, rinfoderala e tornano, finché il tempo non scade e si ritraggono da soli, senza sprecare uno slot tra un uso e l'altro. Mentre sono fuori non possono essere lasciati cadere, scambiati o rubati, e in forma di bestia sono le fauci a fare il lavoro.\n", "rov_compendium_fenrir_cursed_claws_s_wolf_s": "[Passiva base] Artigli maledetti ([K], $1s): le mani del lupo, tenute nella forma dell'uomo per un tempo limitato al posto di un'arma. I colpi a mani nude valgono il $2% del peso di un paio adulto, tutto come danno da taglio, e crescono con ogni boss che cade. Sfodera una spada e aspettano, rinfoderala e tornano, finché il tempo non scade e si ritraggono da soli, senza sprecare uno slot tra un uso e l'altro. Mentre sono fuori non possono essere lasciati cadere, scambiati o rubati, e in forma di bestia sono le fauci a fare il lavoro.\n",
"rov_compendium_fenrir_fenring_form_h_key_night": "[Sblocco Moder] Forma di Fenring (tasto 'H', solo di notte): ergiti come un vero Fenring, con artigli pesanti e un attacco in salto, la più forte delle quattro forme finora.\n", "rov_compendium_fenrir_fenring_form_h_key_night": "[Sblocco Moder] Forma di Fenring (tasto 'H', solo di notte): ergiti come un vero Fenring, con artigli pesanti e un attacco in salto, la più forte delle quattro forme finora. È la forma che tiene la linea: ogni colpo che subisce arriva più leggero del 30%.\n",
"rov_compendium_fenrir_fenring_form_now_answers_by": "[Sblocco Regina] La forma di Fenring ora risponde di giorno come di notte.\n", "rov_compendium_fenrir_fenring_form_now_answers_by": "[Sblocco Regina] La forma di Fenring ora risponde di giorno come di notte.\n",
"rov_compendium_fenrir_g_now_calls_ulv_form": "[Sblocco Moder] 'G' ora richiama la forma di Ulv invece del Lupo, e risponde di giorno come di notte.\n", "rov_compendium_fenrir_g_now_calls_ulv_form": "[Sblocco Moder] 'G' ora richiama la forma di Ulv invece del Lupo, e risponde di giorno come di notte. L'Ulv è la più veloce delle tue forme, quella per viaggiare.\n",
"rov_compendium_fenrir_senses_in_form": "In qualsiasi forma percepisci ogni creatura non addomesticata entro $1m, e la segni con un bagliore rivelatore, come fanno gli Aswid.\n", "rov_compendium_fenrir_senses_in_form": "In qualsiasi forma percepisci ogni creatura non addomesticata entro $1m, e la segni con un bagliore rivelatore, come fanno gli Aswid.\n",
"rov_compendium_fenrir_sunrise_breaks_any_night_bound": "L'alba spezza in anticipo ogni forma legata alla notte, e lascia la bestia troppo stanca per cambiare di nuovo forma per un po'.\n", "rov_compendium_fenrir_sunrise_breaks_any_night_bound": "L'alba spezza in anticipo ogni forma legata alla notte, e lascia la bestia troppo stanca per cambiare di nuovo forma per un po'.\n",
"rov_compendium_fenrir_title": "Segreti dei Fenrir", "rov_compendium_fenrir_title": "Segreti dei Fenrir",
@ -142,7 +142,7 @@
"rov_compendium_skadi_one_stonecutter_holds_them_no": "Uno scalpellino ne tiene $1, e non più di $2 possono stare entro una giornata di cammino l'uno dall'altro. Distruggi lo scalpellino e ciò che ha tagliato si ferma $3 secondi dopo.\n", "rov_compendium_skadi_one_stonecutter_holds_them_no": "Uno scalpellino ne tiene $1, e non più di $2 possono stare entro una giornata di cammino l'uno dall'altro. Distruggi lo scalpellino e ciò che ha tagliato si ferma $3 secondi dopo.\n",
"rov_compendium_skadi_secrets_winter": "I segreti dell'inverno\n", "rov_compendium_skadi_secrets_winter": "I segreti dell'inverno\n",
"rov_compendium_skadi_skeleton_dragon_form_j_key": "[Sblocco Fader] Forma di drago scheletrico (tasto 'J'):", "rov_compendium_skadi_skeleton_dragon_form_j_key": "[Sblocco Fader] Forma di drago scheletrico (tasto 'J'):",
"rov_compendium_skadi_take_shape_frost_drake_right": "Prendi la forma di un drake del gelo. Il tasto destro ti solleva in volo: plani dove miri, tieni premuto W per salire e prendere velocità, aggiungi Shift per spendere stamina in uno scatto, e premi S per battere le ali all'indietro lungo la mira mentre lo sguardo resta dov'era. Lascia tutto e resti in quota per cinque secondi prima di scendere piano. L'acqua non può trattenerti: le tue ali ti tirano fuori dal mare con la stessa facilità con cui ti sollevano dalla riva. In questa forma non puoi ancora colpire.\n", "rov_compendium_skadi_take_shape_frost_drake_right": "Prendi la forma di un drake del gelo. Il tasto destro ti solleva in volo: plani dove miri, tieni premuto W per salire e prendere velocità, aggiungi Shift per spendere stamina in uno scatto, e premi S per battere le ali all'indietro lungo la mira mentre lo sguardo resta dov'era. Lascia tutto e resti in quota per qualche secondo prima di scendere piano. L'acqua non può trattenerti: le tue ali ti tirano fuori dal mare con la stessa facilità con cui ti sollevano dalla riva. Se porti troppo peso, però, non ti sollevano affatto. In questa forma non puoi ancora colpire.\n",
"rov_compendium_skadi_tear_cold_nothing_wakes_stone": "La lacrima è fredda. Niente si sveglia nella pietra finché la regina della montagna non è caduta.\n", "rov_compendium_skadi_tear_cold_nothing_wakes_stone": "La lacrima è fredda. Niente si sveglia nella pietra finché la regina della montagna non è caduta.\n",
"rov_compendium_skadi_title": "Segreti di Skadi", "rov_compendium_skadi_title": "Segreti di Skadi",
"rov_compendium_skadi_winter_incarnate_passive": "[Sblocco Regina] Inverno incarnato (passiva):", "rov_compendium_skadi_winter_incarnate_passive": "[Sblocco Regina] Inverno incarnato (passiva):",
@ -240,5 +240,9 @@
"rov_compendium_warvulture_goes_where_look_goes_as": "Va dove guardi, e va finché vuoi restare in aria: $1 metri al secondo non gli costano niente. Tieni premuto il tasto di corsa e ti dà $2 per $3 secondi, non un momento di più: in un uccello c'è solo tanta fretta. Lascia andare e il vento gli torna dentro in $4 secondi, in aria. Non devi mai atterrare per questo.\n", "rov_compendium_warvulture_goes_where_look_goes_as": "Va dove guardi, e va finché vuoi restare in aria: $1 metri al secondo non gli costano niente. Tieni premuto il tasto di corsa e ti dà $2 per $3 secondi, non un momento di più: in un uccello c'è solo tanta fretta. Lascia andare e il vento gli torna dentro in $4 secondi, in aria. Non devi mai atterrare per questo.\n",
"rov_compendium_warvulture_vulture_s_head_kept_stick": "La testa di un avvoltoio infilata su un bastone, e l'uccello le risponde. Sollevala e l'avvoltoio torna sotto di te. Sollevala di nuovo e ti porta giù, sordo a te finché non arriva il terreno; una terza volta ti lascia andare dove sei.\n", "rov_compendium_warvulture_vulture_s_head_kept_stick": "La testa di un avvoltoio infilata su un bastone, e l'uccello le risponde. Sollevala e l'avvoltoio torna sotto di te. Sollevala di nuovo e ti porta giù, sordo a te finché non arriva il terreno; una terza volta ti lascia andare dove sei.\n",
"rov_compendium_warvulture_war_vulture": "\n-- L'AVVOLTOIO DA GUERRA --\n", "rov_compendium_warvulture_war_vulture": "\n-- L'AVVOLTOIO DA GUERRA --\n",
"rov_compendium_warvulture_what_bird_has_left_bar": "Ciò che resta all'uccello è la barra sotto la tua.\n" "rov_compendium_warvulture_what_bird_has_left_bar": "Ciò che resta all'uccello è la barra sotto la tua.\n",
"rov_compendium_skeleton_diet_bones": "Nessuna fame ti muove e nessun pasto può aiutarti: il cibo dei mortali non è niente per ossa secche. Al suo posto i morti si rafforzano man mano che i loro superiori cadono: al tuo grado attuale hai +$1 di salute massima.",
"rov_compendium_skeleton_diet_mortal": "Hai conservato le abitudini della carne: mangi come i vivi, e la tua salute viene dai pasti, non dal tuo grado.",
"rov_compendium_skeleton_effort_none": "Nemmeno la fatica ti stanca: non hai stamina da spendere.",
"rov_compendium_skeleton_effort_mortal": "La fatica ti stanca come stanca i vivi, e spendi stamina come chiunque altro."
} }

View file

@ -52,5 +52,7 @@
"rov_hover_ward_race_menu_ward_progression_open": "$rov_piece_racemenuward_name\nProgressione $1 - $2 ($3/$4)\n[<color=yellow><b>$KEY_Use</b></color>] Apri\n[<color=yellow><b>Usa oggetto</b></color>] Offri una reliquia di boss", "rov_hover_ward_race_menu_ward_progression_open": "$rov_piece_racemenuward_name\nProgressione $1 - $2 ($3/$4)\n[<color=yellow><b>$KEY_Use</b></color>] Apri\n[<color=yellow><b>Usa oggetto</b></color>] Offri una reliquia di boss",
"rov_hover_ward_world": "del mondo", "rov_hover_ward_world": "del mondo",
"rov_hover_boneship_roster": "\nmischia $1/$2 di $3\narcieri $4/$5 di $6\na bordo $7", "rov_hover_boneship_roster": "\nmischia $1/$2 di $3\narcieri $4/$5 di $6\na bordo $7",
"rov_hover_boneship_bone_hand": "\nosso in mano per comprare un posto" "rov_hover_boneship_bone_hand": "\nosso in mano per comprare un posto",
"rov_hover_alfar_inngangskista": "Inngangskista (ingresso)",
"rov_hover_alfar_eldividarkista": "Eldividarkista (combustibile)"
} }

View file

@ -18,6 +18,7 @@
"rov_msg_aswid_vae_victis": "Vae Victis", "rov_msg_aswid_vae_victis": "Vae Victis",
"rov_msg_aswid_what_horrible_night_have_curse": "what a horrible night to have a curse", "rov_msg_aswid_what_horrible_night_have_curse": "what a horrible night to have a curse",
"rov_msg_aswid_bat_cooldown": "Il tuo sangue non è pronto a spiccare il volo di nuovo ($1s)", "rov_msg_aswid_bat_cooldown": "Il tuo sangue non è pronto a spiccare il volo di nuovo ($1s)",
"rov_msg_aswid_bat_combat_lock": "Il sangue ti ribolle per lo scontro, non puoi spiccare il volo ($1s)",
"rov_msg_aswid_bat_form_fades": "La forma di pipistrello svanisce", "rov_msg_aswid_bat_form_fades": "La forma di pipistrello svanisce",
"rov_msg_aswid_bat_too_heavy_to_beat": "Troppo pesante per battere le ali. Puoi solo planare", "rov_msg_aswid_bat_too_heavy_to_beat": "Troppo pesante per battere le ali. Puoi solo planare",
"rov_msg_aswid_too_heavy_for_bat": "Porti troppo peso per prendere la forma di pipistrello", "rov_msg_aswid_too_heavy_for_bat": "Porti troppo peso per prendere la forma di pipistrello",
@ -117,6 +118,7 @@
"rov_msg_skadi_are_moder": "Sei Moder!", "rov_msg_skadi_are_moder": "Sei Moder!",
"rov_msg_skadi_dragon_form_cooldown": "La forma di drago è in ricarica ($1:$2).", "rov_msg_skadi_dragon_form_cooldown": "La forma di drago è in ricarica ($1:$2).",
"rov_msg_skadi_dragon_form_fades": "La tua forma di drago svanisce.", "rov_msg_skadi_dragon_form_fades": "La tua forma di drago svanisce.",
"rov_msg_skadi_too_heavy_to_fly": "Porti troppo peso perché il Drake possa alzarsi in volo",
"rov_msg_skadi_dumped_dragon_drake_fader_debug": "Info di debug Dragon/Drake/Fader scritte nella console!", "rov_msg_skadi_dumped_dragon_drake_fader_debug": "Info di debug Dragon/Drake/Fader scritte nella console!",
"rov_msg_skadi_needs_stonecutter_cut_at": "Ha bisogno di uno scalpellino per essere tagliato.", "rov_msg_skadi_needs_stonecutter_cut_at": "Ha bisogno di uno scalpellino per essere tagliato.",
"rov_msg_skadi_not_enough_stamina": "Stamina insufficiente", "rov_msg_skadi_not_enough_stamina": "Stamina insufficiente",
@ -239,6 +241,9 @@
"rov_msg_build_limit_alfar_ljosgard": "Questo nucleo ha gia' il suo Ljosgard." "rov_msg_build_limit_alfar_ljosgard": "Questo nucleo ha gia' il suo Ljosgard."
, ,
"rov_msg_alfar_nexus_no_store": "Il nucleo non ha niente da offrire adesso.", "rov_msg_alfar_nexus_no_store": "Il nucleo non ha niente da offrire adesso.",
"rov_msg_alfar_drone_sort_nowhere": "Non so dove mettere $1. Dammi una cassa vuota, o una che contenga già $1.",
"rov_msg_alfar_drone_sort_keep": "Lascio $1 nella $2: una stazione qui lo usa.",
"rov_msg_alfar_drone_kiln_wood": "$4 è fermo. Brucio solo la legna della $3, e $1 è in un'altra cassa.",
"rov_msg_build_scale": "Grandezza $1", "rov_msg_build_scale": "Grandezza $1",
"rov_hint_build_scale": "Alt: Grandezza" "rov_hint_build_scale": "Alt: Grandezza"
} }

View file

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

View file

@ -86,14 +86,14 @@
"rov_compendium_dvergar_weapon_crossbow": "Арбалет", "rov_compendium_dvergar_weapon_crossbow": "Арбалет",
"rov_compendium_dvergar_weapon_hammer": "Молот", "rov_compendium_dvergar_weapon_hammer": "Молот",
"rov_compendium_fenrir_beast_within_physical_stats_scale": "[Базовое пассивное] Зверь внутри: Ваши физические характеристики растут с каждым убитым боссом: +$1 к броне, +$2 к урону, +$3% к скорости, +$4% к прыжку и -$5% к урону от падения.\n", "rov_compendium_fenrir_beast_within_physical_stats_scale": "[Базовое пассивное] Зверь внутри: Ваши физические характеристики растут с каждым убитым боссом: +$1 к броне, +$2 к урону, +$3% к скорости, +$4% к прыжку и -$5% к урону от падения.\n",
"rov_compendium_fenrir_cultist_form_j_key_night": "[Награда: Яглут] Облик культиста (клавиша «J», только ночью): Облик в балахоне, раздирающий врагов когтями и направляющий потоки пламени. Длится 1 минуту, перезарядка: 10 минут.\n", "rov_compendium_fenrir_cultist_form_j_key_night": "[Награда: Яглут] Облик культиста (клавиша «J», только ночью): Облик в балахоне, раздирающий врагов когтями и направляющий потоки пламени. За это приходится платить: каждый удар по нему наносит на 25% больше урона. Длится 1 минуту, перезарядка: 10 минут.\n",
"rov_compendium_fenrir_cultist_form_now_answers_by": "[Награда: Прародитель] Облик культиста теперь подчиняется как днем, так и ночью, и его можно удерживать сколько угодно.\n", "rov_compendium_fenrir_cultist_form_now_answers_by": "[Награда: Прародитель] Облик культиста теперь подчиняется как днем, так и ночью, и его можно удерживать сколько угодно.\n",
"rov_compendium_fenrir_cultist_form_s_cooldown_falls": "[Награда: Королева] Перезарядка облика культиста снижена до 5 минут (все еще только ночью, длительность 1 минута).\n", "rov_compendium_fenrir_cultist_form_s_cooldown_falls": "[Награда: Королева] Перезарядка облика культиста снижена до 5 минут (все еще только ночью, длительность 1 минута).\n",
"rov_compendium_fenrir_curse_pack": "Проклятие Стаи\n", "rov_compendium_fenrir_curse_pack": "Проклятие Стаи\n",
"rov_compendium_fenrir_cursed_claws_s_wolf_s": "[Базовое пассивное] Проклятые когти ([K], $1 с): Волчьи лапы, сохраняющиеся в человеческом теле на ограниченное время вместо оружия. Удары голыми руками наносят $2% от урона зрелых когтей (полностью рубящий урон), и их сила растет с каждым павшим боссом. Достаньте меч — они исчезнут, вложите в ножны — вернутся, пока не истечет время. Не тратят место в инвентаре. Их нельзя выбросить, передать или украсть, пока они активны — а в зверином облике вместо них работают челюсти.\n", "rov_compendium_fenrir_cursed_claws_s_wolf_s": "[Базовое пассивное] Проклятые когти ([K], $1 с): Волчьи лапы, сохраняющиеся в человеческом теле на ограниченное время вместо оружия. Удары голыми руками наносят $2% от урона зрелых когтей (полностью рубящий урон), и их сила растет с каждым павшим боссом. Достаньте меч — они исчезнут, вложите в ножны — вернутся, пока не истечет время. Не тратят место в инвентаре. Их нельзя выбросить, передать или украсть, пока они активны — а в зверином облике вместо них работают челюсти.\n",
"rov_compendium_fenrir_fenring_form_h_key_night": "[Награда: Матерь] Облик фенринга (клавиша «H», только ночью): Станьте истинным Фенрингом — тяжелые когти, сокрушительный удар в прыжке и мощнейшая из четырех форм на данный момент.\n", "rov_compendium_fenrir_fenring_form_h_key_night": "[Награда: Матерь] Облик фенринга (клавиша «H», только ночью): Станьте истинным Фенрингом — тяжелые когти, сокрушительный удар в прыжке и мощнейшая из четырех форм на данный момент. Этот облик держит строй: каждый удар по нему наносит на 30% меньше урона.\n",
"rov_compendium_fenrir_fenring_form_now_answers_by": "[Награда: Королева] Облик фенринга теперь доступен как днем, так и ночью.\n", "rov_compendium_fenrir_fenring_form_now_answers_by": "[Награда: Королева] Облик фенринга теперь доступен как днем, так и ночью.\n",
"rov_compendium_fenrir_g_now_calls_ulv_form": "[Награда: Матерь] Клавиша «G» теперь призывает облик Ульва вместо Волка и доступна и днем, и ночью.\n", "rov_compendium_fenrir_g_now_calls_ulv_form": "[Награда: Матерь] Клавиша «G» теперь призывает облик Ульва вместо Волка и доступна и днем, и ночью. Ульв — самый быстрый из ваших обликов, в нем удобно путешествовать.\n",
"rov_compendium_fenrir_senses_in_form": "В любой форме вы чувствуете любое неприрученное существо в радиусе $1 м, подсвечивая его характерным свечением, как Асвиды.\n", "rov_compendium_fenrir_senses_in_form": "В любой форме вы чувствуете любое неприрученное существо в радиусе $1 м, подсвечивая его характерным свечением, как Асвиды.\n",
"rov_compendium_fenrir_sunrise_breaks_any_night_bound": "Восход солнца прерывает любую ночную форму раньше срока и оставляет зверя истощенным, не позволяя перевоплощаться еще некоторое время.\n", "rov_compendium_fenrir_sunrise_breaks_any_night_bound": "Восход солнца прерывает любую ночную форму раньше срока и оставляет зверя истощенным, не позволяя перевоплощаться еще некоторое время.\n",
"rov_compendium_fenrir_title": "Тайны Фенрира", "rov_compendium_fenrir_title": "Тайны Фенрира",
@ -142,7 +142,7 @@
"rov_compendium_skadi_one_stonecutter_holds_them_no": "Один камнерез поддерживает $1 таких стражей, и не более $2 могут находиться на расстоянии дневного перехода друг от друга. Сломайте камнерез — и сотворенный голем замрет навеки спустя $3 с.\n", "rov_compendium_skadi_one_stonecutter_holds_them_no": "Один камнерез поддерживает $1 таких стражей, и не более $2 могут находиться на расстоянии дневного перехода друг от друга. Сломайте камнерез — и сотворенный голем замрет навеки спустя $3 с.\n",
"rov_compendium_skadi_secrets_winter": "Тайны Зимы\n", "rov_compendium_skadi_secrets_winter": "Тайны Зимы\n",
"rov_compendium_skadi_skeleton_dragon_form_j_key": "[Награда: Прародитель] Облик дракона-скелета (клавиша «J»):", "rov_compendium_skadi_skeleton_dragon_form_j_key": "[Награда: Прародитель] Облик дракона-скелета (клавиша «J»):",
"rov_compendium_skadi_take_shape_frost_drake_right": "Примите облик ледяного дрейка. ПКМ поднимает вас в воздух: вы парите туда, куда смотрите; зажмите W, чтобы набирать высоту и скорость; зажмите с ней Shift, чтобы ускориться за счет выносливости; нажмите S, чтобы пятиться спиной назад, удерживая прицел. Отпустите клавиши управления — и вы замрете в воздухе на 5 секунд перед медленным снижением. Вода не удержит вас: крылья выдернут вас из морской пучины так же легко, как и с берега. В этой форме вы пока не можете атаковать.\n", "rov_compendium_skadi_take_shape_frost_drake_right": "Примите облик ледяного дрейка. ПКМ поднимает вас в воздух: вы парите туда, куда смотрите; зажмите W, чтобы набирать высоту и скорость; зажмите с ней Shift, чтобы ускориться за счет выносливости; нажмите S, чтобы пятиться спиной назад, удерживая прицел. Отпустите клавиши управления — и вы замрете в воздухе на несколько секунд перед медленным снижением. Вода не удержит вас: крылья выдернут вас из морской пучины так же легко, как и с берега. Но с перегрузом они вас не поднимут. В этой форме вы пока не можете атаковать.\n",
"rov_compendium_skadi_tear_cold_nothing_wakes_stone": "Слеза холодна. Ничто в камне не пробудится, пока владычица гор не падет.\n", "rov_compendium_skadi_tear_cold_nothing_wakes_stone": "Слеза холодна. Ничто в камне не пробудится, пока владычица гор не падет.\n",
"rov_compendium_skadi_title": "Тайны Скади", "rov_compendium_skadi_title": "Тайны Скади",
"rov_compendium_skadi_winter_incarnate_passive": "[Награда: Королева] Воплощение зимы (Пассивное):", "rov_compendium_skadi_winter_incarnate_passive": "[Награда: Королева] Воплощение зимы (Пассивное):",
@ -240,5 +240,9 @@
"rov_compendium_warvulture_goes_where_look_goes_as": "Она летит туда, куда обращен ваш взор, и летит так долго, как вы того пожелаете: полет со скоростью $1 м/с не стоит птице никаких сил. Зажмите клавишу бега — и она выдаст рывок со скоростью $2 м/с на $3 с, не дольше: птичьи силы не безграничны. Отпустите бег, и дыхание вернется к ней через $4 с прямо в воздухе. Садиться на землю не придется.\n", "rov_compendium_warvulture_goes_where_look_goes_as": "Она летит туда, куда обращен ваш взор, и летит так долго, как вы того пожелаете: полет со скоростью $1 м/с не стоит птице никаких сил. Зажмите клавишу бега — и она выдаст рывок со скоростью $2 м/с на $3 с, не дольше: птичьи силы не безграничны. Отпустите бег, и дыхание вернется к ней через $4 с прямо в воздухе. Садиться на землю не придется.\n",
"rov_compendium_warvulture_vulture_s_head_kept_stick": "Голова стервятника на шесте, и хищная птица повинуется ей. Поднимите ее — и птица опустится вам под ноги. Поднимите снова — и она понесет вас к земле, не слушая команд до самого приземления, а поднятая в третий раз — отпустит вас на лету.\n", "rov_compendium_warvulture_vulture_s_head_kept_stick": "Голова стервятника на шесте, и хищная птица повинуется ей. Поднимите ее — и птица опустится вам под ноги. Поднимите снова — и она понесет вас к земле, не слушая команд до самого приземления, а поднятая в третий раз — отпустит вас на лету.\n",
"rov_compendium_warvulture_war_vulture": "\n-- БОЕВОЙ СТЕРВЯТНИК --\n", "rov_compendium_warvulture_war_vulture": "\n-- БОЕВОЙ СТЕРВЯТНИК --\n",
"rov_compendium_warvulture_what_bird_has_left_bar": "Остаток выносливости птицы отображается шкалой под вашей собственной.\n" "rov_compendium_warvulture_what_bird_has_left_bar": "Остаток выносливости птицы отображается шкалой под вашей собственной.\n",
"rov_compendium_skeleton_diet_bones": "Голод не движет вами, и никакая еда вам не поможет: смертная пища ничто для сухих костей. Взамен мёртвые крепнут по мере падения своих владык: на вашей нынешней ступени у вас +$1 к максимальному здоровью.",
"rov_compendium_skeleton_diet_mortal": "Вы сохранили привычки плоти: вы едите, как живые, и ваше здоровье даёт пища, а не ступень.",
"rov_compendium_skeleton_effort_none": "И усилия вас не утомляют: выносливости у вас нет вовсе.",
"rov_compendium_skeleton_effort_mortal": "Усилия утомляют вас, как живых, и вы тратите выносливость, как все."
} }

View file

@ -52,5 +52,7 @@
"rov_hover_ward_race_menu_ward_progression_open": "$rov_piece_racemenuward_name\n$1 прогресс — $2 ($3/$4)\n[<color=yellow><b>$KEY_Use</b></color>] Открыть\n[<color=yellow><b>Использовать предмет</b></color>] Пожертвовать реликвию босса", "rov_hover_ward_race_menu_ward_progression_open": "$rov_piece_racemenuward_name\n$1 прогресс — $2 ($3/$4)\n[<color=yellow><b>$KEY_Use</b></color>] Открыть\n[<color=yellow><b>Использовать предмет</b></color>] Пожертвовать реликвию босса",
"rov_hover_ward_world": "Общий", "rov_hover_ward_world": "Общий",
"rov_hover_boneship_roster": "\nближний бой $1/$2 из $3\nлучники $4/$5 из $6\nна борту $7", "rov_hover_boneship_roster": "\nближний бой $1/$2 из $3\nлучники $4/$5 из $6\nна борту $7",
"rov_hover_boneship_bone_hand": "\nкость в руке — купить место" "rov_hover_boneship_bone_hand": "\nкость в руке — купить место",
"rov_hover_alfar_inngangskista": "Инганг-киста (вход)",
"rov_hover_alfar_eldividarkista": "Эльдивидар-киста (топливо)"
} }

View file

@ -18,6 +18,7 @@
"rov_msg_aswid_vae_victis": "Vae Victis", "rov_msg_aswid_vae_victis": "Vae Victis",
"rov_msg_aswid_what_horrible_night_have_curse": "Какая ужасная ночь для носителя проклятия...", "rov_msg_aswid_what_horrible_night_have_curse": "Какая ужасная ночь для носителя проклятия...",
"rov_msg_aswid_bat_cooldown": "Ваша кровь еще не готова снова подняться в небо ($1 с)", "rov_msg_aswid_bat_cooldown": "Ваша кровь еще не готова снова подняться в небо ($1 с)",
"rov_msg_aswid_bat_combat_lock": "Кровь слишком горяча после схватки, чтобы подняться в небо ($1 с)",
"rov_msg_aswid_bat_form_fades": "Облик летучей мыши рассеивается", "rov_msg_aswid_bat_form_fades": "Облик летучей мыши рассеивается",
"rov_msg_aswid_bat_too_heavy_to_beat": "Слишком тяжело, чтобы махать крыльями. Вы можете только планировать", "rov_msg_aswid_bat_too_heavy_to_beat": "Слишком тяжело, чтобы махать крыльями. Вы можете только планировать",
"rov_msg_aswid_too_heavy_for_bat": "Вы несете слишком много, чтобы принять облик летучей мыши", "rov_msg_aswid_too_heavy_for_bat": "Вы несете слишком много, чтобы принять облик летучей мыши",
@ -117,6 +118,7 @@
"rov_msg_skadi_are_moder": "Вы — Матерь!", "rov_msg_skadi_are_moder": "Вы — Матерь!",
"rov_msg_skadi_dragon_form_cooldown": "Облик дракона перезаряжается ($1:$2).", "rov_msg_skadi_dragon_form_cooldown": "Облик дракона перезаряжается ($1:$2).",
"rov_msg_skadi_dragon_form_fades": "Ваш облик дракона рассеивается.", "rov_msg_skadi_dragon_form_fades": "Ваш облик дракона рассеивается.",
"rov_msg_skadi_too_heavy_to_fly": "Вы несете слишком много, чтобы Дрейк мог взлететь",
"rov_msg_skadi_dumped_dragon_drake_fader_debug": "Отладочная информация Dragon/Drake/Fader сброшена в консоль!", "rov_msg_skadi_dumped_dragon_drake_fader_debug": "Отладочная информация Dragon/Drake/Fader сброшена в консоль!",
"rov_msg_skadi_needs_stonecutter_cut_at": "Для обработки требуется камнерез.", "rov_msg_skadi_needs_stonecutter_cut_at": "Для обработки требуется камнерез.",
"rov_msg_skadi_not_enough_stamina": "Недостаточно выносливости", "rov_msg_skadi_not_enough_stamina": "Недостаточно выносливости",
@ -239,6 +241,9 @@
"rov_msg_build_limit_alfar_ljosgard": "У этого ядра уже есть свой Льосгард." "rov_msg_build_limit_alfar_ljosgard": "У этого ядра уже есть свой Льосгард."
, ,
"rov_msg_alfar_nexus_no_store": "У ядра сейчас нечего предложить.", "rov_msg_alfar_nexus_no_store": "У ядра сейчас нечего предложить.",
"rov_msg_alfar_drone_sort_nowhere": "Мне некуда положить $1. Дай мне пустой сундук или тот, где уже лежит $1.",
"rov_msg_alfar_drone_sort_keep": "Оставляю $1 в «$2»: с этим работает станция здесь.",
"rov_msg_alfar_drone_kiln_wood": "«$4» простаивает. Я жгу только дрова из «$3», а $1 лежит в другом сундуке.",
"rov_msg_build_scale": "Размер $1", "rov_msg_build_scale": "Размер $1",
"rov_hint_build_scale": "Alt: размер" "rov_hint_build_scale": "Alt: размер"
} }

View file

@ -40,7 +40,9 @@
"rov_se_skadi_dragonattackcd_tooltip": "Облик дракона восстанавливает силы для следующего удара.", "rov_se_skadi_dragonattackcd_tooltip": "Облик дракона восстанавливает силы для следующего удара.",
"rov_se_skadi_form_name": "Облик дракона", "rov_se_skadi_form_name": "Облик дракона",
"rov_se_skadi_form_tooltip": "Вы сохраняете драконий облик еще некоторое время.", "rov_se_skadi_form_tooltip": "Вы сохраняете драконий облик еще некоторое время.",
"rov_se_skadi_formcd_name": "Перезарядка облика дракона", "rov_se_skadi_drakecd_name": "Перезарядка облика Дрейка",
"rov_se_skadi_fadercd_name": "Перезарядка облика Фейдер",
"rov_se_skadi_formcd_name": "Перезарядка облика Модер",
"rov_se_skadi_stats_name": "Благословение Скади", "rov_se_skadi_stats_name": "Благословение Скади",
"rov_se_skeleton_resurrectcd_name": "Перезарядка воскрешения", "rov_se_skeleton_resurrectcd_name": "Перезарядка воскрешения",
"rov_se_skeleton_resurrectcd_tooltip": "Ваш костяк слишком слаб, чтобы воскреснуть вновь прямо сейчас.", "rov_se_skeleton_resurrectcd_tooltip": "Ваш костяк слишком слаб, чтобы воскреснуть вновь прямо сейчас.",

View file

@ -196,7 +196,14 @@ namespace RacesOfValheim
// The Trenta stands in its own rain and is healed by it too. It used to be left out, so // The Trenta stands in its own rain and is healed by it too. It used to be left out, so
// a lone Trenta cast a heal that never touched anyone. // a lone Trenta cast a heal that never touched anyone.
player.Heal(TrentaConfig.PurpleRainHealAmount, true); float heal = TrentaConfig.PurpleRainHealFor(player);
float poison = TrentaConfig.PurpleRainPoisonFor(player);
player.Heal(heal, true);
// Blood Magic experience once per cast that reached someone besides the caster, the
// way a vanilla staff pays per cast: healing only yourself earns nothing, or the
// skill would level by casting into an empty field on cooldown.
bool reachedSomeone = false;
HashSet<Character> hit = new HashSet<Character>(); HashSet<Character> hit = new HashSet<Character>();
foreach (Collider collider in Physics.OverlapSphere(player.transform.position, TrentaConfig.PurpleRainRadius)) foreach (Collider collider in Physics.OverlapSphere(player.transform.position, TrentaConfig.PurpleRainRadius))
@ -209,16 +216,20 @@ namespace RacesOfValheim
if (BaseAI.IsEnemy(player, character)) if (BaseAI.IsEnemy(player, character))
{ {
HitData hitData = new HitData(); HitData hitData = new HitData();
hitData.m_damage.m_poison = TrentaConfig.PurpleRainPoisonDamage; hitData.m_damage.m_poison = poison;
hitData.m_skill = Skills.SkillType.BloodMagic;
hitData.SetAttacker(player); hitData.SetAttacker(player);
hitData.m_dir = Vector3.zero; hitData.m_dir = Vector3.zero;
character.Damage(hitData); character.Damage(hitData);
} }
else else
{ {
character.Heal(TrentaConfig.PurpleRainHealAmount, true); character.Heal(heal, true);
} }
reachedSomeone = true;
} }
if (reachedSomeone) FormMelee.RaiseSkill(Skills.SkillType.BloodMagic);
} }
/// <summary> /// <summary>

View file

@ -120,6 +120,16 @@ namespace RacesOfValheim
public static float PurpleRainRadius => TrentaConfigManagement.PurpleRainRadius.Value; public static float PurpleRainRadius => TrentaConfigManagement.PurpleRainRadius.Value;
public static float PurpleRainHealAmount => TrentaConfigManagement.PurpleRainHealAmount.Value; public static float PurpleRainHealAmount => TrentaConfigManagement.PurpleRainHealAmount.Value;
public static float PurpleRainPoisonDamage => TrentaConfigManagement.PurpleRainPoisonDamage.Value; public static float PurpleRainPoisonDamage => TrentaConfigManagement.PurpleRainPoisonDamage.Value;
// The base figures plus the Blood Magic bonus, scaled linearly up to the full bonus at
// level 100 - the same shape as the Aswid's Vampiric Aura. The compendium reads these
// too, so its numbers follow the player's skill.
public static float PurpleRainHealFor(Player player) =>
PurpleRainHealAmount + BloodMagicFactor(player) * TrentaConfigManagement.PurpleRainBloodMagicHeal.Value;
public static float PurpleRainPoisonFor(Player player) =>
PurpleRainPoisonDamage + BloodMagicFactor(player) * TrentaConfigManagement.PurpleRainBloodMagicPoison.Value;
private static float BloodMagicFactor(Player player) =>
player != null ? player.GetSkillFactor(Skills.SkillType.BloodMagic) : 0f;
// A Poison-type hit; vanilla's own // A Poison-type hit; vanilla's own
// poison-on-hit handling takes over from // poison-on-hit handling takes over from
// there, same as SkeletonRace's fire aura // there, same as SkeletonRace's fire aura

View file

@ -45,6 +45,8 @@ namespace RacesOfValheim
public static ConfigEntry<float> PurpleRainRadius; public static ConfigEntry<float> PurpleRainRadius;
public static ConfigEntry<float> PurpleRainHealAmount; public static ConfigEntry<float> PurpleRainHealAmount;
public static ConfigEntry<float> PurpleRainPoisonDamage; public static ConfigEntry<float> PurpleRainPoisonDamage;
public static ConfigEntry<float> PurpleRainBloodMagicHeal;
public static ConfigEntry<float> PurpleRainBloodMagicPoison;
// ─── Bonemass (tier 4+, passive) ────────────────────────────────────── // ─── Bonemass (tier 4+, passive) ──────────────────────────────────────
public static ConfigEntry<float> SwimStaminaRegen; public static ConfigEntry<float> SwimStaminaRegen;
@ -116,6 +118,10 @@ namespace RacesOfValheim
new ConfigDescription("Flat heal applied to you and to every ally hit.", new AcceptableValueRange<float>(0f, 200f))); new ConfigDescription("Flat heal applied to you and to every ally hit.", new AcceptableValueRange<float>(0f, 200f)));
PurpleRainPoisonDamage = config.Bind(purpleRain, "Enemy Poison Damage", 40f, PurpleRainPoisonDamage = config.Bind(purpleRain, "Enemy Poison Damage", 40f,
new ConfigDescription("Flat poison damage applied to every enemy hit.", new AcceptableValueRange<float>(0f, 200f))); new ConfigDescription("Flat poison damage applied to every enemy hit.", new AcceptableValueRange<float>(0f, 200f)));
PurpleRainBloodMagicHeal = config.Bind(purpleRain, "Blood Magic Heal Bonus", 40f,
new ConfigDescription("Extra heal at 100 Blood Magic skill, added to Ally Heal Amount (scales linearly from 0).", new AcceptableValueRange<float>(0f, 200f)));
PurpleRainBloodMagicPoison = config.Bind(purpleRain, "Blood Magic Poison Bonus", 40f,
new ConfigDescription("Extra poison damage at 100 Blood Magic skill, added to Enemy Poison Damage (scales linearly from 0).", new AcceptableValueRange<float>(0f, 200f)));
const string bonemass = "Trenta - Bonemass"; const string bonemass = "Trenta - Bonemass";
SwimStaminaRegen = config.Bind(bonemass, "Swim Stamina Regen", 0.1f, SwimStaminaRegen = config.Bind(bonemass, "Swim Stamina Regen", 0.1f,

View file

@ -435,6 +435,7 @@ namespace RacesOfValheim
float totalDamage = baseDamage + unarmedSkillLevel; float totalDamage = baseDamage + unarmedSkillLevel;
HashSet<GameObject> hit = new HashSet<GameObject>(); HashSet<GameObject> hit = new HashSet<GameObject>();
bool hitCreature = false;
foreach (Collider collider in Physics.OverlapSphere(center, radius)) foreach (Collider collider in Physics.OverlapSphere(center, radius))
{ {
Character target = collider.GetComponentInParent<Character>(); Character target = collider.GetComponentInParent<Character>();
@ -442,7 +443,12 @@ namespace RacesOfValheim
if (!BaseAI.IsEnemy(player, target)) continue; if (!BaseAI.IsEnemy(player, target)) continue;
DealDamage(player, target, totalDamage, HitData.DamageType.Blunt, Vector3.zero); DealDamage(player, target, totalDamage, HitData.DamageType.Blunt, Vector3.zero);
hitCreature = true;
} }
// The spike projectile levels Unarmed through vanilla's Projectile.OnHit; the stomp
// calls Damage directly and has to raise the skill itself.
if (hitCreature) FormMelee.RaiseSkill(Skills.SkillType.Unarmed);
} }
/// <summary> /// <summary>

View file

@ -0,0 +1,248 @@
using System.Collections;
using System.Collections.Generic;
using System.IO;
using HarmonyLib;
using Jotunn.Entities;
using Jotunn.Managers;
using UnityEngine;
using UnityEngine.Networking;
namespace RacesOfValheim
{
/// <summary>
/// Two rare Trol voice lines: one when a Trol dies, one when a Trol places a piece with Trol's
/// Hammer. Each has a 1% chance by default.
///
/// The chance is Dota's pseudo-random distribution, not a plain roll: each try starts at a tiny
/// chance C that grows by C after every miss and falls back to C after a hit. It averages the
/// same chance, but long droughts and back-to-back repeats almost never happen, which suits a
/// joke heard rarely. The miss counters live in memory and start over with the game.
///
/// The roll happens on the Trol's own client, which then sends the sound and the spot to every
/// client; each one plays it there if its player is within reach.
///
/// A secret on purpose: no setting, and no word of it in the README, changelog or wiki. The
/// chance and the volume are constants here for that reason.
///
/// The clips ship inside the DLL (Audio/*.ogg, embedded by the csproj), so no sound file sits in
/// the plugins folder for a curious player to find. Unity can only decode Ogg from a file, so at
/// startup each one is written to the game's temp cache under a random name, loaded, and deleted.
/// </summary>
public static class TrolSounds
{
public const string Death = "trolsdeath";
public const string Building = "trolsbuilding";
private const string RpcName = "RoV_TrolSound";
private const float Range = 20f; // metres: heard nearby, not across the base
private const float Volume = 0.6f;
public const float DeathChance = 1f; // percent
public const float BuildingChance = 1f; // percent
private const string MixerSource = "sfx_build_hammer_wood";
private static readonly string[] Clips = { Death, Building };
private static readonly Dictionary<string, AudioClip> s_clips = new Dictionary<string, AudioClip>();
private static readonly Dictionary<string, int> s_misses = new Dictionary<string, int>();
// --- loading ---
/// <summary>Loads both clips out of the DLL, by way of a file that lives only while it loads.</summary>
public static IEnumerator Load()
{
foreach (string name in Clips)
{
byte[] bytes;
using (Stream stream = typeof(TrolSounds).Assembly.GetManifestResourceStream(name + ".ogg"))
{
if (stream == null)
{
Jotunn.Logger.LogWarning($"[TrolSounds] No embedded clip '{name}'.");
continue;
}
bytes = new byte[stream.Length];
int read = 0;
while (read < bytes.Length) read += stream.Read(bytes, read, bytes.Length - read);
}
string path = Path.Combine(Application.temporaryCachePath, System.Guid.NewGuid().ToString("N"));
File.WriteAllBytes(path, bytes);
using (UnityWebRequest request = UnityWebRequestMultimedia.GetAudioClip("file:///" + path.Replace('\\', '/'), AudioType.OGGVORBIS))
{
yield return request.SendWebRequest();
if (request.result == UnityWebRequest.Result.Success)
{
AudioClip clip = DownloadHandlerAudioClip.GetContent(request);
clip.name = name;
s_clips[name] = clip;
}
else
{
Jotunn.Logger.LogWarning($"[TrolSounds] Could not load '{name}': {request.error}");
}
}
try { File.Delete(path); } catch (IOException) { }
}
}
// --- the roll ---
/// <summary>One try at a sound for the local Trol: plays it for everyone nearby on a hit.</summary>
public static void Try(string sound, float percent, Vector3 position)
{
if (!Roll(sound, percent / 100f)) return;
Broadcast(sound, position);
}
private static bool Roll(string sound, float chance)
{
if (chance <= 0f) return false;
if (chance >= 1f) return true;
s_misses.TryGetValue(sound, out int misses);
if (Random.value < PrdConstant(chance) * (misses + 1))
{
s_misses[sound] = 0;
return true;
}
s_misses[sound] = misses + 1;
return false;
}
private static float s_constantFor = -1f, s_constant;
/// <summary>
/// The step C whose growing chance (C, 2C, 3C... until a hit) averages the chance asked for.
/// No formula gives C; it is found by halving, once per chance value (0.000156 for 1%).
/// </summary>
private static float PrdConstant(float chance)
{
if (Mathf.Approximately(chance, s_constantFor)) return s_constant;
double low = 0, high = chance;
for (int i = 0; i < 50; i++)
{
double c = (low + high) / 2;
if (AverageChance(c) > chance) high = c; else low = c;
}
s_constantFor = chance;
s_constant = (float)((low + high) / 2);
return s_constant;
}
/// <summary>The average chance a step of c gives: one over the expected tries to a hit.</summary>
private static double AverageChance(double c)
{
double expected = 0, missedSoFar = 1;
for (int n = 1; missedSoFar > 1e-12; n++)
{
double hit = System.Math.Min(1, c * n);
expected += n * missedSoFar * hit;
missedSoFar *= 1 - hit;
}
return 1 / expected;
}
// --- playing ---
public static void Broadcast(string sound, Vector3 position)
{
if (ZRoutedRpc.instance != null)
ZRoutedRpc.instance.InvokeRoutedRPC(ZRoutedRpc.Everybody, RpcName, sound, position);
else
Play(sound, position);
}
public static void Register()
{
ZRoutedRpc.instance?.Register<string, Vector3>(RpcName, (sender, sound, position) => Play(sound, position));
}
/// <summary>Plays a clip at a spot, if the local player is within reach of it. Through the
/// game's sound-effects mixer, so Valheim's own SFX slider turns it down too.</summary>
public static void Play(string sound, Vector3 position)
{
if (!s_clips.TryGetValue(sound, out AudioClip clip) || clip == null) return;
Player player = Player.m_localPlayer;
if (player != null && Vector3.Distance(player.transform.position, position) > Range) return;
GameObject go = new GameObject("RoV_" + sound);
go.transform.position = position;
AudioSource source = go.AddComponent<AudioSource>();
source.clip = clip;
source.volume = Volume;
source.spatialBlend = 1f;
source.rolloffMode = AudioRolloffMode.Linear;
source.minDistance = 4f;
source.maxDistance = Range;
source.outputAudioMixerGroup = MixerGroup();
source.Play();
Object.Destroy(go, clip.length + 0.5f);
}
private static UnityEngine.Audio.AudioMixerGroup s_mixer;
private static UnityEngine.Audio.AudioMixerGroup MixerGroup()
{
if (s_mixer != null) return s_mixer;
GameObject sfx = PrefabManager.Cache.GetPrefab<GameObject>(MixerSource);
AudioSource vanilla = sfx != null ? sfx.GetComponentInChildren<AudioSource>(true) : null;
s_mixer = vanilla != null ? vanilla.outputAudioMixerGroup : null;
return s_mixer;
}
public static bool IsTrol(Player player) => FactionHostilityPatch.GetPlayerRace(player) == "Trol";
}
[HarmonyPatch(typeof(Game), "Start")]
public static class TrolSoundsRpcPatch
{
private static void Postfix() => TrolSounds.Register();
}
[HarmonyPatch(typeof(Player), "OnDeath")]
public static class TrolSoundsDeathPatch
{
private static void Prefix(Player __instance)
{
if (__instance != Player.m_localPlayer || !TrolSounds.IsTrol(__instance)) return;
TrolSounds.Try(TrolSounds.Death, TrolSounds.DeathChance, __instance.transform.position);
}
}
[HarmonyPatch(typeof(Player), "PlacePiece")]
public static class TrolSoundsBuildingPatch
{
private static void Postfix(Player __instance)
{
if (__instance != Player.m_localPlayer || !TrolsHammerItem.IsTrolsHammer(__instance.RightItem)) return;
if (!TrolSounds.IsTrol(__instance)) return;
TrolSounds.Try(TrolSounds.Building, TrolSounds.BuildingChance, __instance.transform.position);
}
}
/// <summary>
/// rovsnd1 / rovsnd2: play one of the two sounds now, for everyone nearby, to try it out. The
/// names and the help say nothing about what they play: the console's help lists every command.
/// </summary>
public class TrolSoundCommand : ConsoleCommand
{
private readonly string m_name;
private readonly string m_sound;
public TrolSoundCommand(string name, string sound)
{
m_name = name;
m_sound = sound;
}
public override string Name => m_name;
public override string Help => "[DEBUG] Sound test.";
public override void Run(string[] args)
{
Player player = Player.m_localPlayer;
if (player == null) { Console.instance.Print("No local player."); return; }
TrolSounds.Broadcast(m_sound, player.transform.position);
}
}
}

View file

@ -15,9 +15,9 @@ Support the mod: [Patreon — NandorTheModder](https://www.patreon.com/c/NandorT
--- ---
## New in v1.6.5 ## New in v1.6.11
**The old bat flight is back, and the wolves smell their prey.** Aswid players can pick Free Flight, the fast bat flight with no stamina cost, and a server can pick for everyone. Every Fenrir form now lights nearby creatures green, as the Aswid does. The Grafvaettir's drones finally dig copper and tin. Full details in the [changelog](#v165). **F8 no longer fires by accident.** The debug key now lives in a new `Debug` section of the config. It's off until you turn it on, and you can rebind it. Heads-up: `Debug: Log Form Hits` moved there from `Fenrir - Debug`, so if you had turned it on, turn it on again. Full details in the [changelog](#v1611).
--- ---
@ -29,6 +29,7 @@ Support the mod: [Patreon — NandorTheModder](https://www.patreon.com/c/NandorT
![Skeleton](https://wiki.aledanidev.ovh/assets/images/corna_scheletro.gif) ![Skeleton](https://wiki.aledanidev.ovh/assets/images/corna_scheletro.gif)
- **Stamina-less Combat:** Skeletons use no stamina and do not have a stamina bar. - **Stamina-less Combat:** Skeletons use no stamina and do not have a stamina bar.
- **Undead Diet:** Cannot eat normal food. Max health increases automatically as you defeat bosses to make up for lack of food buffs. - **Undead Diet:** Cannot eat normal food. Max health increases automatically as you defeat bosses to make up for lack of food buffs.
- **Mortal Habits (optional):** each player can turn on *Eats Mortal Food* (eat like the living; health comes from meals, and the boss health bonus is dropped) and *Feels Fatigue* (spend stamina like the living) in the config section `Skeleton - Mortal Habits`. Both are off by default and not synced by the server.
- **Lit Sockets:** Your skull carries the eye lights of the creature your tier is built from, in that creature's own colour — so they change as the body does. - **Lit Sockets:** Your skull carries the eye lights of the creature your tier is built from, in that creature's own colour — so they change as the body does.
- **Body Model switch:** with a player model mod (EnhancedValheimVRM and the like), set `Skeleton - Visuals` → `Body Model Enabled` to off and Skeletons keep the vanilla body. Abilities stay the same. - **Body Model switch:** with a player model mod (EnhancedValheimVRM and the like), set `Skeleton - Visuals` → `Body Model Enabled` to off and Skeletons keep the vanilla body. Abilities stay the same.
- **Show Helmet:** turn on `Skeleton - Visuals` → `Show Helmet` and your helmet sits on the skull. Off by default; other players see it the way you picked. - **Show Helmet:** turn on `Skeleton - Visuals` → `Show Helmet` and your helmet sits on the skull. Off by default; other players see it the way you picked.
@ -38,15 +39,15 @@ Support the mod: [Patreon — NandorTheModder](https://www.patreon.com/c/NandorT
![Skadi2](https://wiki.aledanidev.ovh/assets/images/skadi2.gif) ![Skadi2](https://wiki.aledanidev.ovh/assets/images/skadi2.gif)
![Skadi3](https://wiki.aledanidev.ovh/assets/images/skadi3.gif) ![Skadi3](https://wiki.aledanidev.ovh/assets/images/skadi3.gif)
- **Ice Affinity:** Resistant to cold, with unique frost mechanics. - **Ice Affinity:** Resistant to cold, with unique frost mechanics.
- **Drake Form:** Can transform into a frost Drake, letting you fly. - **Drake Form:** Can transform into a frost Drake, letting you fly. The Drake is the scout: quick, nimble, free to fly, but it will not take off while you carry too much.
- **Dragon Form:** Evolve into Moder and later even the Skeleton Dragon. - **Dragon Form:** Evolve into Moder and later even the Skeleton Dragon. The Moder is the freighter: slow to turn, 3 stamina a second to fly, but it lifts a heavy pack. Flight numbers, duration and cooldown for each form are under `Skadi - Dragon Forms`.
- **Elemental Magic:** The Cold Spell and all three dragon breaths raise the Elemental Magic skill when they connect — one cast is worth one cast, however many shards it throws. The Frost Aura earns a fraction of that per tick that actually burns something. Both amounts are configurable, and the dragon forms' melee stays on Unarmed, where it always was. - **Elemental Magic:** The Cold Spell and all three dragon breaths raise the Elemental Magic skill when they connect — one cast is worth one cast, however many shards it throws. The Frost Aura earns a fraction of that per tick that actually burns something. Both amounts are configurable, and the dragon forms' melee stays on Unarmed, where it always was.
### 3. Fenrir ### 3. Fenrir
![Fenrir1](https://wiki.aledanidev.ovh/assets/images/fenrir1.gif) ![Fenrir1](https://wiki.aledanidev.ovh/assets/images/fenrir1.gif)
![Fenrir3](https://wiki.aledanidev.ovh/assets/images/fenrir3.gif) ![Fenrir3](https://wiki.aledanidev.ovh/assets/images/fenrir3.gif)
- **Beast Form:** Transform into a wolf-like beast. - **Beast Form:** Transform into a wolf-like beast. Each form has a job: the Ulv is the fastest, the one to travel in; the Fenring takes 30% less damage and holds the line.
- **Cultist Form:** Transform into a Cultist. Its claws cost nothing, but the **fire breath (hold Right Mouse) runs on eitr** — 12.5 per second — and eitr comes from the Mistlands, so the form unlocks at Yagluth with its flames still out of reach. Holding the button with an empty pool now says so. - **Cultist Form:** Transform into a Cultist. Its claws cost nothing, but the **fire breath (hold Right Mouse) runs on eitr** — 12.5 per second — and eitr comes from the Mistlands, so the form unlocks at Yagluth with its flames still out of reach. Holding the button with an empty pool now says so. The Cultist hits hardest and pays for it: it takes 25% more damage.
- **Cursed Claws:** The wolf's hands, kept on in the man's shape — see [Claws](#claws). - **Cursed Claws:** The wolf's hands, kept on in the man's shape — see [Claws](#claws).
- **Night Eyes:** At night your eyes glow in the Fenring's orange: faintly while no form is ready, brightly when one is, and yellow when the Cultist is back from its cooldown. Other players see it too. Turn it off, or the "Ready!" message, under `Fenrir - Appearance`. - **Night Eyes:** At night your eyes glow in the Fenring's orange: faintly while no form is ready, brightly when one is, and yellow when the Cultist is back from its cooldown. Other players see it too. Turn it off, or the "Ready!" message, under `Fenrir - Appearance`.
- **Hunter's Senses:** In any form, every untamed creature within 100 m glows green, the same senses as the Aswid's. Radius under `Fenrir - Superhuman Senses`. - **Hunter's Senses:** In any form, every untamed creature within 100 m glows green, the same senses as the Aswid's. Radius under `Fenrir - Superhuman Senses`.
@ -57,7 +58,7 @@ Support the mod: [Patreon — NandorTheModder](https://www.patreon.com/c/NandorT
### 4. Aswid ### 4. Aswid
![Aswid](https://wiki.aledanidev.ovh/assets/images/aswidchallenge.gif) ![Aswid](https://wiki.aledanidev.ovh/assets/images/aswidchallenge.gif)
- **The Vampire:** Life-draining abilities. - **The Vampire:** Life-draining abilities.
- **Bat Form:** Press G to become a bat. It flies where you look, with the Skadi drake's controls: W beats forward, Shift sprints, S beats backwards, and letting go hovers a moment before you glide down. Flying and sprinting cost stamina; out of stamina you can only glide. Carrying too much makes it cost 15% more, or, if you set `While Encumbered` to Blocked, keeps you on the ground. Monsters see, chase and hurt the bat like anyone else. - **Bat Form:** Press G to become a bat. It flies where you look, with the Skadi drake's controls: W beats forward, Shift sprints, S beats backwards, and letting go hovers a moment before you glide down. Flying and sprinting cost stamina; out of stamina you can only glide. Carrying too much makes it cost 15% more, or, if you set `While Encumbered` to Blocked, keeps you on the ground. Monsters see, chase and hurt the bat like anyone else. You can't take bat form until 2.5 seconds after you last lost health (`Combat Lock`).
- **Free Bat Flight:** Prefer the old bat? Turn on `Aswid - Bat Form` → `Free Bat Flight`: up to 50 m/s, no stamina and no weight limit, Jump rises and Left Ctrl sinks. Monsters still see and hurt you. The server's `Bat Flight Rule` can force one flight on everyone. - **Free Bat Flight:** Prefer the old bat? Turn on `Aswid - Bat Form` → `Free Bat Flight`: up to 50 m/s, no stamina and no weight limit, Jump rises and Left Ctrl sinks. Monsters still see and hurt you. The server's `Bat Flight Rule` can force one flight on everyone.
- **Vampiric Aura:** A passive life-draining aura around you, no key to hold: half damage as human, double as mist. As a bat it stays silent until The Queen falls (configurable under `Aswid - Vampiric Aura`). Press **[I]** to toggle it (and Devour) off, e.g. before trading with Haldor or Hildir, since it does not recognize traders from monsters. - **Vampiric Aura:** A passive life-draining aura around you, no key to hold: half damage as human, double as mist. As a bat it stays silent until The Queen falls (configurable under `Aswid - Vampiric Aura`). Press **[I]** to toggle it (and Devour) off, e.g. before trading with Haldor or Hildir, since it does not recognize traders from monsters.
- **Blood Magic Mastery:** Cast Blood Magic items with infinite Eitr (health cost only). - **Blood Magic Mastery:** Cast Blood Magic items with infinite Eitr (health cost only).
@ -93,6 +94,7 @@ Support the mod: [Patreon — NandorTheModder](https://www.patreon.com/c/NandorT
- **Kin of the Traders:** Haldor/Hildir give you better prices. - **Kin of the Traders:** Haldor/Hildir give you better prices.
- **Coin Instead of Blood:** The Contract Bank hires professional dvergr crews and the Rune Barrel gives them drink — see [Race Stations](#race-stations--companions). - **Coin Instead of Blood:** The Contract Bank hires professional dvergr crews and the Rune Barrel gives them drink — see [Race Stations](#race-stations--companions).
- **Runes:** Late game, spend Eitr for powerful effects. - **Runes:** Late game, spend Eitr for powerful effects.
- **Deep-Folk Builders:** Black marble building pieces cost 3 stone per marble, and Yggdrasil wood pieces 2 fine wood per Yggdrasil wood. Stations and furniture keep their cost. The pieces carry the Dvergar icon in the build menu, and taking one down gives back what you paid. Ratios and an off switch under `Dvergar - Cheap Building`.
### 9. Trenta ### 9. Trenta
![Trenta](https://wiki.aledanidev.ovh/assets/images/trentecheers.gif) ![Trenta](https://wiki.aledanidev.ovh/assets/images/trentecheers.gif)
@ -108,7 +110,7 @@ Support the mod: [Patreon — NandorTheModder](https://www.patreon.com/c/NandorT
- **Hive Pheromones:** No invertebrate attacks you — leeches, ticks, deathsquitos, seekers and bees all ignore you, from tier zero. - **Hive Pheromones:** No invertebrate attacks you — leeches, ticks, deathsquitos, seekers and bees all ignore you, from tier zero.
- **Toxin Immunity:** Poison cannot touch you. Blunt and fire hit you 40% harder — until Fader, when the fire weakness burns out and comes back as a resistance. - **Toxin Immunity:** Poison cannot touch you. Blunt and fire hit you 40% harder — until Fader, when the fire weakness burns out and comes back as a resistance.
- **The Colony:** After the Elder, a Brood Mound, a Hive Market and a roster of insect troops bought with digested biomass. - **The Colony:** After the Elder, a Brood Mound, a Hive Market and a roster of insect troops bought with digested biomass.
- **Ravager Strain:** After Yagluth, become a Seeker Brute, with its own bite, lunging ram and two-claw ground slam that digs the earth. The carapace is worth double. - **Ravager Strain:** After Yagluth, become a Seeker Brute, with its own bite, lunging ram and two-claw ground slam that digs the earth. Its damage grows with Unarmed. The carapace is worth double.
### 11. Alfar ### 11. Alfar
- **Eitr Shield:** Eitr is your armour: blows land on the eitr pool first, and lightning and spirit cost double. Only drowning and the edge of the world ignore it. Every food you eat also feeds the pool. - **Eitr Shield:** Eitr is your armour: blows land on the eitr pool first, and lightning and spirit cost double. Only drowning and the edge of the world ignore it. Every food you eat also feeds the pool.
@ -294,7 +296,7 @@ Build a **Brood Mound** with the hammer — no more than two within its density
- **Base:** Tree-Born. Green skin/branches, plant diet, food lasts 2x. Photosynthesis: stand still in daylight for 10s = heal 10% max HP/sec for 8s, Rested buff (5 min +1min per boss). Greylings, greydwarves, fulings, trolls, leeches and deathsquitos ignore you. - **Base:** Tree-Born. Green skin/branches, plant diet, food lasts 2x. Photosynthesis: stand still in daylight for 10s = heal 10% max HP/sec for 8s, Rested buff (5 min +1min per boss). Greylings, greydwarves, fulings, trolls, leeches and deathsquitos ignore you.
- **Eikthyr:** Awakened Seeds – eat seeds/cones/acorns/mushrooms for strong food buffs. - **Eikthyr:** Awakened Seeds – eat seeds/cones/acorns/mushrooms for strong food buffs.
- **Elder:** Purple Rain (G): 8m toxic pollen heals you and your allies, poisons enemies, 20s CD. - **Elder:** Purple Rain (G): 8m toxic pollen heals you and your allies, poisons enemies, 20s CD. Heal and poison grow with Blood Magic (+40 each at level 100), and a cast that reaches someone else trains it.
- **Bonemass:** Swim uses no stamina and stamina comes back slowly in the water, immune to Poison/Wet. - **Bonemass:** Swim uses no stamina and stamina comes back slowly in the water, immune to Poison/Wet.
- **Moder:** Last Stand – armor rises as health falls (up to +50%), Thorns (reflects 20% damage). - **Moder:** Last Stand – armor rises as health falls (up to +50%), Thorns (reflects 20% damage).
- **Yagluth:** Homecoming Portal (H): portal to respawn point, anyone can use, 5min CD. - **Yagluth:** Homecoming Portal (H): portal to respawn point, anyone can use, 5min CD.
@ -482,7 +484,7 @@ Aswid, Draugh, Skeleton / at peace with Ghost, Skeleton, Draugr, Wraith, Leech,
The **Sverm** belongs to no faction. Its Hive Pheromones make every invertebrate in the game ignore it instead — leeches, ticks, deathsquitos, seekers and bees — with no boss gate and no trading. The **Sverm** belongs to no faction. Its Hive Pheromones make every invertebrate in the game ignore it instead — leeches, ticks, deathsquitos, seekers and bees — with no boss gate and no trading.
A truce is not a shield: hit one of your own and it hits back, for **Faction grudge** seconds (60 by default), then forgets about it. Your always-on auras — the Aswid's drain, the Skadi's frost — leave your own kin alone, so they never start that fight for you. A truce is not a shield: hit one of your own and it hits back, for **Faction grudge** seconds (60 by default), then forgets about it. Want it harder? Turn on **Grudge spreads to kin** and every creature of that faction within 20 m (`Grudge spread radius`) joins the fight too, the way vanilla's Dvergr treat a human. Your always-on auras — the Aswid's drain, the Skadi's frost — leave your own kin alone, so they never start that fight for you.
Both halves have an off switch under `Factions` in Configuration Manager: **Faction truce** for whether your faction's mobs leave you alone, **Faction merchants** for whether they will trade. Both are on by default and both take effect without a restart. Be aware that turning the truce off also gives up every race's own peace — Fenrir's wolves, the Aswid's list, the Draugh's undead, the Trenta's Black Forest, the Sverm's invertebrates, the Furling's Plains roster and the Skeleton's undead — because they are all the same question asked of the same vanilla method. Both halves have an off switch under `Factions` in Configuration Manager: **Faction truce** for whether your faction's mobs leave you alone, **Faction merchants** for whether they will trade. Both are on by default and both take effect without a restart. Be aware that turning the truce off also gives up every race's own peace — Fenrir's wolves, the Aswid's list, the Draugh's undead, the Trenta's Black Forest, the Sverm's invertebrates, the Furling's Plains roster and the Skeleton's undead — because they are all the same question asked of the same vanilla method.
@ -490,6 +492,49 @@ Both halves have an off switch under `Factions` in Configuration Manager: **Fact
## Changelog ## Changelog
### v1.6.11
- **Heads-up - config key moved:** `Fenrir - Debug` → `Debug: Log Form Hits` is now `Debug` → `Debug: Log Form Hits`. If you had turned it on, turn it on again in Configuration Manager. The old entry stays in your .cfg but does nothing; delete it by hand if you like.
- **Change - the debug key is off by default and can be rebound:** F8 used to toggle the melee reach readout and write Alfar drone reports to the log for everyone, with no way to turn it off. It now sits in a new `Debug` section: `Debug: Enable Debug Key` (off by default) turns it on, and `Debug Key` (F8 by default) rebinds it. `Debug: Log Form Hits` moved into the same section, since it logs the Skadi, Sverm and Trol forms as well as the Fenrir ones. Thanks to Dagaz for the request. Not tested in game yet.
### v1.6.10
- **Fix - Skadi's Moder and Fader forms couldn't hit the training dummy:** their bites, claws and spin checked for cover with a line that counted the target's own body as a wall. Anything standing on the build layer, like the T.W.I.G. training dummy, could never be hit; wildlife worked. They now use the same reach check as the Fenrir forms, and each hit plays the real dragon's impact sound. The blow also lands on the clip's own hit frame instead of a fixed half second, which was early for every melee: the Moder's claws landed a second and a half before the claw came down. Thanks to lexsonn for the report. Not tested in game yet.
- **Change - Ravager Strain fights like the troll True Form:** the Brute's swing and impact sounds play on the bite, ram and slam, which were silent. Every attack that lands on a creature trains Unarmed, and the damage now grows with it the way a weapon grows with its skill: about 40% of a real Seeker Brute's at level 0, about 92% at level 100. The new key `Sverm - Ravager Strain` → `Ravager Attack Damage` (default 1) multiplies it. The bite and the ram now stay in front of you and no longer hit through walls, and each attack uses the Brute's own push and tool tier. Thanks to lexsonn for the report. Not tested in game yet.
- **Fix - Alfar Skrid blinked you onto the roof:** a blink aimed at the floor ended with your feet under it, and the check meant to lift you out of the ground measured from the sky, so under any roof (a crypt, a cave, a house) it put you on top of the roof instead. Skrid now lands you on the floor under the spot it reaches. Inside a dungeon or cave it is cancelled, at no cost, when there is no floor under that spot. Thanks to Joacwoo for the report and the videos. Not tested in game yet.
- **Fix - Alfar hair and beard flashed in for a moment:** changing anything in your hands made the game put the character's hair and beard back, and the Alfar only took them off again half a second later. They are now blocked where the game attaches them, so they never show. Thanks to Joacwoo for the report and the video. Not tested in game yet.
### v1.6.9
- **Fix - you couldn't hit your own faction:** since Valheim 1.0, a player's hit passes through any creature the game calls friendly unless PvP is on, and the faction truce called every creature of your faction friendly. Your blows did nothing, no grudge started, and `Grudge spreads to kin` had nothing to spread. Hitting one of your own works again, and it and its kin fight back as intended. The truce still keeps them off you; it no longer shields them from you. Thanks to Joacwoo and CrimsonAiro for the reports. Not tested in game yet.
- **Fix - grudges in multiplayer:** a creature now keeps its grudge when another player's game takes over running it mid-fight, for example when the first player walks away or logs out. `Grudge spreads to kin` now also reaches kin that another player's game is running; before, they stayed calm until hit themselves. Every player needs this version: a creature run by an older client behaves the old way. Not tested in multiplayer yet.
- **New - race attacks train their skills:** many attacks grew with a skill but gave no XP for it, so the skill never moved. Now an attack that lands on a creature gives the XP a weapon hit gives, and damage over time gives a share per second. Hitting trees or rocks gives nothing. Not tested in game yet.
- Fenrir: the Fenring, Cultist, Wolf and Ulv claws and bites train Unarmed. The Cultist's fire breath trains Elemental Magic.
- Skadi: the Drake forms' bites and claws train Unarmed.
- Trenta: the Muspell stomp trains Unarmed.
- Aswid: the Vampiric Aura slowly trains Blood Magic.
- Alfar: Geisli and Ljosstorm train Elemental Magic. The Sameining pulse trains it slowly.
- **Change - Purple Rain grows with Blood Magic:** at level 100 it heals and poisons for 40 more than its base 40. The bonus has two new keys under `Trenta - Purple Rain`: `Blood Magic Heal Bonus` and `Blood Magic Poison Bonus`. A cast that reaches anyone besides you trains Blood Magic, and the Compendium shows your current numbers. Not tested in game yet.
- **Fix - pukeberries and the Aswid's fourth stomach:** pukeberries emptied only the three vanilla food slots, so the Aswid's fourth meal stayed. It now goes like the others. Thanks to Joacwoo for the report.
### v1.6.8
- **New - Skeleton Mortal Habits:** two options under `Skeleton - Mortal Habits`, both off by default, each player picking their own. *Eats Mortal Food*: the Skeleton eats like the living, and its health and stamina come from its meals. The boss-tier health bonus goes away, since it stood in for food. *Feels Fatigue*: the Skeleton spends stamina; if it doesn't eat, its stamina grows with its standing. Every other Skeleton power stays. Thanks to Celepito for the request. Not tested in game yet.
- **New - Aswid bat form waits out a fight:** you can't take bat form until 2.5 seconds after you last lost health, from a hit or a tick of fire, poison or bleeding. Turning back is never blocked, and a hit still doesn't knock you out of bat form. `Aswid - Bat Form` → `Combat Lock` sets the time; 0 turns it off. Not tested in game yet.
- **New - Dvergar build cheap marble and Yggdrasil pieces:** a Dvergar pays 3 stone for each black marble and 2 fine wood for each Yggdrasil wood on walls, floors, beams, roofs, arches, stairs, doors and stakes. Stations, furniture, containers and fires keep their cost. The marble pieces still need a Stonecutter and the Yggdrasil ones a Black Forge, and they show in the build menu with the Dvergar icon once you know stone or fine wood. Taking a piece down gives back what was paid for it, whoever does it, so a cheap wall never turns into black marble. `Dvergar - Cheap Building` holds the off switch and both ratios. Thanks to Wargles for the suggestion. Refunds not tested in game yet.
- **New - a faction can fight as a group:** turn on `Factions` → `Grudge spreads to kin` and hitting a creature of your own faction makes every creature of that faction within 20 m turn on you too, for the usual grudge time, the way vanilla's Dvergr treat a human. Peace still holds until you strike first, and the radius is `Grudge spread radius`. Off by default. In multiplayer a creature run by another player's game stays calm until it is hit itself. Thanks to Joacwoo for the idea. Not tested in game yet.
- **Fix - Valheim 1.0's new skeletons ignored the faction:** the regional skeletons Valheim 1.0 added (the green ones in the swamp, the blue ones in the mountains, and those of the Meadows and the Deep North, each with its melee-only twin) were missing from the swamp faction, so they attacked Skeleton, Aswid and Draugh players the old skeletons left alone. They keep the truce now and run the Skeleton's faction shop. Thanks to Joacwoo for the report. Not tested in game yet.
### v1.6.7
- **Heads-up - config reset:** some settings were renamed, so any value you changed in them is back to its default. Skadi: everything in `Skadi - Directed Flight` now lives in `Skadi - Dragon Forms`, split into Drake and Moder keys. Fenrir: `Full Form Speed Bonus` is now `Fenring And Cultist Speed Bonus`, and `Wolf Form Speed Bonus` is split into `Wolf Speed Bonus` and `Ulv Speed Bonus`. If you had tuned any of these, set them again in Configuration Manager. The old entries stay in your .cfg but do nothing. Delete them by hand, or, if you never changed any setting, delete the whole .cfg and the game writes a fresh one on the next start. Don't delete the whole file if you customised anything else: everything goes back to default, keybinds included.
- **Change - Skadi's Drake and Moder fly differently:** the Drake is the scout: it turns faster, sprints at 26 m/s and flies for free, but it will not take off while you are encumbered. The Moder is the freighter: it turns slowly and pays 3 stamina a second to beat its wings, but it carries a heavy pack at 25% extra cost and glides for 8 seconds. `Skadi - Dragon Forms` holds every flight number per form plus, as on the Aswid's bat, Flight Stamina, While Encumbered, Encumbered Extra Stamina Cost, Max Duration, Duration Per State and Cooldown for the Drake, the Moder and the Fader. Duration and cooldown default to -1, which keeps the boss-tier timings. Each form also has its own cooldown now, with its own icon, so a cooldown on one form never blocks another. Thanks to Dissolution for the suggestion. Not tested in game yet.
- **Change - each Fenrir form has a job:** the Ulv is the travel form: it runs 100% faster, where the Fenring and the Cultist drop from 100% to 50%. The Fenring holds the line and takes 30% less damage from every hit. The Cultist keeps its damage and pays for it, taking 25% more. All four numbers are under `Fenrir - Form Buffs`. The Cultist's 25% is a first guess: tell us if it feels too harsh or too soft. Thanks to Lexsonn for the suggestion. Not tested in game yet.
- **Fix - Alfar drones froze with a load:** a delivery started with the clock of the trip before it, so a slow flight or a fight on the way left the drone frozen in place with its load, and only a respawn freed it. Kiln wood was the usual victim. The same fix reaches the Skeleton's, Sverm's and Skadi's servants. A station a drone cannot reach is now set aside for a few minutes, and the load goes back to the chest it came from. Drones also fly up beside a station instead of into it, so they reach a big one like the kiln. Thanks to the players who tested the fix.
### v1.6.6
- **New - Shrink Hammer:** a fine hammer for small work, a little drakkar on a shelf for instance. It builds everything the ordinary hammer builds, from the same menu and at the same cost, from a quarter of the size up to vanilla size. Craft it at a Workbench with 2 Fine Wood and 2 Resin; any race can. Thanks to MrBiffty for the idea.
- **New - Alt + scroll sizes your pieces:** with Trol's Hammer (1 to 3) or the Shrink Hammer (0.25 to 1), hold Alt and scroll in build mode to change the size in steps of 0.05. The bottom bar shows the hint, and the size floats over the preview whenever it is not the hammer's usual one. Select the repair tool and aim at a piece to read the size it was built at. The sliders in Configuration Manager follow the wheel. Both hammers have icons of their own now, so neither passes for the vanilla hammer.
- **Change - Alfar chests:** players took a plain Wood chest for the Eldividarkista, so neither Alfar chest looks like a vanilla chest any more. The Eldividarkista is a blackened iron crate with a grate on the front that glows and throws sparks only while it holds wood the drones may burn. The Inngangskista is navy steel with a cyan line in the lid that shines while it holds anything for the drones. Their hover names say which is which, and both have icons of their own. Thanks to snakey for the report.
- **Change - Ljoskjarne:** the Alfar core is now a riveted steel pyramid, 2 m tall, carved with Valheim's runes, floating 0.8 m above the ground and turning slowly. A cyan seam down each face breathes, and burns brighter while crystals wait. Building on it, hovering it and pressing E work as before.
- **Fix - Alfar drones stuck after a fight:** a drone alerted by an enemy kept fighting it forever if the enemy ran off but stayed loaded, and stopped sorting until you replaced it. Drones now drop an enemy that gets too far and go back to work. Not tested in game yet.
- **New - Alfar drones talk:** over their heads and in chat (40 m), the drones now say when an item in the Inngangskista has nowhere to go, when they keep an item there for a station, and when a kiln stands idle because its wood is in a plain chest instead of the Eldividarkista. Thanks to snakey for the reports.
### v1.6.5 ### v1.6.5
- **New - Free Bat Flight:** the bat flight from before v1.6.1 is back as a choice. Turn on `Aswid - Bat Form` → `Free Bat Flight` and the bat flies up to 50 m/s with Shift, costs no stamina and ignores your weight: Jump rises, Left Ctrl sinks. Handy for building tall. Each player picks their own. The server's `Bat Flight Rule` decides for everyone if the admin wants: PlayerChoice (the default), AlwaysStaminaFlight or AlwaysFreeFlight. A change counts from the next time you become a bat. Monsters still see, chase and hurt a free-flying bat. Thanks to MrBiffty for the idea. Not tested in game yet, multiplayer included. - **New - Free Bat Flight:** the bat flight from before v1.6.1 is back as a choice. Turn on `Aswid - Bat Form` → `Free Bat Flight` and the bat flies up to 50 m/s with Shift, costs no stamina and ignores your weight: Jump rises, Left Ctrl sinks. Handy for building tall. Each player picks their own. The server's `Bat Flight Rule` decides for everyone if the admin wants: PlayerChoice (the default), AlwaysStaminaFlight or AlwaysFreeFlight. A change counts from the next time you become a bat. Monsters still see, chase and hurt a free-flying bat. Thanks to MrBiffty for the idea. Not tested in game yet, multiplayer included.
- **New - Fenrir senses:** every Fenrir form (Wolf, Ulv, Fenring, Cultist) now lights each untamed creature within 100 m with a green glow, the same senses the Aswid gets at Moder. The human shape does not have it. Set the radius under `Fenrir - Superhuman Senses`; the light itself follows the Aswid's `Marker Light` settings. Thanks to MrBiffty's friend for the idea. Not tested in game yet. - **New - Fenrir senses:** every Fenrir form (Wolf, Ulv, Fenring, Cultist) now lights each untamed creature within 100 m with a green glow, the same senses the Aswid gets at Moder. The human shape does not have it. Set the radius under `Fenrir - Superhuman Senses`; the light itself follows the Aswid's `Marker Light` settings. Thanks to MrBiffty's friend for the idea. Not tested in game yet.
@ -655,37 +700,6 @@ Thanks to frogneel, Aquious, Dagaz and Dissolution for the Aswid reports and ide
- **Fix - Fenrir sounds were only half heard, and a 1.4.24 note was wrong:** 1.4.24 said these sounds had been writing into the world save. They had not - the game deletes them when they finish - and the change made for it left other players unable to hear them and could play a sound twice. Sounds are spawned the game's own way again. - **Fix - Fenrir sounds were only half heard, and a 1.4.24 note was wrong:** 1.4.24 said these sounds had been writing into the world save. They had not - the game deletes them when they finish - and the change made for it left other players unable to hear them and could play a sound twice. Sounds are spawned the game's own way again.
- **Fix - The Cold Spell key's description said tier 1+:** the spell unlocks at Eikthyr, tier 2, and the description now says so. - **Fix - The Cold Spell key's description said tier 1+:** the spell unlocks at Eikthyr, tier 2, and the description now says so.
### v1.4.24 Versions before v1.5.0 are no longer listed here — see the [wiki's release notes](https://wiki.aledanidev.ovh/release-notes) for the full history back to v1.0.0.
- **Fix - Purple smoke around the Skeleton's burning skull with some magic mods installed:** the fire aura the Skeleton wears from Moder on looked for its particles under two names that are not in Valheim at all. A name the game does not use is a free slot for whichever mod ships one, and with Magic Supremacy installed the aura picked up that mod's weapon trail on an emissive shader and sprayed it through a five-metre sphere. The aura had never actually been visible in a plain install, so it now draws nothing on purpose; its damage, radius and tick are untouched. Thanks to the players who reported it and named the mods they were running.
- **Fix - Effects and sounds that were quietly missing across five races:** an audit of every prefab the mod asks for by name found nine that do not exist in the game, each one failing in silence. The puff that covers a transformation never played for the Fenrir, the Skadi or the Trenta's Muspell; the Aswid's Mist Form appeared and vanished with no effect at all, and so did dominating a creature with a thrall; the Aswid's two status effects and its Bat Form entry in the radial had no icon. All of them now use names the game really has.
- **Fix - A Draugh's successful parry threw an error and cancelled its own frost nova:** the poison splash asked for an effect that does not exist and passed it straight to the game without checking, so every parry inside the window failed at that line - taking the North Wind nova that runs immediately after it down as well. Both work now.
- **New - Human Meat is a real item at last:** the Bonemass tier has promised it since 1.4 and nothing ever created it, so the drop never happened and the "fatal to the living" warning never fired. A player who dies inside your death aura now leaves a piece behind, yourself included, and only a Draugh can stomach it. It is built from Blood Pudding's own nourishment, with its stamina folded into health since a Draugh has no use for stamina, and is tunable under `Draugh - Undead Fortitude`.
- **Fix - Fenrir forms fought in a borrowed voice, or in silence:** every form's sounds were looked up by name and most of those names are not in the game. The chains hid it - a Fenring swung with a wolf's voice through a fallback - and the Cultist's double claw asked for three dead names in a row and had never made a sound at all. Each form now uses the creature's own sounds, and the jump attack's impact lands with the jump instead of firing while the form is still standing.
- **New - The Cultist says why its fire will not come:** holding Right Mouse 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 tells you the flames want eitr.
- **New - Howl on demand in every Fenrir form:** the howl key was only ever read by the Fenring and the Cultist. As a wolf or an Ulv it did nothing. All four howl now, and the wolf and the Ulv use the creature's real howl animation - the sound is carried inside that animation, so it lands at the moment the animation means it to.
- **Fix - Fenrir form sounds no longer write into your world save:** some of the game's sound prefabs carry a networked component, and spawning one the ordinary way leaves a persistent record behind - one per claw swing. They are now spawned the way the game itself does it, and leave nothing.
### v1.4.23
- **Fix - Trol clients could not chop trees or mine rocks with their fists:** the fist bonus (chop and pickaxe damage, and the tool tier that grows with the bosses) was applied on whichever machine owned the tree or rock - usually the host - where the hit did not belong to the local player, so it only ever worked for the host. It is now applied on the attacking player's own machine before the hit is sent. Thanks to the players who reported it.
- **New - Configuration is synced from the server:** every gameplay setting now follows the server's value in multiplayer, and is locked in Configuration Manager for players who are not admins. Keybinds and the purely cosmetic settings (eye and claw colours, glow, model rotation and offsets, the Head Fire VFX and stamina-bar toggles, debug logging) stay local, so each player keeps their own.
### v1.4.22
- **Fix - Other players saw Fenrir forms standing silent:** every form's attacks - the Fenring's claws, the Cultist's claws and flames, the Wolf's and the Ulv's bites - were only ever triggered on the transformed player's own Animator, so onlookers saw the form run but never swing. The attacks now reach every other client, along with the opening sound of each swing and the howls. The Cultist's flame breath, its roar and the fire itself are shown to onlookers too. The sounds of the impact itself and the Fenring's jump are still heard only by the player who makes them.
- **Fix - Fenrir players turned back to human at every sunrise, even with a form the day allows:** after the Queen the Fenring form (and the Wolf after Bonemass, the Cultist after Fader) is meant to work day and night, but sunrise took it away regardless. Only forms granted for the night alone are taken back now, and "The beast is tired" no longer blocks the daytime forms either. Thanks to the tester who noticed it.
- **Fix - The Aswid's Blood Refinery had the insertion sounds the wrong way round:** flesh and bone played each other's sound. They are swapped.
### v1.4.21
- **Fix - Other players saw Moder, the Drake and Fader at full size no matter what:** the dragon forms' own size (Moder's shrink included) was only ever applied on the transformed player's own screen — every other client built the remote copy at the prefab's raw scale. Two Skadi players who both turned into Moder each saw themselves correctly and the other one full-sized. Thanks to the tester who caught it from a second Skadi.
- **Fix - Drake and Moder's bite, claw and breath attacks played no animation for onlookers:** the attack trigger was only ever set on the transforming player's own Animator, so everyone else saw the form fly, walk and idle but never actually swing or breathe. The trigger now reaches every other client too.
- **Fix - Sverm Ravager Strain was invisible to everyone but the player using it:** the whole form — the model, the hidden human body, the attacks — was built entirely around the local player and never told the ZDO it was active. Other players saw a Sverm standing still for the whole two minutes with no Brute in sight. It is now networked the same way the Skadi and Fenrir forms already are.
- **Fix - The Sverm's dorsal spines were mounted up over the shoulders, onto the face:** the crest was based at its mount bone and grown upward from there, which reached past the head once the Full Crest size (Queen tier on) came in. It is now centred on the bone instead, with a live "Offset Y" knob under `[Sverm - Dorsal Spines]` in Configuration Manager for any further nudging. Thanks to the tester who sent the screenshot.
- **Changed - The Sverm's dorsal spines are 30% smaller:** 0.45 m down to 0.315 m from Moder to the Queen, 0.8 m down to 0.56 m from the Queen on.
### v1.4.20
- **Fix - A refused race building still took your materials:** building something your race is not allowed to build, or before its boss has fallen, showed the refusal and then charged the full cost anyway — a non-Sverm trying the Brood Mound got "Only the Sverm can raise a hive." and lost 40 wood and 20 resin. The refusal stopped the building, but Valheim takes the cost in a separate step that never heard about it. Now a refused building costs nothing, no stamina included. This covered every locked building in the mod: the Sverm hive and market (and the one-hive-per-area limit), the Skadi golem, the Dvergar contract bank and barrel, the Trenta Elder Root and the Trol totem. Thanks to the tester who noticed the wood going missing.
- **Fix - On a gamepad the Skadi cast the Cold Spell every time she built:** the spell sits on the pad's secondary attack button, which Valheim also uses to remove pieces (Classic layout) or place them (Alt 2). Every piece built or removed also cast the spell and drained stamina, which made building nearly impossible. The spell no longer casts while you hold the hammer, hoe or cultivator — on the keyboard as well, where middle mouse is Remove.
- **Changed - On a gamepad the Cold Spell now casts bare-handed only:** the pad has no separate key for the spell, so with a weapon, shield, torch or tool in hand the button goes back to that item's own secondary attack, as it does in vanilla. Previously both fired together. Bare-handed, the spell casts without the unarmed kick. Keyboard players are unaffected: the Cold Spell key works as before. Thanks to the tester who reported it from a controller.
Versions before v1.4.20 are no longer listed here — see the [wiki's release notes](https://wiki.aledanidev.ovh/release-notes) for the full history back to v1.0.0.
![Furling](https://wiki.aledanidev.ovh/assets/images/fur.gif) ![Furling](https://wiki.aledanidev.ovh/assets/images/fur.gif)

View file

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

View file

@ -47,6 +47,13 @@ $version = (Get-Content $Manifest -Raw | ConvertFrom-Json).version_number
# them, because they work on the wiki and on the git host. # them, because they work on the wiki and on the git host.
$readmeText = [System.IO.File]::ReadAllText((Resolve-Path $Readme).Path) $readmeText = [System.IO.File]::ReadAllText((Resolve-Path $Readme).Path)
$readmeText = [regex]::Replace($readmeText, '\[([^\]]+)\]\(#[^)]*\)', '$1') $readmeText = [regex]::Replace($readmeText, '\[([^\]]+)\]\(#[^)]*\)', '$1')
# Thunderstore refuses a README over 100000 characters (hit at v1.6.7). Stop here rather than
# ship a zip the upload rejects: cut the oldest changelog versions in README.md and move the
# "Versions before vX are no longer listed here" line up with them. The wiki keeps them all.
if ($readmeText.Length -gt 100000) {
throw "README.md is $($readmeText.Length) characters; Thunderstore allows 100000. Cut the oldest changelog versions in README.md."
}
$packagedReadme = Join-Path ([System.IO.Path]::GetTempPath()) ("RacesOfValheim_README_" + [guid]::NewGuid().ToString('N') + ".md") $packagedReadme = Join-Path ([System.IO.Path]::GetTempPath()) ("RacesOfValheim_README_" + [guid]::NewGuid().ToString('N') + ".md")
[System.IO.File]::WriteAllText($packagedReadme, $readmeText, (New-Object System.Text.UTF8Encoding($false))) [System.IO.File]::WriteAllText($packagedReadme, $readmeText, (New-Object System.Text.UTF8Encoding($false)))

View file

@ -0,0 +1,89 @@
"""Paint the Eldividarkista (Alfar fire chest) and render its preview and hammer icon.
Usage: py -3.14 -I paint_fire_chest.py <pylib> <scripts dir> <work dir>
<work dir> must hold tex/Crate_d.png and crate_0.obj / crate_2.obj (body, lid) exported from
dvergrprops_crate in bundle c4210710 (see extract_carto.py for the export). Writes
AlfarFireChest_d.png and AlfarFireChest_icon.png there; copy both to
JotunnModStub/Assets/AlfarFireChest/."""
import sys, os, math
sys.path.insert(0, sys.argv[1]); sys.path.insert(0, sys.argv[2])
import numpy as np
from PIL import Image, ImageFilter
from render_obj import render
d = sys.argv[3]
src = Image.open(os.path.join(d,"tex","Crate_d.png")).convert("RGB")
S = 256
up = np.asarray(src.resize((S,S), Image.BICUBIC), dtype=np.float32)/255
lum = up @ np.array([0.3,0.59,0.11])
# normalise the wood's shading into 0..1 so the brace and frame keep their relief
lo, hi = np.percentile(lum, 3), np.percentile(lum, 97)
t = np.clip((lum-lo)/(hi-lo), 0, 1)
rng = np.random.default_rng(7)
grain = np.asarray(Image.fromarray((rng.random((S,S))*255).astype(np.uint8)).filter(ImageFilter.GaussianBlur(0.8)), dtype=np.float32)/255
# the panels: plain brushed plates, the wood's planks and X-brace flattened away
brushed = np.asarray(Image.fromarray((rng.random((S,S))*255).astype(np.uint8)).resize((S//32,S), Image.BICUBIC).resize((S,S), Image.BICUBIC), dtype=np.float32)/255
iron = np.array([0.17,0.18,0.20])[None,None,:] * (0.85 + 0.3*brushed)[...,None] * (0.92 + 0.16*t)[...,None]
# the raised frame and brace become copper: every triangle lying on the outer shell of the body
# or lid (|x|, |z| or y at the extreme) paints its UV area into the copper mask
from PIL import ImageDraw
from render_obj import load_obj
mask = Image.new("L", (S,S), 0); md = ImageDraw.Draw(mask)
for name in ("crate_0.obj","crate_2.obj"):
v, vt, faces = load_obj(os.path.join(d,name))
mn, mx = v.min(0), v.max(0)
for f in faces:
pv = np.array([v[i] for i,_ in f]); c = pv.mean(0)
n = np.cross(pv[1]-pv[0], pv[2]-pv[0]); nl = np.linalg.norm(n)
if nl == 0: continue
n = n/nl; ax = int(np.argmax(np.abs(n)))
outer = (abs(c[ax]-mx[ax]) < 0.012) or (abs(c[ax]-mn[ax]) < 0.012)
if ax != 1 and not outer: continue
if ax == 1 and name == "crate_0.obj": continue # body top/bottom: skip
if ax == 1 and not outer: continue
uv = [(vt[j][0]*S, (1-vt[j][1])*S) for _,j in f]
md.polygon(uv, fill=255)
mask = mask.filter(ImageFilter.GaussianBlur(0.6))
mask.save(os.path.join(d,"copper_mask.png"))
cu = (np.asarray(mask, dtype=np.float32)/255)[...,None]
copper = np.array([0.30,0.17,0.10]) * (0.8 + 0.4*t[...,None])
iron = iron*(1-cu) + copper*cu
iron *= (0.9 + 0.2*grain)[...,None]
# soot: a warm brown tint creeping into the darkest texels
soot = np.clip(0.35 - t, 0, 0.35)/0.35
iron = iron*(1-0.25*soot[...,None]) + np.array([0.12,0.06,0.03])*0.25*soot[...,None]
out = np.clip(iron,0,1)
Image.fromarray((out*255).astype(np.uint8)).save(os.path.join(d,"AlfarFireChest_d.png"))
# a unit cube OBJ for the grate bars and the glow plate
cube = """v -0.5 -0.5 -0.5\nv 0.5 -0.5 -0.5\nv 0.5 0.5 -0.5\nv -0.5 0.5 -0.5\nv -0.5 -0.5 0.5\nv 0.5 -0.5 0.5\nv 0.5 0.5 0.5\nv -0.5 0.5 0.5\nvt 0 0\nf 1/1 2/1 3/1 4/1\nf 5/1 8/1 7/1 6/1\nf 1/1 5/1 6/1 2/1\nf 2/1 6/1 7/1 3/1\nf 3/1 7/1 8/1 4/1\nf 4/1 8/1 5/1 1/1\n"""
open(os.path.join(d,"cube.obj"),"w").write(cube)
tex = Image.open(os.path.join(d,"AlfarFireChest_d.png"))
# the crate stretched into a chest: 1.6x as wide, 0.8x as deep (AlfarFireChest.Stretch)
SX, SZ = 1.6, 0.8
parts=[{'obj':os.path.join(d,'crate_0.obj'),'tex':tex,'scale':(1.5*SX,1.5,1.5*SZ)},
{'obj':os.path.join(d,'crate_2.obj'),'tex':tex,'scale':(1.5*SX,1.5,1.5*SZ),'offset':(0,0.81,0)}]
# grate on the +z face: glow plate, frame, bars (sizes in metres, mirrored like the OBJ x)
FZ = 0.515*SZ; GW, GH, GY = 0.62*SX, 0.36, 0.42
glow = (1.0, 0.45, 0.12)
bar = (0.16,0.15,0.15)
parts.append({'obj':os.path.join(d,'cube.obj'),'color':glow,'emissive':True,'scale':(GW,GH,0.01),'offset':(0,GY,FZ+0.005)})
T = 0.035
for x in (-GW/2, GW/2):
parts.append({'obj':os.path.join(d,'cube.obj'),'color':bar,'scale':(T,GH+T,0.04),'offset':(x,GY,FZ+0.02)})
for y in (GY-GH/2, GY+GH/2):
parts.append({'obj':os.path.join(d,'cube.obj'),'color':bar,'scale':(GW+T,T,0.04),'offset':(0,y,FZ+0.02)})
n = 10
for i in range(1,n):
x = -GW/2 + GW*i/n
parts.append({'obj':os.path.join(d,'cube.obj'),'color':bar,'scale':(0.022,GH,0.03),'offset':(x,GY,FZ+0.02)})
parts.append({'obj':os.path.join(d,'cube.obj'),'color':bar,'scale':(GW,0.022,0.03),'offset':(0,GY,FZ+0.022)})
render(parts, os.path.join(d,'prev_fire.png'), yaw=-30, pitch=-20, light=(0.4,0.8,0.6))
render(parts, os.path.join(d,'prev_fire_side.png'), yaw=-80, pitch=-15, light=(0.4,0.8,0.6))
from PIL import Image as I
tiles=[]
for k,yw in enumerate((-30,60,150,240)):
p=os.path.join(d,f'_q{k}.png'); render(parts,p,size=256,yaw=yw,pitch=-20,light=(0.4,0.8,0.6)); tiles.append(I.open(p))
sheet=I.new('RGBA',(1024,256))
for k,tl in enumerate(tiles): sheet.paste(tl,(k*256,0))
sheet.save(os.path.join(d,'prev_sheet.png'))
render(parts, os.path.join(d,'AlfarFireChest_icon.png'), size=128, yaw=160, pitch=-22, bg=(0,0,0,0), light=(0.3,0.8,0.7))

View file

@ -0,0 +1,45 @@
"""Paint the Inngangskista (Alfar input chest) and render its preview and hammer icon.
Usage: py -3.14 -I paint_input_chest.py <pylib> <scripts dir> <work dir>
<work dir> must hold tex/dvergrchestWorn_d.png, tex/anvil.png and
TreasureChest_dvergrtown__stonechest.obj / __stonechesttop_closed.obj, exported from bundle c4210710.
Writes AlfarInputChest_d.png and AlfarInputChest_icon.png; copy both to
JotunnModStub/Assets/AlfarInputChest/. The trim is recoloured in code (AlfarInputChest.Trim)."""
import sys, os
sys.path.insert(0, sys.argv[1]); sys.path.insert(0, sys.argv[2])
import numpy as np
from PIL import Image, ImageFilter
from render_obj import render
d = sys.argv[3]
S = 128
src = Image.open(os.path.join(d,"tex","dvergrchestWorn_d.png")).convert("RGB")
up = np.asarray(src.resize((S,S), Image.BICUBIC), dtype=np.float32)/255
lum = up @ np.array([0.3,0.59,0.11])
lo, hi = np.percentile(lum, 3), np.percentile(lum, 97)
t = np.clip((lum-lo)/(hi-lo), 0, 1)
rng = np.random.default_rng(11)
brushed = np.asarray(Image.fromarray((rng.random((S,S))*255).astype(np.uint8)).resize((S,S//16), Image.BICUBIC).resize((S,S), Image.BICUBIC), dtype=np.float32)/255
# steel-blue plates: the planks' seams survive as faint plate joints
steel = np.array([0.12,0.17,0.24])[None,None,:] * (0.85 + 0.25*brushed)[...,None] * (0.8 + 0.35*t)[...,None]
Image.fromarray((np.clip(steel,0,1)*255).astype(np.uint8)).save(os.path.join(d,"AlfarInputChest_d.png"))
TRIM = (1.25,1.3,1.35) # AlfarInputChest.Trim
K = 1.5*1.2 # the mesh scale times the chest's 1.2
LIDTOP, HX, HZ = 0.48*K, 0.42*K, 0.24*K
INSET, W = 0.10, 0.03 # AlfarInputChest inlay
cyan = (0.35,0.9,1.0)
panel = Image.open(os.path.join(d,"AlfarInputChest_d.png")); metal = Image.open(os.path.join(d,"tex","anvil.png"))
parts = [{'obj':os.path.join(d,'TreasureChest_dvergrtown__'+n+'.obj'),'texs':[metal,panel],'colors':[TRIM,(1,1,1)],'scale':(K,K,K)}
for n in ('stonechest','stonechesttop_closed')]
cube = os.path.join(d,'cube.obj')
ix, iz = HX-INSET, HZ-INSET
for z in (-iz, iz): parts.append({'obj':cube,'color':cyan,'emissive':True,'scale':(2*ix+W,0.01,W),'offset':(0,LIDTOP+0.004,z)})
for x in (-ix, ix): parts.append({'obj':cube,'color':cyan,'emissive':True,'scale':(W,0.01,2*iz),'offset':(x,LIDTOP+0.004,0)})
tiles = []
for k,yw in enumerate((-30,60,150,240)):
p = os.path.join(d,f'_i{k}.png'); render(parts,p,size=256,yaw=yw,pitch=-30,light=(0.4,0.8,0.6)); tiles.append(Image.open(p))
sheet = Image.new('RGBA',(1024,256))
for k,tl in enumerate(tiles): sheet.paste(tl,(k*256,0))
sheet.save(os.path.join(d,'prev_input.png'))
render(parts, os.path.join(d,'AlfarInputChest_icon.png'), size=128, yaw=160, pitch=-28, bg=(0,0,0,0), light=(0.3,0.8,0.7))

154
scripts/paint_nexus.py Normal file
View file

@ -0,0 +1,154 @@
"""Paint the Ljoskjarne's pyramid face (Alfar Nexus) and render a preview.
Usage: py -3.14 -I paint_nexus.py <pylib> <scripts dir> <work dir>
<work dir> must hold runes/RuneTile_e.png (Valheim's glyphs, the Ashlands rune tile's glow mask),
metal/Ironbeam_d.png, both from bundle c4210710. Writes
AlfarNexus_face.png (one face, u 0..1 along the base, v 1 at the apex), AlfarNexus_glow.png (its glow
map: the cyan seam down the middle), AlfarNexus_n.png (its normal map), AlfarNexus_icon.png and
prev_nexus.png; copy the face, glow, normal map and icon to
JotunnModStub/Assets/AlfarNexus/."""
import sys, os, math
sys.path.insert(0, sys.argv[1]); sys.path.insert(0, sys.argv[2])
import numpy as np
from PIL import Image, ImageFilter, ImageChops
from render_obj import render
d = sys.argv[3]
S = 512
# --- the glyphs: every blob of the rune tile's glow mask, cut out with its bounding box
mask = np.asarray(Image.open(os.path.join(d,"runes","RuneTile_e.png")).convert("L"), dtype=np.float32)/255
grown = np.asarray(Image.fromarray((mask>0.15).astype(np.uint8)*255).filter(ImageFilter.MaxFilter(15)))>0
seen = np.zeros_like(grown); blobs = []
H, W = grown.shape
for y in range(H):
for x in range(W):
if grown[y,x] and not seen[y,x]:
stack=[(y,x)]; seen[y,x]=True; ys=[];xs=[]
while stack:
cy,cx=stack.pop(); ys.append(cy); xs.append(cx)
for ny,nx in ((cy+1,cx),(cy-1,cx),(cy,cx+1),(cy,cx-1)):
if 0<=ny<H and 0<=nx<W and grown[ny,nx] and not seen[ny,nx]: seen[ny,nx]=True; stack.append((ny,nx))
y0,y1,x0,x1=min(ys)+7,max(ys)-7,min(xs)+7,max(xs)-7
if (y1-y0)*(x1-x0) > 150: blobs.append((x0,y0,x1+1,y1+1))
tall = [b for b in blobs if (b[3]-b[1]) > 2.5*(b[2]-b[0])]
wide = [b for b in blobs if b not in tall and (b[2]-b[0]) < 200]
glyph = lambda b: Image.fromarray((mask[b[1]:b[3], b[0]:b[2]]*255).astype(np.uint8))
print("glyphs: tall", len(tall), "short", len(wide))
# --- the plate: three riveted steel panels per face, split by two straight seams and framed by a
# seam along the sloping edges, each brushed in its own streaks toward the apex. Straight lines and
# streaks read as metal; the iron beam's blotches stay only as a faint hint of wear.
def norm(a): return (a - a.mean())/(a.std() + 1e-6)
Y, X = np.mgrid[0:S, 0:S].astype(np.float32) # Y from the apex down
edge = Y/2 - np.abs(X - (S-1)/2) # pixels inside the sloping edges
SEAMS_Y = (int(S*0.31), int(S*0.635)) # above the tall runes, between them and the rows
FRAME = 12 # the edge seam, this far inside the edge
band = (Y >= SEAMS_Y[0]).astype(int) + (Y >= SEAMS_Y[1]).astype(int)
def brushed(seed):
n = np.random.default_rng(seed).normal(size=(S + 120, S)).astype(np.float32)
c = np.cumsum(n, axis=0); n = (c[120:] - c[:-120])/120 # long streaks down the face
return norm(n + 0.5*np.roll(n, 1, axis=1))
streaks = np.choose(band, [brushed(1), brushed(2), brushed(3)])
iron = Image.open(os.path.join(d,"metal","Ironbeam_d.png")).convert("L").crop((176,90,256,250))
mottle = norm(np.asarray(iron.resize((S,S), Image.BICUBIC).filter(ImageFilter.GaussianBlur(10)), dtype=np.float32))
seam_lines = np.zeros((S,S), np.float32) # 1 in the groove, soft at its sides
for y in SEAMS_Y: seam_lines = np.maximum(seam_lines, np.clip(2 - np.abs(Y - y), 0, 1))
seam_lines = np.maximum(seam_lines, np.clip(2 - np.abs(edge - FRAME), 0, 1)*(Y > FRAME*2))
rivets = np.zeros((S,S), np.float32) # domes, 2 cm across
def rivet(cx, cy, r=5):
if edge[int(cy), int(cx)] < FRAME + 2 or abs(cx - (S-1)/2) < 30: return
rivets[:] = np.maximum(rivets, np.sqrt(np.clip(1 - ((X-cx)**2 + (Y-cy)**2)/r**2, 0, 1)))
for y, below in zip(SEAMS_Y, (True, False)): # the rune rows start just under the second seam
for cy in ((y - 8, y + 8) if below else (y - 8,)):
for cx in np.arange(S/2 % 30, S, 30): rivet(cx, cy)
for cy in np.arange(FRAME*2 + 20, S - 12, 30): # down both sloping edges
for side in (-1, 1): rivet((S-1)/2 + side*(cy/2 - FRAME - 9), cy)
tone = 0.30 + np.choose(band, [0.015, -0.01, 0.005]) + 0.022*streaks + 0.012*mottle
tone = tone*(1 - 0.5*seam_lines) + 0.08*rivets
stone = tone[...,None]*np.array([0.95,1.0,1.08])
# --- lay the glyphs out inside the face's triangle (in image space the apex is at the top middle)
ink = Image.new("L", (S,S), 0)
inside = lambda x, y: abs(x - S/2) < (y/S)*S/2 - 14 # y measured from the apex
GAP = 26 # half-width kept clear for the seam
# the tall columns flank the seam
for i, b in enumerate(tall[:3]):
g = glyph(b); h = int(S*0.28); w = max(1, int(g.width*h/g.height))
g = g.resize((w,h), Image.LANCZOS)
for side in (-1, 1):
x = int(S/2 + side*(GAP + 8 + i*(w+10)) - (w if side < 0 else 0)); y = int(S*0.34)
if inside(x, y) and inside(x+w, y): ink.paste(g, (x,y), g)
# short clusters in rows toward the base
k = 0
for row, y in enumerate(range(int(S*0.66), S-40, 48)):
half = (y/S)*S/2 - 36 # clear of the edge rivets
x = S/2 - half
while x < S/2 + half:
g = glyph(wide[k % len(wide)]); k += 1
h = 34; w = max(1, int(g.width*h/g.height)); w = min(w, 80)
g = g.resize((w,h), Image.LANCZOS)
if abs(x + w/2 - S/2) < GAP + w/2: x = S/2 + GAP; continue
if inside(x, y) and inside(x+w, y+h): ink.paste(g, (int(x), int(y)), g)
x += w + 14
ink = ink.filter(ImageFilter.MaxFilter(3)) # thicker strokes: they are read from metres away
inkf = np.clip(np.asarray(ink, dtype=np.float32)/255*1.4, 0, 1)
# carved: a dark rim just below each line, the line itself light grey
shadow = np.asarray(ink.filter(ImageFilter.GaussianBlur(2)).transform((S,S), Image.AFFINE, (1,0,-1,0,1,-2)), dtype=np.float32)/255
face = stone*(1 - 0.45*shadow[...,None])
face = face*(1 - inkf[...,None]) + np.array([0.72,0.73,0.76])*inkf[...,None]
out = Image.fromarray((np.clip(face,0,1)*255).astype(np.uint8)) # top row is v = 1, the apex, as Unity reads a PNG
out.save(os.path.join(d,"AlfarNexus_face.png"))
# --- the glow map: one line down the middle. u runs 0.5 per metre at every height, so a band of
# constant width in u is 9 cm wide on the pyramid from base to tip.
SEAM_HALF = 11 # pixels; GAP keeps the runes clear of it
xs = np.abs(np.arange(S) - (S-1)/2)
line = np.clip((SEAM_HALF + 1 - xs)/2, 0, 1) # two pixels of soft edge
glow = np.tile(line, (S,1))
Image.fromarray((glow*255).astype(np.uint8)).convert("RGB").save(os.path.join(d,"AlfarNexus_glow.png"))
# --- the normal map, from a height field: faint streaks and wear, the panel seams, runes and the
# glowing seam's channel cut in, the rivets raised. DXT5nm, as Valheim packs it: X in alpha, Y in
# green and blue, red 255.
height = 0.12*streaks + 0.25*mottle - 1.6*seam_lines + 2.5*rivets \
- 2.2*np.asarray(ink.filter(ImageFilter.GaussianBlur(1)), dtype=np.float32)/255 \
- 1.5*np.clip((SEAM_HALF + 4 - xs)/3, 0, 1)[None,:]
gx = np.zeros_like(height); gy = np.zeros_like(height)
gx[:,1:-1] = height[:,2:] - height[:,:-2]; gy[1:-1,:] = height[2:,:] - height[:-2,:]
K = 0.35
nm = np.stack([-gx*K, gy*K, np.ones_like(height)], -1) # image y runs down, texture v up
nm /= np.linalg.norm(nm, axis=-1, keepdims=True)
packed = np.zeros((S,S,4), np.float32)
packed[...,0] = 1; packed[...,1] = packed[...,2] = nm[...,1]*0.5 + 0.5; packed[...,3] = nm[...,0]*0.5 + 0.5
Image.fromarray((packed*255).astype(np.uint8), "RGBA").save(os.path.join(d,"AlfarNexus_n.png"))
# a lit check of the normal map, light from the upper left
shade = np.clip(nm @ np.array([-0.5,0.5,0.7])/np.linalg.norm([-0.5,0.5,0.7]), 0, 1)
Image.fromarray((np.clip(face*shade[...,None]*1.6,0,1)*255).astype(np.uint8)).save(os.path.join(d,"prev_nexus_bump.png"))
# --- preview: the pyramid as AlfarNexus builds it
HGT, B, LIFT = 2.0, 1.0, 0.8 # AlfarNexusLook: 2 m tall, 2 m base, floating 0.8 m up
apex = np.array([0, LIFT+HGT, 0]); c = [np.array(p) for p in [(-B,LIFT,-B),(B,LIFT,-B),(B,LIFT,B),(-B,LIFT,B)]]
lit = np.asarray(out, dtype=np.float32)/255
lit = lit*(1-glow[...,None]) + np.array([0.35,0.75,1.0])*glow[...,None]
shown = Image.fromarray((lit*255).astype(np.uint8))
L = []; vi = 1
for i in range(4):
a, b = c[i], c[(i+1)%4]
for p in (a, b, apex): L.append("v %f %f %f" % (-p[0], p[1], p[2]))
L += ["vt 0 0", "vt 1 0", "vt 0.5 1", f"f {vi}/{vi} {vi+1}/{vi+1} {vi+2}/{vi+2}"]; vi += 3
for p in c: L.append("v %f %f %f" % (-p[0], p[1], p[2]))
L += ["vt 0 0", f"f {vi}/{3*4+1} {vi+3}/{3*4+1} {vi+2}/{3*4+1} {vi+1}/{3*4+1}"]
open(os.path.join(d,"pyramid.obj"),"w").write("\n".join(L)+"\n")
open(os.path.join(d,"ground.obj"),"w").write("v -2 0 -2\nv 2 0 -2\nv 2 0 2\nv -2 0 2\nvt 0 0\nf 1/1 2/1 3/1 4/1\n")
sh = B*0.85
open(os.path.join(d,"shadow.obj"),"w").write(
f"v {-sh} 0.005 {-sh}\nv {sh} 0.005 {-sh}\nv {sh} 0.005 {sh}\nv {-sh} 0.005 {sh}\nvt 0 0\nf 1/1 2/1 3/1 4/1\n")
parts = [{'obj':os.path.join(d,'pyramid.obj'),'tex':shown},
{'obj':os.path.join(d,'ground.obj'),'color':(0.33,0.36,0.3)},
{'obj':os.path.join(d,'shadow.obj'),'color':(0.18,0.2,0.17)}]
render(parts, os.path.join(d,'prev_nexus.png'), size=640, yaw=25, pitch=-12, light=(0.4,0.8,0.6), fit=(np.array([0,1.4,0]), 2.5))
# the hammer icon: the pyramid alone, nearly side-on so two faces show
render(parts[:1], os.path.join(d,'AlfarNexus_icon.png'), size=128, yaw=35, pitch=-12, bg=(0,0,0,0), light=(0.3,0.8,0.7))

88
scripts/render_obj.py Normal file
View file

@ -0,0 +1,88 @@
"""Tiny software renderer: render(parts, out, size, yaw, pitch, bg)
parts: list of dicts {obj: path, tex: PIL image or None, color:(r,g,b), offset:(x,y,z), scale:(sx,sy,sz), emissive:bool}
OBJ x is mirrored vs Unity: we flip x back."""
import numpy as np
from PIL import Image
import math
def load_obj(path, groups=False):
v=[];vt=[];vn=[];faces=[];gid=[];g=0;gn=0;ids={}
for l in open(path):
p=l.split()
if not p: continue
if p[0]=='g': gn+=1; g=gn
elif p[0]=='v': v.append([float(x) for x in p[1:4]])
elif p[0]=='vt': vt.append([float(x) for x in p[1:3]])
elif p[0]=='f':
idx=[]
for k in p[1:]:
a=k.split('/'); idx.append((int(a[0])-1, int(a[1])-1 if len(a)>1 and a[1] else -1))
# a group counts as a submesh only once it has faces (the export starts with an empty one)
if g not in ids: ids[g]=len(ids)
for i in range(1,len(idx)-1): faces.append((idx[0],idx[i],idx[i+1])); gid.append(ids[g])
v=np.array(v); v[:,0]*=-1
if groups: return v, np.array(vt) if vt else None, faces, gid
return v, np.array(vt) if vt else None, faces
def render(parts, out, size=512, yaw=35, pitch=25, bg=(40,44,52,255), fit=None, light=(0.4,0.8,-0.5)):
tris=[]
for P in parts:
v,vt,faces,gid=load_obj(P['obj'],groups=True)
if 'rotx' in P:
a=math.radians(P['rotx']); c,s=math.cos(a),math.sin(a)
v=v@np.array([[1,0,0],[0,c,-s],[0,s,c]]).T
v=v*np.array(P.get('scale',(1,1,1)))+np.array(P.get('offset',(0,0,0)))
# 'texs'/'colors'/'emissives' per OBJ group (submesh) override 'tex'/'color'/'emissive'
def arr(t): return np.asarray(t.convert('RGBA'),dtype=np.float32)/255 if t is not None else None
texs=[arr(t) for t in P['texs']] if 'texs' in P else None
ta0=arr(P.get('tex'))
for f,gi in zip(faces,gid):
pv=np.array([v[i] for i,_ in f]); puv=np.array([vt[j] if (vt is not None and j>=0) else (0,0) for _,j in f])
ta=texs[min(gi,len(texs)-1)] if texs is not None else ta0
col=P['colors'][min(gi,len(P['colors'])-1)] if 'colors' in P else P.get('color',(1,1,1))
em=P['emissives'][min(gi,len(P['emissives'])-1)] if 'emissives' in P else P.get('emissive',False)
tris.append((pv,puv,ta,col,em))
ay=math.radians(yaw); ap=math.radians(pitch)
Ry=np.array([[math.cos(ay),0,math.sin(ay)],[0,1,0],[-math.sin(ay),0,math.cos(ay)]])
Rx=np.array([[1,0,0],[0,math.cos(ap),-math.sin(ap)],[0,math.sin(ap),math.cos(ap)]])
R=Rx@Ry
allv=np.concatenate([t[0] for t in tris])@R.T
if fit is None:
mn=allv.min(0); mx=allv.max(0); c=(mn+mx)/2; ext=max(mx[0]-mn[0],mx[1]-mn[1])*0.55
else: c,ext=fit
img=np.zeros((size,size,4),np.float32); img[:]=np.array(bg)/255
zb=np.full((size,size),-1e9)
L=np.array(light);L=L/np.linalg.norm(L)
for pv,puv,ta,col,em in tris:
q=pv@R.T
n=np.cross(pv[1]-pv[0],pv[2]-pv[0]); nl=np.linalg.norm(n)
if nl==0: continue
n=n/nl
nv=n@R.T
shade=1.0 if em else 0.35+0.65*abs(float(n@L))
sx=(q[:,0]-c[0])/ext*size/2+size/2; sy=size/2-(q[:,1]-c[1])/ext*size/2
x0=max(int(sx.min()),0);x1=min(int(sx.max())+1,size);y0=max(int(sy.min()),0);y1=min(int(sy.max())+1,size)
if x0>=x1 or y0>=y1: continue
xs,ys=np.meshgrid(np.arange(x0,x1)+0.5,np.arange(y0,y1)+0.5)
d=(sy[1]-sy[2])*(sx[0]-sx[2])+(sx[2]-sx[1])*(sy[0]-sy[2])
if abs(d)<1e-9: continue
w0=((sy[1]-sy[2])*(xs-sx[2])+(sx[2]-sx[1])*(ys-sy[2]))/d
w1=((sy[2]-sy[0])*(xs-sx[2])+(sx[0]-sx[2])*(ys-sy[2]))/d
w2=1-w0-w1
m=(w0>=0)&(w1>=0)&(w2>=0)
if not m.any(): continue
z=w0*q[0,2]+w1*q[1,2]+w2*q[2,2]
z=-z
sub=zb[y0:y1,x0:x1]; m&=z>sub
if not m.any(): continue
if ta is not None:
u=(w0*puv[0,0]+w1*puv[1,0]+w2*puv[2,0])%1; vv=(w0*puv[0,1]+w1*puv[1,1]+w2*puv[2,1])%1
th,tw=ta.shape[:2]
px=np.clip((u*tw).astype(int),0,tw-1); py=np.clip(((1-vv)*th).astype(int),0,th-1)
rgb=ta[py,px,:3]
else: rgb=np.ones(xs.shape+(3,))
rgb=rgb*np.array(col)*shade
sub[m]=z[m]
reg=img[y0:y1,x0:x1]
reg[m,:3]=np.clip(rgb[m],0,1); reg[m,3]=1
Image.fromarray((img*255).astype(np.uint8)).save(out)