diff --git a/JotunnModStub/Alfar/AlfarArchon.cs b/JotunnModStub/Alfar/AlfarArchon.cs
index 0be4415..079d7a6 100644
--- a/JotunnModStub/Alfar/AlfarArchon.cs
+++ b/JotunnModStub/Alfar/AlfarArchon.cs
@@ -119,7 +119,10 @@ namespace RacesOfValheim
if (Time.time >= nextPulse)
{
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);
}
}
diff --git a/JotunnModStub/Alfar/AlfarChestGlow.cs b/JotunnModStub/Alfar/AlfarChestGlow.cs
new file mode 100644
index 0000000..dc529ff
--- /dev/null
+++ b/JotunnModStub/Alfar/AlfarChestGlow.cs
@@ -0,0 +1,79 @@
+using UnityEngine;
+
+namespace RacesOfValheim
+{
+ ///
+ /// 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.
+ ///
+ 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();
+ 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);
+ }
+ }
+}
diff --git a/JotunnModStub/Alfar/AlfarChests.cs b/JotunnModStub/Alfar/AlfarChests.cs
index e8fc1d9..9efa86a 100644
--- a/JotunnModStub/Alfar/AlfarChests.cs
+++ b/JotunnModStub/Alfar/AlfarChests.cs
@@ -61,12 +61,15 @@ namespace RacesOfValheim
public static void Register()
{
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",
- 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 build, string iconResource)
{
GameObject source = PrefabManager.Cache.GetPrefab("piece_chest_wood");
if (source == null)
@@ -91,15 +94,19 @@ namespace RacesOfValheim
}
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();
- if (container != null) container.m_name = display;
+ if (container != null) container.m_name = hoverName;
Piece piece = prefab.GetComponent();
if (piece == null) { Jotunn.Logger.LogWarning("[Alfar] The chest has no Piece: " + pieceName); return; }
piece.m_name = display;
piece.m_description = description;
- AlfarConstructs.Tint(prefab, tint);
+ // 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
{
@@ -107,7 +114,7 @@ namespace RacesOfValheim
Description = description,
PieceTable = PieceTables.Hammer,
Category = PieceCategories.Crafting,
- Icon = piece.m_icon,
+ Icon = icon,
Requirements = requirements.ToArray(),
}));
@@ -130,5 +137,12 @@ namespace RacesOfValheim
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));
+ }
}
}
diff --git a/JotunnModStub/Alfar/AlfarDroneAI.cs b/JotunnModStub/Alfar/AlfarDroneAI.cs
index 9da8077..b319ceb 100644
--- a/JotunnModStub/Alfar/AlfarDroneAI.cs
+++ b/JotunnModStub/Alfar/AlfarDroneAI.cs
@@ -58,6 +58,13 @@ namespace RacesOfValheim
public const string KeyStatus = "RoV_alfarStatus";
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";
+
/// Every drone alive in the loaded zones: the repairs look at each other through it.
public static readonly List All = new List();
@@ -141,6 +148,7 @@ namespace RacesOfValheim
private float m_nextFightScan;
private float m_fightUntil;
+ private bool m_fighting;
private ZNetView m_nview;
private Character m_character;
@@ -168,6 +176,11 @@ namespace RacesOfValheim
private ZDOID m_sortDest;
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 float m_nextPlan;
private float m_jobDeadline;
@@ -200,6 +213,16 @@ namespace RacesOfValheim
All.Add(this);
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()
@@ -293,7 +316,17 @@ namespace RacesOfValheim
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;
+ // 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();
+ if (target != null && !target.IsDead() && !InFightReach(target))
+ {
+ m_ai.MakeTame();
+ target = null;
+ }
+
if (target != null && !target.IsDead())
{
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_nextPlan = 0f; // the fight moved it; plan afresh the moment it hands back
SetStatus("Fighting.");
return true;
}
+ /// Close to the drone, and not past the edge of the base it works.
+ 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
/// Everything. Returns what MonsterAI.UpdateAI would have returned.
@@ -393,17 +445,34 @@ namespace RacesOfValheim
Scan(anchor.Value);
ExpirePenalties();
+ CheckIdleKiln();
// A harvest is in progress: wait for the drops to land, then gather them and replant.
+ Job job;
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 = "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 (m_payload.Count > 0) { m_job = PlanDelivery(anchor.Value); return; }
+ 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;
+ }
+
+ private Job PlanWork(Vector3 anchor)
+ {
// 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
@@ -419,15 +488,7 @@ namespace RacesOfValheim
// base: repairs, the fields, and last the tidying of the entry chest.
Job job = PlanRescue();
job = job ?? PlanCollect() ?? PlanFuel() ?? PlanLoad();
- job = job ?? PlanRepair(anchor.Value) ?? PlanFarm(anchor.Value) ?? PlanSort();
-
- if (job != null && (m_job == null || m_job.Kind != job.Kind || m_job.Target != job.Target))
- {
- m_jobDeadline = Time.time + JobTimeout;
- }
- if (m_job != null && !ReferenceEquals(m_job, job)) Release(m_job.Claim);
- if (job != null) Claim(job.Claim);
- m_job = job;
+ return job ?? PlanRepair(anchor) ?? PlanFarm(anchor) ?? PlanSort();
}
///
@@ -556,7 +617,7 @@ namespace RacesOfValheim
Kind = "collect",
Target = best.Id,
Claim = best.Id,
- Point = best.Position,
+ Point = ApproachPoint(best),
Hurry = true,
Label = "Saving the food",
};
@@ -587,7 +648,7 @@ namespace RacesOfValheim
Kind = "collect",
Target = best.Id,
Claim = best.Id,
- Point = best.Position,
+ Point = ApproachPoint(best),
Label = "Collecting",
};
}
@@ -717,20 +778,37 @@ namespace RacesOfValheim
// coal, so gating the delivery on free slots sent the servant back to the chest with
// the coal it had just fetched - and then PlanFuel sent it out for the same coal again,
// forever. AcceptsAnything already asks the right question of both doors.
+ // 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);
- if (station != null && station.Alive && station.Operable && AcceptsAnything(station))
+ if (station != null && station.Alive && station.Operable && AcceptsAnything(station) && !unreachable)
{
return new Job
{
Kind = "deposit_station",
Target = target,
- Point = station.Position,
+ Point = ApproachPoint(station),
Label = "Loading " + Describe(),
};
}
// The station is gone, full or cold. The goods are ours to put back, not to hold.
m_nview.GetZDO().Set(KeyTarget, ZDOID.None);
+
+ // 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();
@@ -763,7 +841,7 @@ namespace RacesOfValheim
{
Kind = "deposit_station",
Target = consumer.Id,
- Point = consumer.Position,
+ Point = ApproachPoint(consumer),
Label = "Loading " + Describe(),
};
}
@@ -1422,16 +1500,25 @@ namespace RacesOfValheim
if (inventory == null) return null;
string sigil = AlfarSigil.PrefabName;
+ bool spoke = false;
foreach (ItemDrop.ItemData item in inventory.GetAllItems())
{
if (item == null || item.m_dropPrefab == null) continue;
string name = item.m_dropPrefab.name;
if (name == sigil) continue;
- if (!IsWood(name) && AnyStationAccepts(name)) continue;
+ if (!IsWood(name) && AnyStationAccepts(name))
+ {
+ if (!spoke) spoke = Say("rov_msg_alfar_drone_sort_keep", name, KeepRepeatSeconds);
+ continue;
+ }
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_sortDest = ZdoOf(destination);
@@ -1447,6 +1534,119 @@ namespace RacesOfValheim
return null;
}
+ // ================================================================ speech
+
+ /// 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.
+ private static readonly Dictionary s_nextMention = new Dictionary();
+ private const float NowhereRepeatSeconds = 300f;
+ private const float KeepRepeatSeconds = 1800f;
+ private const float SpeechRange = 40f;
+
+ /// 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.
+ 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;
+ }
+
+ /// 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.
+ 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() : 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);
+ }
+
+ ///
+ /// 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.
+ ///
+ 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();
+ string stationName = piece != null ? piece.m_name : "";
+ if (Say("rov_msg_alfar_drone_kiln_wood", misplaced, NowhereRepeatSeconds, stationName)) return;
+ }
+ }
+
+ /// Wood the station would take, lying in the entry chest or a storage chest.
+ 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()
{
if (m_sortItem == null || m_sortDest == ZDOID.None) return false;
@@ -1467,6 +1667,169 @@ namespace RacesOfValheim
// ================================================================ moving
/// Vanilla pathing, through the private MoveTo. True the moment it has arrived.
+ /// 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.
+ public static void DebugReport(Player player)
+ {
+ var lines = new List();
+ 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);
+ }
+ }
+
+ /// 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.
+ private IEnumerable 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();
+ 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 pieces = AllPiecesField != null ? AllPiecesField.GetValue(null) as List : 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 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();
+ 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}";
+ }
+ }
+
+ ///
+ /// 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.
+ ///
+ 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())
+ {
+ 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)
{
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",
};
- private static bool IsWood(string prefabName) => s_woodFamily.Contains(prefabName);
+ internal static bool IsWood(string prefabName) => s_woodFamily.Contains(prefabName);
///
/// The first thing a station will take, and the chest it is in: raw material from the ENTRY chest
diff --git a/JotunnModStub/Alfar/AlfarDrones.cs b/JotunnModStub/Alfar/AlfarDrones.cs
index 2564a4f..669d0c0 100644
--- a/JotunnModStub/Alfar/AlfarDrones.cs
+++ b/JotunnModStub/Alfar/AlfarDrones.cs
@@ -105,6 +105,10 @@ namespace RacesOfValheim
BaseAI ai = prefab.GetComponent();
if (ai != null) ai.m_randomMoveRange = 5f;
+ // A flyer's MoveTo lifts its goal to m_flyAltitudeMin above whatever solid is under it,
+ // the rock top included: at the vanilla height the miners hovered over a deposit out of
+ // reach and never struck.
+ if (ai != null && miner) { ai.m_flyAltitudeMin = 0.5f; ai.m_flyAltitudeMax = 2f; }
foreach (CharacterDrop drops in prefab.GetComponentsInChildren(true))
{
@@ -251,28 +255,89 @@ namespace RacesOfValheim
public float Radius = 12f;
public float LiveSeconds = 120f;
- private float born;
+ // The job lives in the drone's ZDO, not only in these fields: Valheim destroys a creature
+ // when its zone unloads and builds a fresh one when the zone comes back, and the fresh
+ // one had a zero Centre, so it searched around the world origin and stood idle. The
+ // birth time is network time, so a rebuilt drone does not get a new two minutes either.
+ private static readonly int CentreKey = "rov_graf_centre".GetStableHashCode();
+ private static readonly int RadiusKey = "rov_graf_radius".GetStableHashCode();
+ private static readonly int LifeKey = "rov_graf_life".GetStableHashCode();
+ private static readonly int BornKey = "rov_graf_born".GetStableHashCode();
+
+ private const float Reach = 4f;
+
+ private bool loaded;
+ private double bornAt;
private float nextStrike;
private Component target;
+ private float lastDistance = -1f;
+ private int strikes;
+ private string lastHit = "none";
+
+ public static readonly List All = new List();
+
+ private void OnEnable() { All.Add(this); }
+ private void OnDisable() { All.Remove(this); }
private static readonly System.Reflection.MethodInfo MoveToMethod =
AccessTools.Method(typeof(BaseAI), "MoveTo", new[] { typeof(float), typeof(Vector3), typeof(float), typeof(bool) });
- private void Start()
+ private static double Now => ZNet.instance != null ? ZNet.instance.GetTimeSeconds() : Time.time;
+
+ /// Called by the throw right after the drone is made: the job, into the ZDO.
+ public void Assign(Vector3 centre, float radius, float liveSeconds)
{
- born = Time.time;
+ Centre = centre;
+ Radius = radius;
+ LiveSeconds = liveSeconds;
+ bornAt = Now;
+ loaded = true;
+
+ ZNetView nview = GetComponent();
+ if (nview == null || !nview.IsValid()) return;
+ ZDO zdo = nview.GetZDO();
+ zdo.Set(CentreKey, centre);
+ zdo.Set(RadiusKey, radius);
+ zdo.Set(LifeKey, liveSeconds);
+ zdo.Set(BornKey, (long)(bornAt * 1000.0));
+ }
+
+ ///
+ /// A drone rebuilt from its ZDO reads its job back. One with no job at all (thrown by an
+ /// older build) digs around where it stands, which is where it was thrown.
+ ///
+ private void Load()
+ {
+ loaded = true;
+ ZNetView nview = GetComponent();
+ ZDO zdo = nview != null && nview.IsValid() ? nview.GetZDO() : null;
+ long born = zdo != null ? zdo.GetLong(BornKey, 0L) : 0L;
+ if (born == 0L)
+ {
+ Centre = transform.position;
+ bornAt = Now;
+ return;
+ }
+ Centre = zdo.GetVec3(CentreKey, transform.position);
+ Radius = zdo.GetFloat(RadiusKey, Radius);
+ LiveSeconds = zdo.GetFloat(LifeKey, LiveSeconds);
+ bornAt = born / 1000.0;
}
public bool Tick(MonsterAI ai, float dt)
{
- if (Time.time - born >= LiveSeconds)
+ if (!loaded) Load();
+
+ if (Now - bornAt >= LiveSeconds)
{
ZNetView nview = GetComponent();
if (nview != null && nview.IsValid() && nview.IsOwner()) ZNetScene.instance.Destroy(gameObject);
return true;
}
- if (target == null || !target.gameObject.activeInHierarchy) target = FindDeposit();
+ // A deposit another drone just broke is still there until the end of the frame, with a
+ // dead network view: drop it and look again.
+ if (target == null || !target.gameObject.activeInHierarchy || !Live(target)) target = FindDeposit();
Vector3 point = Vector3.zero;
Collider area = target != null ? NearestArea(target, out point) : null;
if (area == null) { target = null; ai.StopMoving(); return true; }
@@ -281,8 +346,9 @@ namespace RacesOfValheim
// sits at its base inside the mesh, so a drone aiming there stopped on top of the rock
// and never came within reach.
float distance = Vector3.Distance(transform.position, point);
+ lastDistance = distance;
- if (distance > 3.5f)
+ if (distance > Reach)
{
if (MoveToMethod != null) MoveToMethod.Invoke(ai, new object[] { dt, point + Vector3.up * 1.5f, 2f, true });
return true;
@@ -292,14 +358,29 @@ namespace RacesOfValheim
if (Time.time < nextStrike) return true;
nextStrike = Time.time + 1f;
Strike(target, area, point);
+ strikes++;
return true;
}
private static string[] names;
- private static string[] Deposits => names ?? (names = AlfarNexusConfig.MinerDeposits.Value.Split(
- new[] { ',' }, System.StringSplitOptions.RemoveEmptyEntries));
+ private static string namesSource;
- private bool IsPrecious(string prefabName)
+ // Read again when the config line changes, so an edit in game counts without a restart.
+ private static string[] Deposits
+ {
+ get
+ {
+ string value = AlfarNexusConfig.MinerDeposits.Value;
+ if (names == null || namesSource != value)
+ {
+ namesSource = value;
+ names = value.Split(new[] { ',' }, System.StringSplitOptions.RemoveEmptyEntries);
+ }
+ return names;
+ }
+ }
+
+ private static bool IsPrecious(string prefabName)
{
foreach (string wanted in Deposits)
{
@@ -314,12 +395,11 @@ namespace RacesOfValheim
float bestDistance = float.MaxValue;
foreach (Collider collider in Physics.OverlapSphere(Centre, Radius, ~0, QueryTriggerInteraction.Ignore))
{
- Component deposit = collider.GetComponentInParent();
- if (deposit == null) deposit = collider.GetComponentInParent();
- if (deposit == null) deposit = collider.GetComponentInParent();
+ Component deposit = DepositOf(collider);
if (deposit == null) continue;
- string prefabName = Utils.GetPrefabName(deposit.gameObject);
+ if (!Live(deposit)) continue;
+ string prefabName = DepositName(deposit);
if (!IsPrecious(prefabName)) continue;
float distance = Vector3.Distance(transform.position, deposit.transform.position);
@@ -355,7 +435,7 @@ namespace RacesOfValheim
private void Strike(Component deposit, Collider area, Vector3 point)
{
IDestructible destructible = deposit as IDestructible;
- if (destructible == null) return;
+ if (destructible == null) { lastHit = $"{deposit.GetType().Name} is not IDestructible"; return; }
HitData hit = new HitData();
hit.m_damage.m_pickaxe = AlfarNexusConfig.MinerDamage.Value;
@@ -369,7 +449,248 @@ namespace RacesOfValheim
// check: a hit with no attacker throws before the area can break.
hit.SetAttacker(GetComponent());
- destructible.Damage(hit);
+ // Overwritten by the patches below at each step the hit gets through. Vanilla runs the
+ // RPC on this machine at once when we own the deposit, so `striking` is still set then.
+ lastHit = "Damage not entered";
+ striking = this;
+ rpcRan = false;
+ try
+ {
+ destructible.Damage(hit);
+
+ // The F8 readout showed the hit entering Damage with every gate open and this
+ // machine owning the deposit, and the RPC handler never running: the routed call
+ // left for the network instead of being handled here. When we own the deposit,
+ // call its own handler directly - the same resistance, tier and break logic, only
+ // without the routing.
+ if (!rpcRan && OwnsDeposit(deposit)) StrikeDirect(deposit, area, hit);
+ }
+ finally { striking = null; }
+ }
+
+ private static bool rpcRan;
+
+ private static readonly System.Reflection.MethodInfo DestructibleRpc = AccessTools.Method(typeof(Destructible), "RPC_Damage");
+ private static readonly System.Reflection.MethodInfo MineRockRpc = AccessTools.Method(typeof(MineRock), "RPC_Hit");
+ private static readonly System.Reflection.MethodInfo MineRockArea = AccessTools.Method(typeof(MineRock), "GetAreaIndex");
+ private static readonly System.Reflection.MethodInfo MineRock5Rpc = AccessTools.Method(typeof(MineRock5), "RPC_Damage");
+ private static readonly System.Reflection.MethodInfo MineRock5Area = AccessTools.Method(typeof(MineRock5), "GetAreaIndex");
+ private static readonly System.Reflection.FieldInfo RpcIdField = AccessTools.Field(typeof(ZRoutedRpc), "m_id");
+
+ private static bool OwnsDeposit(Component deposit)
+ {
+ ZNetView nview = deposit.GetComponent();
+ return nview != null && nview.IsValid() && nview.IsOwner();
+ }
+
+ private void StrikeDirect(Component deposit, Collider area, HitData hit)
+ {
+ long sender = ZDOMan.GetSessionID();
+ string entry = lastHit;
+ try
+ {
+ if (deposit is Destructible && DestructibleRpc != null)
+ {
+ DestructibleRpc.Invoke(deposit, new object[] { sender, hit });
+ }
+ else if (deposit is MineRock && MineRockRpc != null && MineRockArea != null)
+ {
+ int index = (int)MineRockArea.Invoke(deposit, new object[] { area });
+ if (index < 0) { lastHit = "direct: collider is not a MineRock area"; return; }
+ MineRockRpc.Invoke(deposit, new object[] { sender, hit, index });
+ }
+ else if (deposit is MineRock5 && MineRock5Rpc != null && MineRock5Area != null)
+ {
+ int index = (int)MineRock5Area.Invoke(deposit, new object[] { area });
+ if (index < 0) { lastHit = "direct: collider is not a MineRock5 area"; return; }
+ MineRock5Rpc.Invoke(deposit, new object[] { sender, hit, index });
+ }
+ else
+ {
+ lastHit = $"direct: no handler for {deposit.GetType().Name}";
+ return;
+ }
+ lastHit = $"direct, {lastHit} | before: {entry}";
+ }
+ catch (System.Exception ex)
+ {
+ System.Exception inner = ex.InnerException ?? ex;
+ lastHit = $"direct failed: {inner.GetType().Name}: {inner.Message}";
+ Jotunn.Logger.LogWarning($"[Alfar] Grafvaettir direct hit failed: {inner}");
+ }
+ }
+
+ // ─── F8 diagnostics: what each hit did on arrival ──────────────────────
+
+ private static AlfarMiner striking;
+
+ private static AlfarMiner MinerOf(HitData hit)
+ {
+ if (striking != null) return striking;
+ Character attacker = hit != null ? hit.GetAttacker() : null;
+ return attacker != null ? attacker.GetComponent() : null;
+ }
+
+ private static readonly System.Reflection.FieldInfo FirstFrameField = AccessTools.Field(typeof(Destructible), "m_firstFrame");
+
+ /// The gates in front of the RPC: whose deposit it is and whether the view is live.
+ private static void RecordEntry(Component deposit, string extra)
+ {
+ if (striking == null) return;
+ ZNetView nview = deposit.GetComponent();
+ bool valid = nview != null && nview.IsValid();
+ long owner = valid ? nview.GetZDO().GetOwner() : -1L;
+ long me = ZDOMan.GetSessionID();
+ Character attacker = striking.GetComponent();
+ object rpcId = RpcIdField != null && ZRoutedRpc.instance != null ? RpcIdField.GetValue(ZRoutedRpc.instance) : null;
+ striking.lastHit = $"Damage entered{extra} valid={valid} owner={owner} session={me} rpcId={rpcId} " +
+ $"attackerZdo={(attacker != null ? attacker.GetZDOID().ToString() : "none")}, no RPC";
+ }
+
+ [HarmonyPatch(typeof(Destructible), nameof(Destructible.Damage))]
+ public static class Alfar_Miner_DestructibleEnter_Patch
+ {
+ public static void Prefix(Destructible __instance)
+ {
+ object first = FirstFrameField != null ? FirstFrameField.GetValue(__instance) : null;
+ RecordEntry(__instance, $" firstFrame={first}");
+ }
+ }
+
+ [HarmonyPatch(typeof(MineRock), nameof(MineRock.Damage))]
+ public static class Alfar_Miner_MineRockEnter_Patch
+ {
+ public static void Prefix(MineRock __instance) => RecordEntry(__instance, "");
+ }
+
+ [HarmonyPatch(typeof(MineRock5), nameof(MineRock5.Damage))]
+ public static class Alfar_Miner_MineRock5Enter_Patch
+ {
+ public static void Prefix(MineRock5 __instance) => RecordEntry(__instance, "");
+ }
+
+ private static void Record(HitData hit, string kind, float before, float after, int minTier)
+ {
+ AlfarMiner miner = MinerOf(hit);
+ if (miner == null) return;
+ if (miner == striking) rpcRan = true;
+ miner.lastHit = $"{kind} hp {before:0.#}->{after:0.#} dmg {hit.GetTotalDamage():0.#} " +
+ $"pick {hit.m_damage.m_pickaxe:0.#} tier {hit.m_toolTier}/{minTier}";
+ }
+
+ [HarmonyPatch(typeof(Destructible), "RPC_Damage")]
+ public static class Alfar_Miner_DestructibleHit_Patch
+ {
+ private static float Health(Destructible d)
+ {
+ ZNetView nview = d.GetComponent();
+ return nview != null && nview.IsValid() ? nview.GetZDO().GetFloat(ZDOVars.s_health, d.m_health) : -1f;
+ }
+
+ public static void Prefix(Destructible __instance, HitData hit, out float __state)
+ {
+ __state = MinerOf(hit) != null ? Health(__instance) : -1f;
+ }
+
+ public static void Postfix(Destructible __instance, HitData hit, float __state)
+ {
+ if (MinerOf(hit) == null) return;
+ Record(hit, "Destructible", __state, Health(__instance), __instance.m_minToolTier);
+ }
+ }
+
+ [HarmonyPatch(typeof(MineRock), "RPC_Hit")]
+ public static class Alfar_Miner_MineRockHit_Patch
+ {
+ private static float Health(MineRock rock, int area)
+ {
+ ZNetView nview = rock.GetComponent();
+ return nview != null && nview.IsValid() ? nview.GetZDO().GetFloat("Health" + area, rock.GetHealth()) : -1f;
+ }
+
+ public static void Prefix(MineRock __instance, HitData hit, int hitAreaIndex, out float __state)
+ {
+ __state = MinerOf(hit) != null ? Health(__instance, hitAreaIndex) : -1f;
+ }
+
+ public static void Postfix(MineRock __instance, HitData hit, int hitAreaIndex, float __state)
+ {
+ if (MinerOf(hit) == null) return;
+ Record(hit, $"MineRock area {hitAreaIndex}", __state, Health(__instance, hitAreaIndex), __instance.m_minToolTier);
+ }
+ }
+
+ [HarmonyPatch(typeof(MineRock5), "DamageArea")]
+ public static class Alfar_Miner_MineRock5Hit_Patch
+ {
+ public static void Postfix(MineRock5 __instance, int hitAreaIndex, HitData hit, bool __result)
+ {
+ if (MinerOf(hit) == null) return;
+ Record(hit, $"MineRock5 area {hitAreaIndex} damaged={__result}", -1f, -1f, __instance.m_minToolTier);
+ }
+ }
+
+ private static bool Live(Component deposit)
+ {
+ ZNetView nview = deposit.GetComponent();
+ return nview != null && nview.IsValid();
+ }
+
+ ///
+ /// The deposit's prefab name, read from its ZDO. Not from the GameObject: MineRock5 renames
+ /// its own object to "___MineRock5 m_meshFilter" in Awake, so a broken copper vein
+ /// (rock4_copper_frac) never matched the list and the drones stopped after the first blow.
+ ///
+ private static string DepositName(Component deposit)
+ {
+ ZNetView nview = deposit.GetComponent();
+ if (nview != null && nview.IsValid() && ZNetScene.instance != null)
+ {
+ GameObject prefab = ZNetScene.instance.GetPrefab(nview.GetZDO().GetPrefab());
+ if (prefab != null) return prefab.name;
+ }
+ return Utils.GetPrefabName(deposit.gameObject);
+ }
+
+ private static Component DepositOf(Collider collider)
+ {
+ Component deposit = collider.GetComponentInParent();
+ if (deposit == null) deposit = collider.GetComponentInParent();
+ if (deposit == null) deposit = collider.GetComponentInParent();
+ return deposit;
+ }
+
+ ///
+ /// F8 readout: what the camera looks at (is it a deposit, of which kind, on the list?) and
+ /// what each live miner is doing (its target, how far, how many strikes).
+ ///
+ public static void DebugReport(Player player)
+ {
+ var lines = new List();
+ Transform aim = GameCamera.instance != null ? GameCamera.instance.transform : player.transform;
+ if (Physics.Raycast(aim.position, aim.forward, out RaycastHit hit, 50f, ~0, QueryTriggerInteraction.Ignore))
+ {
+ Component deposit = DepositOf(hit.collider);
+ string prefabName = deposit != null ? DepositName(deposit) : Utils.GetPrefabName(hit.collider.transform.root.gameObject);
+ lines.Add($"[RoV graf] look: {hit.collider.name} on {prefabName} " +
+ (deposit != null ? $"{deposit.GetType().Name} listed={IsPrecious(prefabName)}" : "not a deposit"));
+ }
+ else lines.Add("[RoV graf] look: nothing within 50m");
+
+ foreach (AlfarMiner miner in All)
+ {
+ if (miner == null) continue;
+ string targetName = miner.target != null ? DepositName(miner.target) : "none";
+ lines.Add($"[RoV graf] miner {Vector3.Distance(miner.transform.position, player.transform.position):0}m away: " +
+ $"target {targetName} dist {miner.lastDistance:0.0} strikes {miner.strikes} " +
+ $"age {Now - miner.bornAt:0}s centre {miner.Centre} r {miner.Radius:0} | last hit: {miner.lastHit}");
+ }
+
+ foreach (string line in lines)
+ {
+ Debug.Log(line);
+ player.Message(MessageHud.MessageType.TopLeft, line);
+ }
}
[HarmonyPatch(typeof(MonsterAI), "UpdateAI")]
diff --git a/JotunnModStub/Alfar/AlfarFireChest.cs b/JotunnModStub/Alfar/AlfarFireChest.cs
new file mode 100644
index 0000000..ffff98a
--- /dev/null
+++ b/JotunnModStub/Alfar/AlfarFireChest.cs
@@ -0,0 +1,166 @@
+using System.Collections.Generic;
+using Jotunn.Managers;
+using UnityEngine;
+
+namespace RacesOfValheim
+{
+ ///
+ /// 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.
+ ///
+ 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);
+
+ /// 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.
+ public static bool Build(GameObject prefab)
+ {
+ GameObject crate = PrefabManager.Cache.GetPrefab(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();
+ 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(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();
+ 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 { { "Crate_d", paint } });
+ Material iron = paint != null ? body.GetComponent()?.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();
+ look.Glows = new[] { glow };
+ look.Embers = embers;
+ look.GlowColor = Ember * 2f;
+ look.WoodOnly = true;
+ return true;
+ }
+
+ /// The grate: a glowing plate just off the front face, a frame and bars in front of it.
+ 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();
+
+ 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;
+ }
+
+ /// A plain box with no collider, for trim the borrowed meshes do not have.
+ internal static GameObject Block(Transform parent, string name, Vector3 position, Vector3 size, Material material)
+ {
+ GameObject block = GameObject.CreatePrimitive(PrimitiveType.Cube);
+ Object.DestroyImmediate(block.GetComponent());
+ 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().sharedMaterial = material;
+ return block;
+ }
+
+ /// The carried torch's embers, rising off the top of the grate.
+ private static ParticleSystem AddEmbers(Transform grate)
+ {
+ GameObject torch = PrefabManager.Cache.GetPrefab(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();
+ }
+ }
+}
diff --git a/JotunnModStub/Alfar/AlfarInputChest.cs b/JotunnModStub/Alfar/AlfarInputChest.cs
new file mode 100644
index 0000000..6f4ea39
--- /dev/null
+++ b/JotunnModStub/Alfar/AlfarInputChest.cs
@@ -0,0 +1,137 @@
+using System.Collections.Generic;
+using Jotunn.Managers;
+using UnityEngine;
+
+namespace RacesOfValheim
+{
+ ///
+ /// The Inngangskista's own body, the cold twin of : 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.
+ ///
+ 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);
+
+ /// Swaps the cloned wood chest's meshes for the input chest. False leaves the wood
+ /// chest's look in place, with a warning.
+ public static bool Build(GameObject prefab)
+ {
+ GameObject source = PrefabManager.Cache.GetPrefab(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();
+ 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();
+ 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 { { "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 panel = null;
+ foreach (Renderer renderer in visual.GetComponentsInChildren(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();
+ look.Glows = BuildInlay(lidClosed.transform, panel);
+ look.GlowColor = Inlay * 1.6f;
+ look.WoodOnly = false;
+ return true;
+ }
+
+ /// A copy of one of the town chest's parts, at the town chest's size and on the piece layer.
+ 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(true)) t.gameObject.layer = parent.gameObject.layer;
+ return copy;
+ }
+
+ /// 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.
+ 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();
+ 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();
+ }
+ }
+}
diff --git a/JotunnModStub/Alfar/AlfarMiners.cs b/JotunnModStub/Alfar/AlfarMiners.cs
index 59b3b22..b2c5a95 100644
--- a/JotunnModStub/Alfar/AlfarMiners.cs
+++ b/JotunnModStub/Alfar/AlfarMiners.cs
@@ -22,7 +22,11 @@ namespace RacesOfValheim
public static void Throw(Player player)
{
- if (Time.time < readyAt) return;
+ if (Time.time < readyAt)
+ {
+ player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_alfar_graf_cooldown", Mathf.CeilToInt(readyAt - Time.time)));
+ return;
+ }
Transform aim = GameCamera.instance != null ? GameCamera.instance.transform : player.transform;
Vector3 origin = aim.position;
@@ -76,12 +80,7 @@ namespace RacesOfValheim
GameObject spawned = Object.Instantiate(prefab, where, Quaternion.identity);
AlfarMiner miner = spawned.GetComponent();
- if (miner != null)
- {
- miner.Centre = point;
- miner.Radius = AlfarPowerConfig.GrafRadius.Value;
- miner.LiveSeconds = AlfarPowerConfig.GrafSeconds.Value;
- }
+ if (miner != null) miner.Assign(point, AlfarPowerConfig.GrafRadius.Value, AlfarPowerConfig.GrafSeconds.Value);
// Tame at once so nothing flees them and they flee nothing; no anchor, no leash.
MonsterAI ai = spawned.GetComponent();
diff --git a/JotunnModStub/Alfar/AlfarNexus.cs b/JotunnModStub/Alfar/AlfarNexus.cs
index 8ba5ac9..26024f5 100644
--- a/JotunnModStub/Alfar/AlfarNexus.cs
+++ b/JotunnModStub/Alfar/AlfarNexus.cs
@@ -46,7 +46,9 @@ namespace RacesOfValheim
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();
nexus.m_switch = prefab.AddComponent();
@@ -71,7 +73,7 @@ namespace RacesOfValheim
trader.m_randomUseItemAlreadyRecieved = new List();
trader.m_randomTalkConditionals = new List();
- Sprite icon = BorrowIcon("Eitr") ?? BorrowIcon("SurtlingCore");
+ Sprite icon = (pyramid ? AlfarChests.IconFrom("AlfarNexus_icon.png") : null) ?? BorrowIcon("Eitr") ?? BorrowIcon("SurtlingCore");
Piece piece = prefab.GetComponent() ?? prefab.AddComponent();
piece.m_craftingStation = null;
diff --git a/JotunnModStub/Alfar/AlfarNexusLook.cs b/JotunnModStub/Alfar/AlfarNexusLook.cs
new file mode 100644
index 0000000..34c1fe7
--- /dev/null
+++ b/JotunnModStub/Alfar/AlfarNexusLook.cs
@@ -0,0 +1,217 @@
+using Jotunn.Managers;
+using UnityEngine;
+
+namespace RacesOfValheim
+{
+ ///
+ /// 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.
+ ///
+ 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);
+
+ /// 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.
+ 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();
+ 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();
+ 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();
+ 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();
+
+ NexusLook look = prefab.AddComponent();
+ 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().sharedMesh = mesh;
+ part.AddComponent().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),
+ };
+
+ /// 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.
+ 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;
+ }
+
+ /// 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.
+ private static ParticleSystem AddMotes(Transform root)
+ {
+ GameObject torch = PrefabManager.Cache.GetPrefab(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();
+ 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;
+ }
+
+ /// The motion and the seam's light, per client.
+ 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();
+ 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);
+ }
+ }
+ }
+}
diff --git a/JotunnModStub/Alfar/AlfarPatches.cs b/JotunnModStub/Alfar/AlfarPatches.cs
index 5d5e5ea..73864de 100644
--- a/JotunnModStub/Alfar/AlfarPatches.cs
+++ b/JotunnModStub/Alfar/AlfarPatches.cs
@@ -38,6 +38,37 @@ namespace RacesOfValheim
}
}
+ ///
+ /// 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.
+ ///
+ [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();
+ return player != null && AlfarVisuals.IsAlfarPlayer(player);
+ }
+
///
/// 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,
diff --git a/JotunnModStub/Alfar/AlfarPowers.cs b/JotunnModStub/Alfar/AlfarPowers.cs
index 82aca06..8a02b61 100644
--- a/JotunnModStub/Alfar/AlfarPowers.cs
+++ b/JotunnModStub/Alfar/AlfarPowers.cs
@@ -148,12 +148,17 @@ namespace RacesOfValheim
}
/// A pulse of lightning on every hostile creature within a radius of the Alfr.
- public static void Pulse(Player player, float radius, float damage)
+ /// True if it struck at least one creature.
+ public static bool Pulse(Player player, float radius, float damage)
{
+ bool struck = false;
foreach (Character character in CharactersIn(player.transform.position, radius))
{
- if (IsHostile(player, character)) Strike(player, character, damage, character.GetCenterPoint());
+ if (!IsHostile(player, character)) continue;
+ Strike(player, character, damage, character.GetCenterPoint());
+ struck = true;
}
+ return struck;
}
private static IEnumerable CharactersIn(Vector3 center, float radius)
@@ -177,35 +182,64 @@ namespace RacesOfValheim
Vector3 direction = aim.forward;
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.
Vector3 destination = origin + direction * distance;
- RaycastHit[] hits = Physics.RaycastAll(origin, direction, distance, ~0, QueryTriggerInteraction.Ignore);
- float nearest = float.MaxValue;
- foreach (RaycastHit hit in hits)
+ if (NearestHit(player, origin, direction, distance, out RaycastHit wall))
{
- if (hit.collider.GetComponentInParent() == player) continue;
- if (hit.distance < nearest)
+ destination = wall.point - direction * 0.6f;
+ }
+
+ // Back down to the player's own height: the origin was at the chest. The floor is found
+ // with a short ray down from the landing point, never with GetSolidHeight: that one casts
+ // from 1000 m up, so under any roof (a crypt, a cave, a house) it returned the roof and
+ // put the Alfr on top of it. A flat 1 m drop also sank the feet under the floor when the
+ // blink was aimed at it.
+ const float FloorSearch = 3f;
+ if (NearestHit(player, destination, Vector3.down, FloorSearch, out RaycastHit floor))
+ {
+ destination.y = floor.point.y + 0.05f;
+ }
+ else if (player.InInterior())
+ {
+ // No floor under the landing point inside a dungeon: it would end in the void the
+ // dungeon floats in. Cancel before paying.
+ return;
+ }
+ else
+ {
+ destination.y -= 1.0f;
+ if (ZoneSystem.instance != null)
{
- nearest = hit.distance;
- destination = hit.point - direction * 0.6f;
+ // 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;
}
}
- // Back down to the player's own height: the origin was at the chest.
- destination.y -= 1.0f;
- if (ZoneSystem.instance != null)
- {
- float ground = ZoneSystem.instance.GetSolidHeight(destination);
- if (destination.y < ground) destination.y = ground + 0.1f;
- }
+ if (!Pay(player, AlfarPowerConfig.SkridCost.Value)) return;
Teleport(player, destination);
StartCooldown("skrid", AlfarPowerConfig.SkridCooldown.Value);
AlfarFx.Spawn("fx_JotunWitch_LightningBolt_Explosion", origin);
}
+ /// The nearest solid hit along a ray, skipping the caster's own colliders.
+ 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) continue;
+ if (!found || hit.distance < nearest.distance)
+ {
+ nearest = hit;
+ found = true;
+ }
+ }
+ return found;
+ }
+
///
/// 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.
@@ -396,7 +430,11 @@ namespace RacesOfValheim
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)
@@ -548,14 +586,19 @@ namespace RacesOfValheim
const float tick = 0.5f;
nextTick = Time.time + tick;
+ bool struck = false;
foreach (Collider collider in Physics.OverlapSphere(transform.position, Radius, ~0, QueryTriggerInteraction.Ignore))
{
Character character = collider.GetComponentInParent();
if (character == null || character == Owner || character.IsDead() || character.IsTamed()) continue;
if (!BaseAI.IsEnemy(Owner, character)) continue;
AlfarPowers.Strike(Owner, character, DamagePerSecond * tick, character.GetCenterPoint());
+ struck = true;
}
+ // Once per tick, not per creature: a full hit per second the storm strikes something.
+ if (struck && Owner == Player.m_localPlayer) FormMelee.RaiseSkill(Skills.SkillType.ElementalMagic, tick);
+
Vector2 offset = Random.insideUnitCircle * Radius;
AlfarFx.Spawn("fx_JotunWitch_LightningBolt_Explosion", transform.position + new Vector3(offset.x, 0f, offset.y));
}
diff --git a/JotunnModStub/Assets/AlfarFireChest/AlfarFireChest_d.png b/JotunnModStub/Assets/AlfarFireChest/AlfarFireChest_d.png
new file mode 100644
index 0000000..6f380b1
Binary files /dev/null and b/JotunnModStub/Assets/AlfarFireChest/AlfarFireChest_d.png differ
diff --git a/JotunnModStub/Assets/AlfarFireChest/AlfarFireChest_icon.png b/JotunnModStub/Assets/AlfarFireChest/AlfarFireChest_icon.png
new file mode 100644
index 0000000..8a4077f
Binary files /dev/null and b/JotunnModStub/Assets/AlfarFireChest/AlfarFireChest_icon.png differ
diff --git a/JotunnModStub/Assets/AlfarInputChest/AlfarInputChest_d.png b/JotunnModStub/Assets/AlfarInputChest/AlfarInputChest_d.png
new file mode 100644
index 0000000..6ede24f
Binary files /dev/null and b/JotunnModStub/Assets/AlfarInputChest/AlfarInputChest_d.png differ
diff --git a/JotunnModStub/Assets/AlfarInputChest/AlfarInputChest_icon.png b/JotunnModStub/Assets/AlfarInputChest/AlfarInputChest_icon.png
new file mode 100644
index 0000000..761ff83
Binary files /dev/null and b/JotunnModStub/Assets/AlfarInputChest/AlfarInputChest_icon.png differ
diff --git a/JotunnModStub/Assets/AlfarNexus/AlfarNexus_face.png b/JotunnModStub/Assets/AlfarNexus/AlfarNexus_face.png
new file mode 100644
index 0000000..2dff3cb
Binary files /dev/null and b/JotunnModStub/Assets/AlfarNexus/AlfarNexus_face.png differ
diff --git a/JotunnModStub/Assets/AlfarNexus/AlfarNexus_glow.png b/JotunnModStub/Assets/AlfarNexus/AlfarNexus_glow.png
new file mode 100644
index 0000000..d88a980
Binary files /dev/null and b/JotunnModStub/Assets/AlfarNexus/AlfarNexus_glow.png differ
diff --git a/JotunnModStub/Assets/AlfarNexus/AlfarNexus_icon.png b/JotunnModStub/Assets/AlfarNexus/AlfarNexus_icon.png
new file mode 100644
index 0000000..a85c891
Binary files /dev/null and b/JotunnModStub/Assets/AlfarNexus/AlfarNexus_icon.png differ
diff --git a/JotunnModStub/Assets/AlfarNexus/AlfarNexus_n.png b/JotunnModStub/Assets/AlfarNexus/AlfarNexus_n.png
new file mode 100644
index 0000000..1940c2a
Binary files /dev/null and b/JotunnModStub/Assets/AlfarNexus/AlfarNexus_n.png differ
diff --git a/JotunnModStub/Assets/Hammers/ShrinkHammer_icon.png b/JotunnModStub/Assets/Hammers/ShrinkHammer_icon.png
new file mode 100644
index 0000000..a7328f5
Binary files /dev/null and b/JotunnModStub/Assets/Hammers/ShrinkHammer_icon.png differ
diff --git a/JotunnModStub/Assets/Hammers/TrolsHammer_icon.png b/JotunnModStub/Assets/Hammers/TrolsHammer_icon.png
new file mode 100644
index 0000000..99e1761
Binary files /dev/null and b/JotunnModStub/Assets/Hammers/TrolsHammer_icon.png differ
diff --git a/JotunnModStub/Aswid/AswidBatForm.cs b/JotunnModStub/Aswid/AswidBatForm.cs
index 1ce1fc3..2ac80c7 100644
--- a/JotunnModStub/Aswid/AswidBatForm.cs
+++ b/JotunnModStub/Aswid/AswidBatForm.cs
@@ -118,6 +118,27 @@ namespace RacesOfValheim
}
}
+ ///
+ /// 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.
+ ///
+ [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;
+ }
+ }
+
///
/// 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
diff --git a/JotunnModStub/Aswid/AswidConfig.cs b/JotunnModStub/Aswid/AswidConfig.cs
index fa58ee2..57bc11a 100644
--- a/JotunnModStub/Aswid/AswidConfig.cs
+++ b/JotunnModStub/Aswid/AswidConfig.cs
@@ -107,6 +107,7 @@ namespace RacesOfValheim
public static ConfigEntry BatMaxDuration;
public static ConfigEntry BatDurationPerState;
public static ConfigEntry BatCooldown;
+ public static ConfigEntry BatCombatLock;
// ─── Vampiric Aura (passive, always active) ──────────────────────────────
public static ConfigEntry 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(0f, 600f)));
BatCooldown = config.Bind(batform, "Cooldown", 0f,
new ConfigDescription("Seconds after leaving bat form before you can take it again. 0 means none.", new AcceptableValueRange(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(0f, 30f)));
const string aura = "Aswid - Vampiric Aura";
AuraTickInterval = config.Bind(aura, "Tick Interval", 0.25f,
diff --git a/JotunnModStub/Aswid/AswidPatches.cs b/JotunnModStub/Aswid/AswidPatches.cs
index b799936..b607ad9 100644
--- a/JotunnModStub/Aswid/AswidPatches.cs
+++ b/JotunnModStub/Aswid/AswidPatches.cs
@@ -931,6 +931,30 @@ namespace RacesOfValheim
}
}
+ ///
+ /// 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.
+ ///
+ [HarmonyPatch(typeof(Player), "RemoveOneFood")]
+ public static class Aswid_PlayerRemoveOneFood_Patch
+ {
+ public static bool Prefix(Player __instance, System.Collections.Generic.List ___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")]
public static class Aswid_Player_ClearFood_Patch
{
diff --git a/JotunnModStub/Aswid/AswidRace.cs b/JotunnModStub/Aswid/AswidRace.cs
index 556d8d5..8367a64 100644
--- a/JotunnModStub/Aswid/AswidRace.cs
+++ b/JotunnModStub/Aswid/AswidRace.cs
@@ -615,6 +615,14 @@ namespace RacesOfValheim
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);
if (cooldownLeft > 0f)
{
@@ -629,6 +637,10 @@ namespace RacesOfValheim
// fresh session never begins on cooldown.
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
// TransformIntoBatRoutine left running through a reset finishes its 1.1s gesture and
// turns a freshly reset Human into a bat.
@@ -1179,6 +1191,7 @@ namespace RacesOfValheim
int layerMask = LayerMask.GetMask("character", "character_net", "character_ghost");
var colliders = Physics.OverlapSphere(center, radius, layerMask);
+ bool hitCreature = false;
foreach (var col in colliders)
{
@@ -1229,10 +1242,16 @@ namespace RacesOfValheim
// 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.
c.Damage(hd);
+ hitCreature = true;
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)
{
diff --git a/JotunnModStub/Audio/trolsbuilding.ogg b/JotunnModStub/Audio/trolsbuilding.ogg
new file mode 100644
index 0000000..697f323
Binary files /dev/null and b/JotunnModStub/Audio/trolsbuilding.ogg differ
diff --git a/JotunnModStub/Audio/trolsdeath.ogg b/JotunnModStub/Audio/trolsdeath.ogg
new file mode 100644
index 0000000..9f5ea11
Binary files /dev/null and b/JotunnModStub/Audio/trolsdeath.ogg differ
diff --git a/JotunnModStub/Butler/BoneServantAI.cs b/JotunnModStub/Butler/BoneServantAI.cs
index 073d718..2c165db 100644
--- a/JotunnModStub/Butler/BoneServantAI.cs
+++ b/JotunnModStub/Butler/BoneServantAI.cs
@@ -363,8 +363,22 @@ namespace RacesOfValheim
Scan(anchor.Value);
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 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
@@ -376,13 +390,7 @@ namespace RacesOfValheim
// in return, because FuelWanted is zero for a station with no work: an empty furnace asks
// for no coal, gets filled, and only then becomes worth stoking.
Job job = m_family == ButlerFamily.Kitchen ? PlanRescue() : null;
- job = 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;
+ return job ?? PlanCollect() ?? PlanFuel() ?? PlanLoad();
}
///
@@ -634,8 +642,10 @@ namespace RacesOfValheim
// coal, so gating the delivery on free slots sent the servant back to the chest with
// the coal it had just fetched - and then PlanFuel sent it out for the same coal again,
// forever. AcceptsAnything already asks the right question of both doors.
+ // 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);
- if (station != null && station.Alive && station.Operable && AcceptsAnything(station))
+ if (station != null && station.Alive && station.Operable && AcceptsAnything(station) && !IsPenalised(target))
{
return new Job
{
diff --git a/JotunnModStub/ConfigSync.cs b/JotunnModStub/ConfigSync.cs
index fd0fa67..fbf16b6 100644
--- a/JotunnModStub/ConfigSync.cs
+++ b/JotunnModStub/ConfigSync.cs
@@ -31,6 +31,8 @@ namespace RacesOfValheim
"Aswid - Eyes",
"Fenrir - Appearance",
"Skeleton - Visuals",
+ // Food and stamina for a Skeleton who wants them: each only gives up an advantage.
+ "Skeleton - Mortal Habits",
"Sverm - Dorsal Spines",
"Sverm - Emberform",
"Trol - Appearance",
diff --git a/JotunnModStub/DebugConfig.cs b/JotunnModStub/DebugConfig.cs
new file mode 100644
index 0000000..ae763e0
--- /dev/null
+++ b/JotunnModStub/DebugConfig.cs
@@ -0,0 +1,32 @@
+using UnityEngine;
+using BepInEx.Configuration;
+
+namespace RacesOfValheim
+{
+ ///
+ /// 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.
+ ///
+ public static class DebugConfig
+ {
+ public static ConfigEntry EnableDebugKey;
+ public static ConfigEntry DebugKey;
+ public static ConfigEntry 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."));
+ }
+ }
+}
diff --git a/JotunnModStub/Dvergar/DvergarCheapBuilding.cs b/JotunnModStub/Dvergar/DvergarCheapBuilding.cs
new file mode 100644
index 0000000..9fa25ec
--- /dev/null
+++ b/JotunnModStub/Dvergar/DvergarCheapBuilding.cs
@@ -0,0 +1,275 @@
+using System.Collections.Generic;
+using HarmonyLib;
+using UnityEngine;
+using UnityEngine.UI;
+
+namespace RacesOfValheim
+{
+ ///
+ /// 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.
+ ///
+ 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 originals;
+ private static Dictionary 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()?.m_itemData?.m_shared?.m_buildPieces : null;
+ stoneItem = ObjectDB.instance.GetItemPrefab(Stone)?.GetComponent();
+ fineWoodItem = ObjectDB.instance.GetItemPrefab(FineWood)?.GetComponent();
+ if (table == null || stoneItem == null || fineWoodItem == null) return false;
+
+ originals = new Dictionary();
+ prefabs = new Dictionary();
+ foreach (GameObject go in table.m_pieces)
+ {
+ Piece piece = go != null ? go.GetComponent() : 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() == null
+ && piece.GetComponentInChildren() == null
+ && piece.GetComponentInChildren() == null
+ && piece.GetComponentInChildren() == null
+ && piece.GetComponentInChildren() == null
+ && piece.m_comfort <= 0;
+ }
+
+ ///
+ /// 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.
+ ///
+ private static Piece.Requirement[] BuildCheap(Piece.Requirement[] original, int stoneRatio, int woodRatio)
+ {
+ var result = new List();
+ 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();
+ foreach (Piece.Requirement req in reqs)
+ {
+ if (req.m_resItem != null) parts.Add($"{req.m_amount} {req.m_resItem.name}");
+ }
+ return string.Join(", ", parts);
+ }
+
+ ///
+ /// Puts the cost the local player should see on the prefabs. Returns whether anything
+ /// changed, so the caller knows to refresh the build menu.
+ ///
+ 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));
+ }
+
+ ///
+ /// 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.
+ ///
+ [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();
+ }
+ }
+
+ ///
+ /// 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.
+ ///
+ [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();
+ if (nview == null || !nview.IsValid() || !nview.IsOwner()) return;
+
+ nview.GetZDO().Set(StoneRatioZdoKey, DvergarConfigManagement.CheapStonePerBlackMarble.Value);
+ nview.GetZDO().Set(WoodRatioZdoKey, DvergarConfigManagement.CheapFineWoodPerYggdrasil.Value);
+ }
+ }
+
+ ///
+ /// 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.
+ ///
+ [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();
+ 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;
+ }
+ }
+
+ ///
+ /// 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.
+ ///
+ [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.sprite = RacesOfValheim.RaceIcon(DvergarConfig.RaceId);
+ image.preserveAspect = true;
+ image.raycastTarget = false;
+ return obj.transform;
+ }
+ }
+ }
+}
diff --git a/JotunnModStub/Dvergar/DvergarConfigManagement.cs b/JotunnModStub/Dvergar/DvergarConfigManagement.cs
index b9be848..3a6d43f 100644
--- a/JotunnModStub/Dvergar/DvergarConfigManagement.cs
+++ b/JotunnModStub/Dvergar/DvergarConfigManagement.cs
@@ -57,6 +57,11 @@ namespace RacesOfValheim
public static ConfigEntry RunicOverchargeWindow;
public static ConfigEntry RunicOverchargeCooldown;
+ // ─── Cheap Building ───────────────────────────────────────────────────────
+ public static ConfigEntry CheapBuildingEnabled;
+ public static ConfigEntry CheapStonePerBlackMarble;
+ public static ConfigEntry CheapFineWoodPerYggdrasil;
+
public static void Bind(ConfigFile config)
{
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(1f, 60f)));
RunicOverchargeCooldown = config.Bind(overcharge, "Cooldown", 60f,
new ConfigDescription("Seconds between casts.", new AcceptableValueRange(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(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(1, 10)));
}
}
}
diff --git a/JotunnModStub/Factions/FactionHostilityPatch.cs b/JotunnModStub/Factions/FactionHostilityPatch.cs
index 7fee617..2bc10ce 100644
--- a/JotunnModStub/Factions/FactionHostilityPatch.cs
+++ b/JotunnModStub/Factions/FactionHostilityPatch.cs
@@ -54,9 +54,17 @@ namespace RacesOfValheim
//
// Skeleton_Hildir stays out deliberately, on the same rule that keeps GoblinKing and the
// Hildir brothers out of the Black Forest set: a quest boss is not somebody's kin.
+ //
+ // Valheim 1.0 added a skeleton per region (the green swamp ones and the blue mountain ones
+ // players noticed first), each with a melee-only twin, and spawners place those instead
+ // of the plain Skeleton. Left out, they fought a Skeleton player the plain ones ignored.
private static readonly HashSet PaludeMobs = new HashSet
{
"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",
"Wraith", "Leech", "Abomination",
"Blob", "BlobElite", "BlobTar", // Blob, Oozer, Growth
@@ -157,6 +165,10 @@ namespace RacesOfValheim
if (!__result) return; // already not enemies, nothing to add
if (a == null || b == null) return;
+ // The player's own blow. Peace is the creature's choice, not a shield. See
+ // RaceGrudge.StrikeScope.
+ if (RaceGrudge.PlayerStrikes(a)) return;
+
if (IsThrallTruce(a, b) || IsThrallTruce(b, a))
{
__result = false;
diff --git a/JotunnModStub/Factions/FactionMerchantCatalog.cs b/JotunnModStub/Factions/FactionMerchantCatalog.cs
index e4db2cb..93a0b71 100644
--- a/JotunnModStub/Factions/FactionMerchantCatalog.cs
+++ b/JotunnModStub/Factions/FactionMerchantCatalog.cs
@@ -337,7 +337,16 @@ namespace RacesOfValheim
{ "Draugr_Elite", DraugrShop },
{ "Skeleton", SkeletonShop },
+ { "Skeleton_NoArcher", 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 },
{ "Wraith", WraithShop },
diff --git a/JotunnModStub/Factions/FactionsConfig.cs b/JotunnModStub/Factions/FactionsConfig.cs
index 2448192..6535e12 100644
--- a/JotunnModStub/Factions/FactionsConfig.cs
+++ b/JotunnModStub/Factions/FactionsConfig.cs
@@ -21,6 +21,8 @@ namespace RacesOfValheim
public static ConfigEntry HostilityEnabled;
public static ConfigEntry MerchantsEnabled;
public static ConfigEntry GrudgeDuration;
+ public static ConfigEntry GrudgeSpreadEnabled;
+ public static ConfigEntry GrudgeSpreadRadius;
// 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
@@ -28,6 +30,8 @@ namespace RacesOfValheim
public static bool Hostility => HostilityEnabled?.Value ?? true;
public static bool Merchants => MerchantsEnabled?.Value ?? true;
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)
{
@@ -55,11 +59,24 @@ namespace RacesOfValheim
"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 " +
"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 " +
- "and per creature, on whichever machine runs that creature's AI. 0 restores the " +
+ "was hurt and had no enemy it was allowed to have. Each creature holds one " +
+ "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.",
new AcceptableValueRange(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(5f, 60f)));
+
MerchantsEnabled = config.Bind(factions, "Faction merchants", true,
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 " +
diff --git a/JotunnModStub/Fenrir/FenrirBehaviors.cs b/JotunnModStub/Fenrir/FenrirBehaviors.cs
index b702a20..d0dd0cd 100644
--- a/JotunnModStub/Fenrir/FenrirBehaviors.cs
+++ b/JotunnModStub/Fenrir/FenrirBehaviors.cs
@@ -774,6 +774,7 @@ namespace RacesOfValheim
Collider[] hits = Physics.OverlapSphere(attackPoint, attackRadius, layerMask);
FormMelee.LogSwing(FormLabel, hits.Length);
System.Collections.Generic.HashSet hitObjects = new System.Collections.Generic.HashSet();
+ bool hitCreature = false;
foreach (Collider hit in hits)
{
@@ -823,10 +824,13 @@ namespace RacesOfValheim
FormMelee.LogHit(FormLabel, target, totalDamage);
target.Damage(hitData);
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);
FormMelee.LogSwing(FormLabel, hits.Length);
System.Collections.Generic.HashSet hitObjects = new System.Collections.Generic.HashSet();
+ bool hitCreature = false;
foreach (Collider hit in hits)
{
@@ -1106,6 +1111,7 @@ namespace RacesOfValheim
FormMelee.LogHit(FormLabel, target, totalDamage);
target.Damage(hitData);
FormMelee.GrantAdrenaline(target, 0.2f); // one 0.2s tick: a full hit per second of breath
+ if (target is Character) hitCreature = true;
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()
@@ -1231,6 +1239,7 @@ namespace RacesOfValheim
Collider[] hits = Physics.OverlapSphere(attackPoint, attackRadius, layerMask);
FormMelee.LogSwing(FormLabel, hits.Length);
System.Collections.Generic.HashSet hitObjects = new System.Collections.Generic.HashSet();
+ bool hitCreature = false;
foreach (Collider hit in hits)
{
@@ -1280,10 +1289,13 @@ namespace RacesOfValheim
FormMelee.LogHit(FormLabel, target, totalDamage);
target.Damage(hitData);
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);
FormMelee.LogSwing(FormLabel, hits.Length);
System.Collections.Generic.HashSet hitObjects = new System.Collections.Generic.HashSet();
+ bool hitCreature = false;
foreach (Collider hit in hits)
{
@@ -1495,10 +1508,13 @@ namespace RacesOfValheim
FormMelee.LogHit(FormLabel, target, totalDamage);
target.Damage(hitData);
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);
FormMelee.LogSwing(FormLabel, hits.Length);
System.Collections.Generic.HashSet hitObjects = new System.Collections.Generic.HashSet();
+ bool hitCreature = false;
foreach (Collider hit in hits)
{
@@ -1703,10 +1720,13 @@ namespace RacesOfValheim
FormMelee.LogHit(FormLabel, target, totalDamage);
target.Damage(hitData);
FormMelee.GrantAdrenaline(target);
+ if (target is Character) hitCreature = true;
}
}
}
}
+
+ if (hitCreature) FormMelee.RaiseSkill(Skills.SkillType.Unarmed);
}
private IEnumerator UlvJumpAttackRoutine()
diff --git a/JotunnModStub/Fenrir/FenrirConfig.cs b/JotunnModStub/Fenrir/FenrirConfig.cs
index 4b8c4fa..2190a36 100644
--- a/JotunnModStub/Fenrir/FenrirConfig.cs
+++ b/JotunnModStub/Fenrir/FenrirConfig.cs
@@ -45,6 +45,9 @@ namespace RacesOfValheim
public static ConfigEntry FullFormJumpBonus;
public static ConfigEntry FullFormFallDamageReduction;
public static ConfigEntry WolfFormSpeedBonus;
+ public static ConfigEntry UlvFormSpeedBonus;
+ public static ConfigEntry FenringDamageReduction;
+ public static ConfigEntry CultistExtraDamageTaken;
public static ConfigEntry WolfFormFallDamageReduction;
public static ConfigEntry FormStaminaRegenMultiplier;
public static ConfigEntry FormStaminaDrainReduction;
@@ -97,9 +100,6 @@ namespace RacesOfValheim
public static ConfigEntry UlvAttackRadius;
public static ConfigEntry UlvPushForce;
- // ─── Debug ─────────────────────────────────────────────────────────────
- public static ConfigEntry DebugFormHits;
-
// ─── Appearance (per player, never synced) ──────────────────────────────
public static ConfigEntry ReadyMessage;
public static ConfigEntry EyeGlow;
@@ -138,14 +138,24 @@ namespace RacesOfValheim
const string buffs = "Fenrir - Form Buffs";
BindNote(config, buffs, "Note: these values need a relog to take effect.");
- FullFormSpeedBonus = config.Bind(buffs, "Full Form Speed Bonus", 1.0f,
- new ConfigDescription("Speed multiplier bonus while in Fenring or Cultist form.", new AcceptableValueRange(0f, 3f)));
+ // Each form has a job once all three are unlocked (Lexsonn's suggestion): the Ulv
+ // 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(0f, 3f)));
FullFormJumpBonus = config.Bind(buffs, "Full Form Jump Bonus", 1.0f,
new ConfigDescription("Jump multiplier bonus while in Fenring or Cultist form.", new AcceptableValueRange(0f, 3f)));
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(0f, 1f)));
- WolfFormSpeedBonus = config.Bind(buffs, "Wolf Form Speed Bonus", 0.5f,
- new ConfigDescription("Speed multiplier bonus while in Wolf or Ulv form.", new AcceptableValueRange(0f, 3f)));
+ WolfFormSpeedBonus = config.Bind(buffs, "Wolf Speed Bonus", 0.5f,
+ new ConfigDescription("Speed multiplier bonus while in Wolf form, the G form before Moder.", new AcceptableValueRange(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(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(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(0f, 2f)));
WolfFormFallDamageReduction = config.Bind(buffs, "Wolf Form Fall Damage Reduction", 0.5f,
new ConfigDescription("Fall damage reduction while in Wolf or Ulv form.", new AcceptableValueRange(0f, 1f)));
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.
EyeReadyStrength = config.Bind(appearance, "Eye Ready Strength", 0.9f,
new ConfigDescription("Glow at night while a form is ready.", new AcceptableValueRange(0f, 3f)));
-
- // "debug" in the key keeps it local - see ConfigSync.
- DebugFormHits = config.Bind("Fenrir - Debug", "Debug: Log Form Hits", false,
- new ConfigDescription("Writes one log line per claw or bite: what was in reach, what it hit, and why anything was skipped. For bug reports about attacks that do no damage."));
}
///
diff --git a/JotunnModStub/Fenrir/FenrirFormShared.cs b/JotunnModStub/Fenrir/FenrirFormShared.cs
index a26c6ed..bcd9c27 100644
--- a/JotunnModStub/Fenrir/FenrirFormShared.cs
+++ b/JotunnModStub/Fenrir/FenrirFormShared.cs
@@ -342,7 +342,7 @@ namespace RacesOfValheim
///
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}.");
}
@@ -368,6 +368,21 @@ namespace RacesOfValheim
player.AddAdrenaline(perHit * character.m_enemyAdrenalineMultiplier * scale);
}
+ ///
+ /// 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.
+ ///
+ 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);
+ }
+
///
/// 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
@@ -398,16 +413,37 @@ namespace RacesOfValheim
return true;
}
+ private static readonly System.Collections.Generic.Dictionary weapons =
+ new System.Collections.Generic.Dictionary();
+
+ ///
+ /// 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.
+ ///
+ 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(prefabName);
+ ItemDrop.ItemData.SharedData shared = prefab != null ? prefab.GetComponent()?.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)
{
- if (!FenrirConfig.DebugFormHits.Value) return;
+ if (!DebugConfig.LogFormHits.Value) return;
string name = target is MonoBehaviour behaviour && behaviour != null ? behaviour.name : target.ToString();
Jotunn.Logger.LogInfo($"[FenrirForm] {form} swing hit '{name}' for {damage:0}.");
}
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.");
}
}
diff --git a/JotunnModStub/Fenrir/FenrirRace.cs b/JotunnModStub/Fenrir/FenrirRace.cs
index f23e140..f3dbb49 100644
--- a/JotunnModStub/Fenrir/FenrirRace.cs
+++ b/JotunnModStub/Fenrir/FenrirRace.cs
@@ -76,7 +76,7 @@ namespace RacesOfValheim {
cultistCdSE.m_icon = fenringTrophyIcon;
ItemManager.Instance.AddStatusEffect(new CustomStatusEffect(cultistCdSE, fixReference: false));
- formBuffSE = ScriptableObject.CreateInstance();
+ formBuffSE = ScriptableObject.CreateInstance();
formBuffSE.name = "SE_FenrirForm";
formBuffSE.m_name = "$rov_se_fenrir_form_name";
formBuffSE.m_speedModifier = FenrirConfig.FullFormSpeedBonus.Value;
@@ -87,7 +87,7 @@ namespace RacesOfValheim {
formBuffSE.m_icon = fenringTrophyIcon;
ItemManager.Instance.AddStatusEffect(new CustomStatusEffect(formBuffSE, fixReference: false));
- cultistFormBuffSE = ScriptableObject.CreateInstance();
+ cultistFormBuffSE = ScriptableObject.CreateInstance();
cultistFormBuffSE.name = "SE_CultistForm";
cultistFormBuffSE.m_name = "$rov_se_fenrir_cultistform_name";
cultistFormBuffSE.m_speedModifier = FenrirConfig.FullFormSpeedBonus.Value;
@@ -98,7 +98,7 @@ namespace RacesOfValheim {
cultistFormBuffSE.m_icon = fenringTrophyIcon;
ItemManager.Instance.AddStatusEffect(new CustomStatusEffect(cultistFormBuffSE, fixReference: false));
- wolfFormBuffSE = ScriptableObject.CreateInstance();
+ wolfFormBuffSE = ScriptableObject.CreateInstance();
wolfFormBuffSE.name = "SE_WolfForm";
wolfFormBuffSE.m_name = "$rov_se_fenrir_wolfform_name";
wolfFormBuffSE.m_speedModifier = FenrirConfig.WolfFormSpeedBonus.Value;
@@ -109,6 +109,16 @@ namespace RacesOfValheim {
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()
{
if (Player.m_localPlayer == null || EnvMan.instance == null) return;
@@ -550,6 +560,7 @@ namespace RacesOfValheim {
Player.m_localPlayer.GetSEMan().AddStatusEffect("SE_WolfForm".GetStableHashCode(), true);
var se = Player.m_localPlayer.GetSEMan().GetStatusEffect("SE_WolfForm".GetStableHashCode());
if (se != null) se.m_ttl = ttl;
+ SetFormBuff(se, FenrirConfig.UlvFormSpeedBonus.Value, 1f);
Player.m_localPlayer.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_fenrir_are_ulv"));
}
else if (prefabName == "Wolf")
@@ -558,6 +569,7 @@ namespace RacesOfValheim {
Player.m_localPlayer.GetSEMan().AddStatusEffect("SE_WolfForm".GetStableHashCode(), true);
var se = Player.m_localPlayer.GetSEMan().GetStatusEffect("SE_WolfForm".GetStableHashCode());
if (se != null) se.m_ttl = ttl;
+ SetFormBuff(se, FenrirConfig.WolfFormSpeedBonus.Value, 1f);
Player.m_localPlayer.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_fenrir_are_wolf"));
}
else if (prefabName == "Fenring_Cultist")
@@ -566,6 +578,7 @@ namespace RacesOfValheim {
Player.m_localPlayer.GetSEMan().AddStatusEffect("SE_CultistForm".GetStableHashCode(), true);
var se = Player.m_localPlayer.GetSEMan().GetStatusEffect("SE_CultistForm".GetStableHashCode());
if (se != null) se.m_ttl = ttl;
+ SetFormBuff(se, FenrirConfig.FullFormSpeedBonus.Value, 1f + FenrirConfig.CultistExtraDamageTaken.Value);
Player.m_localPlayer.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_fenrir_are_cultist"));
}
else
@@ -574,6 +587,7 @@ namespace RacesOfValheim {
Player.m_localPlayer.GetSEMan().AddStatusEffect("SE_FenrirForm".GetStableHashCode(), true);
var se = Player.m_localPlayer.GetSEMan().GetStatusEffect("SE_FenrirForm".GetStableHashCode());
if (se != null) se.m_ttl = ttl;
+ SetFormBuff(se, FenrirConfig.FullFormSpeedBonus.Value, 1f - FenrirConfig.FenringDamageReduction.Value);
Player.m_localPlayer.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_fenrir_are_fenring"));
}
diff --git a/JotunnModStub/Fenrir/FenrirStatusEffects.cs b/JotunnModStub/Fenrir/FenrirStatusEffects.cs
index f08ae33..2050229 100644
--- a/JotunnModStub/Fenrir/FenrirStatusEffects.cs
+++ b/JotunnModStub/Fenrir/FenrirStatusEffects.cs
@@ -22,6 +22,23 @@ namespace RacesOfValheim
}
}
+ ///
+ /// 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.
+ ///
+ 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 override void Setup(Character character)
diff --git a/JotunnModStub/Package/manifest.json b/JotunnModStub/Package/manifest.json
index 0dbd90f..a240b90 100644
--- a/JotunnModStub/Package/manifest.json
+++ b/JotunnModStub/Package/manifest.json
@@ -1,7 +1,7 @@
{
"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.",
- "version_number": "1.6.4",
+ "version_number": "1.6.11",
"website_url": "",
"dependencies": [
"denikson-BepInExPack_Valheim-5.4.2333",
diff --git a/JotunnModStub/RaceCompendium.cs b/JotunnModStub/RaceCompendium.cs
index 946311a..1505ac1 100644
--- a/JotunnModStub/RaceCompendium.cs
+++ b/JotunnModStub/RaceCompendium.cs
@@ -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(ModText.Get("rov_compendium_skeleton_undead_diet"));
- sb.AppendLine(ModText.Get("rov_compendium_skeleton_no_hunger_moves_no_meal", (health).ToString("0")));
+ 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")));
+ }
+ 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_blades_points_find_little_cut"));
@@ -863,8 +874,8 @@ namespace RacesOfValheim
int foodDuration = Mathf.RoundToInt(TrentaConfig.FoodDurationMultiplier);
int purpleRainRadius = Mathf.RoundToInt(TrentaConfig.PurpleRainRadius);
- int purpleRainHeal = Mathf.RoundToInt(TrentaConfig.PurpleRainHealAmount);
- int purpleRainPoison = Mathf.RoundToInt(TrentaConfig.PurpleRainPoisonDamage);
+ int purpleRainHeal = Mathf.RoundToInt(TrentaConfig.PurpleRainHealFor(Player.m_localPlayer));
+ int purpleRainPoison = Mathf.RoundToInt(TrentaConfig.PurpleRainPoisonFor(Player.m_localPlayer));
int purpleRainCooldown = Mathf.RoundToInt(TrentaConfigManagement.PurpleRainCooldown.Value);
int purpleRainMuspellCooldown = Mathf.RoundToInt(TrentaConfigManagement.MuspellPurpleRainCooldown.Value);
diff --git a/JotunnModStub/RaceGrudge.cs b/JotunnModStub/RaceGrudge.cs
index 927f4b5..09bb834 100644
--- a/JotunnModStub/RaceGrudge.cs
+++ b/JotunnModStub/RaceGrudge.cs
@@ -25,11 +25,13 @@ namespace RacesOfValheim
/// which means everything downstream - acquiring, chasing, retaliating, giving up - is vanilla
/// 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
- /// matters and the only one that runs Character.ApplyDamage for it. BaseAI.OnDamaged is reached
- /// through the character's damage callback on exactly that machine, so the record is made where
- /// it will be read. Nothing is replicated and nothing needs to be: another client's copy of the
- /// same mob is not the one deciding who it chases.
+ /// WHERE IT LIVES. On the creature's own ZDO: who it is angry at and until when, in network time.
+ /// The AI that reads it runs on whichever machine owns the creature, and that can change in the
+ /// middle of a fight (the owner walks off or logs out). A grudge kept in one machine's memory
+ /// went with it, and the new owner's copy of the creature made peace on its next UpdateTarget.
+ /// 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:
/// it does nothing unless the prefab sets m_aggravatable, which only the dvergr and the seekers
@@ -37,67 +39,96 @@ namespace RacesOfValheim
///
public static class RaceGrudge
{
- private struct Grudge
- {
- public ZDOID Attacker;
- public float Until;
- }
+ private const string RpcName = "RacesOfValheim_Grudge";
- // One grudge per mob, against the last thing that hit it. A creature can only chase one
- // target anyway, and if two players of the same race are both poking it, the one it wants
- // is whoever hit it last.
- private static readonly Dictionary grudges = new Dictionary();
- private static float lastSweep = 0f;
+ // One grudge per creature, against the last player that hit it. A creature can only chase
+ // one target anyway, and if two players of the same race are both poking it, the one it
+ // wants is whoever hit it last.
+ private static readonly KeyValuePair AttackerKey = ZDO.GetHashZDOID("RacesOfValheim_GrudgeAttacker");
+ private static readonly int UntilKey = "RacesOfValheim_GrudgeUntil".GetStableHashCode();
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);
+ }
+
///
/// True while is owed a hit by . 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.
///
public static bool Holds(Character monster, Character player)
{
if (monster == null || player == null) return false;
if (Duration <= 0f) return false;
- if (!grudges.TryGetValue(monster.GetZDOID(), out Grudge grudge)) return false;
- if (Time.time >= grudge.Until) return false;
+ ZDO zdo = ZdoOf(monster);
+ 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)
- {
- if (monster == null || attacker == null) return;
- if (Duration <= 0f) return;
-
- grudges[monster.GetZDOID()] = new Grudge
- {
- Attacker = attacker.GetZDOID(),
- Until = Time.time + Duration
- };
-
- Sweep();
+ return zdo.GetZDOID(AttackerKey) == player.GetZDOID();
}
///
- /// Drops grudges nobody is owed any more. At most once per duration: a fight is a burst of
- /// damage events and the list should not be walked on each one.
+ /// Writes the grudge on the creature's ZDO if this machine owns it, and otherwise asks the
+ /// owner to. Returns true when it was written here.
///
- private static void Sweep()
+ public static bool Remember(Character monster, Character attacker)
{
- if (Time.time - lastSweep < Duration) return;
- lastSweep = Time.time;
+ if (monster == null || attacker == null) return false;
+ if (Duration <= 0f) return false;
- List expired = null;
- foreach (var entry in grudges)
+ ZNetView nview = monster.GetComponent();
+ if (nview == null || !nview.IsValid()) return false;
+
+ if (!nview.IsOwner())
{
- if (Time.time < entry.Value.Until) continue;
- if (expired == null) expired = new List();
- expired.Add(entry.Key);
+ nview.InvokeRPC(RpcName, attacker.GetZDOID());
+ return false;
+ }
+
+ 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));
+ }
+
+ ///
+ /// 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.
+ ///
+ [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();
+ if (nview == null || !nview.IsValid()) return;
+
+ nview.Register(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);
}
///
@@ -121,6 +152,81 @@ namespace RacesOfValheim
if (monster == null || monster.IsPlayer()) return;
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;
+
+ ///
+ /// True while vanilla is deciding whether '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.
+ ///
+ public static bool PlayerStrikes(Character attacker)
+ {
+ return strikeDepth > 0 && attacker != null && attacker.IsPlayer();
+ }
+
+ ///
+ /// 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.
+ ///
+ [HarmonyPatch]
+ public static class StrikeScope
+ {
+ public static IEnumerable 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--;
+ }
+
+ ///
+ /// 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.
+ ///
+ 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();
}
}
}
diff --git a/JotunnModStub/RaceHostilityManager.cs b/JotunnModStub/RaceHostilityManager.cs
index 03f9fa4..13ed8ed 100644
--- a/JotunnModStub/RaceHostilityManager.cs
+++ b/JotunnModStub/RaceHostilityManager.cs
@@ -22,6 +22,9 @@ namespace RacesOfValheim
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 monster = a.IsPlayer() ? b : (b.IsPlayer() ? a : null);
diff --git a/JotunnModStub/RaceMeleeReach.cs b/JotunnModStub/RaceMeleeReach.cs
index 4b2d66b..4bb0331 100644
--- a/JotunnModStub/RaceMeleeReach.cs
+++ b/JotunnModStub/RaceMeleeReach.cs
@@ -115,15 +115,18 @@ namespace RacesOfValheim
}
}
- /// F8 turns the reach readout on and off.
+ /// The debug key (DebugConfig, F8 by default) turns the reach readout on and off.
[HarmonyPatch(typeof(Player), "Update")]
internal static class RaceMeleeReachDebugKey
{
private static void Postfix(Player __instance)
{
- if (__instance != Player.m_localPlayer || !Input.GetKeyDown(KeyCode.F8)) return;
+ if (__instance != Player.m_localPlayer || !DebugConfig.EnableDebugKey.Value) return;
+ if (!DebugConfig.DebugKey.Value.IsDownIgnoringHeldKeys()) return;
RaceMeleeReach.DebugOn = !RaceMeleeReach.DebugOn;
__instance.Message(MessageHud.MessageType.TopLeft, $"[RoV reach] debug {(RaceMeleeReach.DebugOn ? "on" : "off")}");
+ AlfarMiner.DebugReport(__instance);
+ AlfarDroneAI.DebugReport(__instance);
}
}
}
diff --git a/JotunnModStub/RacesOfValheim.cs b/JotunnModStub/RacesOfValheim.cs
index 70b10b4..6172ff6 100644
--- a/JotunnModStub/RacesOfValheim.cs
+++ b/JotunnModStub/RacesOfValheim.cs
@@ -16,7 +16,7 @@ namespace RacesOfValheim
{
public const string PluginGUID = "com.nandor.racesofvalheim";
public const string PluginName = "Races Of Valheim";
- public const string PluginVersion = "1.6.4";
+ public const string PluginVersion = "1.6.11";
private readonly Harmony harmony = new Harmony(PluginGUID);
@@ -47,6 +47,7 @@ namespace RacesOfValheim
// Not a race either: a tool any race can craft, so it sits beside the vulture rather
// than inside the alphabetical run above.
TrolsHammerConfig.Bind(Config);
+ ShrinkHammerConfig.Bind(Config);
// Not a race either: the two Bone Servants, shared by the Skeleton and Skadi, so they
// bind here rather than inside either race's run.
ButlerConfig.Bind(Config);
@@ -56,6 +57,8 @@ namespace RacesOfValheim
// 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.
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.
ConfigSync.Apply(Config);
harmony.PatchAll();
@@ -75,6 +78,9 @@ namespace RacesOfValheim
PrefabManager.OnVanillaPrefabsAvailable += CreateAllModAssets;
CommandManager.Instance.AddConsoleCommand(new ResetRaceCommand());
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 ResetProgressionCommand());
CommandManager.Instance.AddConsoleCommand(new DumpDvergerCommand());
@@ -306,6 +312,7 @@ namespace RacesOfValheim
AlfarRace.CreateModAssets();
WarVultureItem.Register();
TrolsHammerItem.Register();
+ ShrinkHammerItem.Register();
BoneServant.Register();
}
// --- RACE SELECTION UI ---
diff --git a/JotunnModStub/RacesOfValheim.csproj b/JotunnModStub/RacesOfValheim.csproj
index 66294a4..1659b93 100644
--- a/JotunnModStub/RacesOfValheim.csproj
+++ b/JotunnModStub/RacesOfValheim.csproj
@@ -57,6 +57,7 @@
manager has no extra folder to flatten. Loaded by name: PieceLook.LoadTexture("CookCloth_d.png"). -->
+
diff --git a/JotunnModStub/ShrinkHammer/BuildScale.cs b/JotunnModStub/ShrinkHammer/BuildScale.cs
new file mode 100644
index 0000000..5e778ab
--- /dev/null
+++ b/JotunnModStub/ShrinkHammer/BuildScale.cs
@@ -0,0 +1,211 @@
+using BepInEx.Configuration;
+using HarmonyLib;
+using TMPro;
+using UnityEngine;
+
+namespace RacesOfValheim
+{
+ ///
+ /// What both sizing hammers share: which size the hammer in hand builds at, Alt + scroll to
+ /// change it, the size floating over the ghost, and the "Alt: Size" row in the bottom bar.
+ ///
+ /// Trol's Hammer builds 1 to 3 times the vanilla size, the Shrink Hammer a quarter to 1. Each
+ /// keeps its size in its own config entry, and the wheel writes that entry, so Configuration
+ /// Manager and the wheel never disagree. The entries are not synced: each player picks their own.
+ /// Alt is free in build mode: vanilla's own placing modifier ("AltPlace") is Left Shift.
+ ///
+ public static class BuildScale
+ {
+ public const float Step = 0.05f;
+
+ /// The config entry behind the hammer in hand, or null for any other tool.
+ public static ConfigEntry EntryFor(ItemDrop.ItemData item)
+ {
+ if (TrolsHammerItem.IsTrolsHammer(item)) return TrolsHammerConfig.ScaleFactor;
+ if (ShrinkHammerItem.IsShrinkHammer(item)) return ShrinkHammerConfig.ScaleFactor;
+ return null;
+ }
+
+ /// The multiplier a placement with this item in hand gets: 1 for any other tool.
+ public static float For(ItemDrop.ItemData item)
+ {
+ if (TrolsHammerItem.IsTrolsHammer(item)) return TrolsHammerConfig.ActiveFactor();
+ if (ShrinkHammerItem.IsShrinkHammer(item)) return ShrinkHammerConfig.ActiveFactor();
+ return 1f;
+ }
+
+ public static bool AltHeld() => Input.GetKey(KeyCode.LeftAlt) || Input.GetKey(KeyCode.RightAlt);
+
+ /// Moves the entry by whole steps, kept on the 0.05 grid and inside its range.
+ public static void Nudge(ConfigEntry entry, int steps)
+ {
+ AcceptableValueRange range = entry.Description.AcceptableValues as AcceptableValueRange;
+ float min = range != null ? range.MinValue : 0.25f, max = range != null ? range.MaxValue : 3f;
+ float value = Mathf.Round((entry.Value + steps * Step) / Step) * Step;
+ entry.Value = Mathf.Clamp(value, min, max);
+ }
+
+ // --- the size over the ghost ---
+
+ private static GameObject s_labelled;
+ private static float s_shown;
+
+ ///
+ /// The size in Valheim's own floating NPC text, with one of the two hammers in hand:
+ /// - over the ghost, while the hammer's size differs from its default (1.2 for Trol's
+ /// Hammer, 1 for the Shrink Hammer);
+ /// - with the repair tool selected, over the piece aimed at, always: the size it was built
+ /// at, 1 for a piece no sizing hammer built.
+ /// The text has no timeout, so it is set again only when its piece or the size changes:
+ /// setting it replays its fade-in.
+ ///
+ public static void UpdateLabel(Player player, GameObject ghost)
+ {
+ if (Chat.instance == null) return;
+
+ ConfigEntry entry = player != null && player.InPlaceMode() ? EntryFor(player.RightItem) : null;
+ if (entry == null)
+ {
+ ClearLabel();
+ return;
+ }
+
+ Piece tool = player.GetSelectedPiece();
+ if (tool != null && tool.m_repairPiece)
+ {
+ Piece aimed = player.GetHoveringPiece();
+ if (aimed != null) Show(aimed.gameObject, BuiltSize(aimed));
+ else ClearLabel();
+ return;
+ }
+
+ float value = For(player.RightItem);
+ if (ghost != null && ghost.activeInHierarchy && !Mathf.Approximately(value, (float)entry.DefaultValue))
+ Show(ghost, value);
+ else
+ ClearLabel();
+ }
+
+ /// The size a placed piece was built at, from its ZDO; 1 when no sizing hammer built it.
+ private static float BuiltSize(Piece piece)
+ {
+ ZDO zdo = piece.GetComponent()?.GetZDO();
+ float saved = zdo != null ? zdo.GetFloat(TrolsHammerScaling.ScaleKey, 0f) : 0f;
+ return saved > 0f ? saved : 1f;
+ }
+
+ private static void Show(GameObject target, float value)
+ {
+ if (target == s_labelled && Mathf.Approximately(value, s_shown)) return;
+
+ ClearLabel();
+ Chat.instance.SetNpcText(target, Vector3.up * (TopOf(target) + 0.3f), 30f, 0f, "",
+ ModText.Get("rov_msg_build_scale", value.ToString("0.00")), false);
+ s_labelled = target;
+ s_shown = value;
+ }
+
+ private static void ClearLabel()
+ {
+ if (s_labelled != null && Chat.instance != null) Chat.instance.ClearNpcText(s_labelled);
+ s_labelled = null;
+ }
+
+ /// How far above its pivot the ghost reaches, from its renderers.
+ private static float TopOf(GameObject ghost)
+ {
+ float top = 0.5f;
+ foreach (Renderer renderer in ghost.GetComponentsInChildren())
+ top = Mathf.Max(top, renderer.bounds.max.y - ghost.transform.position.y);
+ return top;
+ }
+ }
+
+ ///
+ /// Alt + scroll in build mode. Vanilla turns the piece with the same wheel in the same method,
+ /// whatever key is held, so the prefix reads the wheel for the size and the postfix puts the
+ /// rotation back as it was.
+ ///
+ [HarmonyPatch(typeof(Player), "UpdatePlacement")]
+ public static class BuildScaleScrollPatch
+ {
+ private static float s_scroll;
+
+ private static void Prefix(Player __instance, bool takeInput, int ___m_placeRotation, out int __state)
+ {
+ __state = ___m_placeRotation;
+ if (!takeInput || __instance != Player.m_localPlayer || !__instance.InPlaceMode()) return;
+ if (!BuildScale.AltHeld()) return;
+ ConfigEntry entry = BuildScale.EntryFor(__instance.RightItem);
+ if (entry == null) return;
+
+ s_scroll += ZInput.GetMouseScrollWheel();
+ if (s_scroll > __instance.m_scrollAmountThreshold) { s_scroll = 0f; BuildScale.Nudge(entry, 1); }
+ if (s_scroll < -__instance.m_scrollAmountThreshold) { s_scroll = 0f; BuildScale.Nudge(entry, -1); }
+ }
+
+ private static void Postfix(Player __instance, int __state, ref int ___m_placeRotation,
+ ref float ___m_scrollCurrAmount, GameObject ___m_placementGhost)
+ {
+ if (__instance != Player.m_localPlayer) return;
+
+ if (BuildScale.AltHeld() && BuildScale.EntryFor(__instance.RightItem) != null)
+ {
+ ___m_placeRotation = __state;
+ ___m_scrollCurrAmount = 0f;
+ }
+ BuildScale.UpdateLabel(__instance, ___m_placementGhost);
+ }
+ }
+
+ ///
+ /// The "Alt: Size" row in the build hints, next to vanilla's "Rotate": a copy of that row (the
+ /// wheel icon and its text), shown only while one of the two hammers is in hand. Added beside the
+ /// vanilla rows rather than through Jotunn's key hints, which replace the whole bar for an item.
+ ///
+ [HarmonyPatch(typeof(KeyHints), "UpdateHints")]
+ public static class BuildScaleKeyHintPatch
+ {
+ private static GameObject s_row;
+ private static bool s_failed;
+
+ private static void Postfix(KeyHints __instance)
+ {
+ if (s_row == null && !s_failed) s_row = MakeRow(__instance);
+ if (s_row == null) return;
+
+ Player player = Player.m_localPlayer;
+ bool show = player != null && BuildScale.EntryFor(player.RightItem) != null;
+ if (s_row.activeSelf != show) s_row.SetActive(show);
+ }
+
+ private static GameObject MakeRow(KeyHints hints)
+ {
+ Transform rotate = hints.m_buildHints != null ? FindDeep(hints.m_buildHints.transform, "rotate") : null;
+ TMP_Text source = rotate != null ? rotate.Find("Text")?.GetComponent() : null;
+ if (source == null)
+ {
+ s_failed = true;
+ Jotunn.Logger.LogWarning("[BuildScale] No rotate row in the build hints; the Alt: Size hint is not shown.");
+ return null;
+ }
+
+ GameObject row = Object.Instantiate(rotate.gameObject, rotate.parent, false);
+ row.name = "RoV_scale";
+ row.transform.SetSiblingIndex(rotate.GetSiblingIndex() + 1);
+ row.transform.Find("Text").GetComponent().text = ModText.Get("rov_hint_build_scale");
+ return row;
+ }
+
+ private static Transform FindDeep(Transform parent, string name)
+ {
+ foreach (Transform child in parent)
+ {
+ if (child.name == name) return child;
+ Transform found = FindDeep(child, name);
+ if (found != null) return found;
+ }
+ return null;
+ }
+ }
+}
diff --git a/JotunnModStub/ShrinkHammer/ShrinkHammerConfig.cs b/JotunnModStub/ShrinkHammer/ShrinkHammerConfig.cs
new file mode 100644
index 0000000..2baceb9
--- /dev/null
+++ b/JotunnModStub/ShrinkHammer/ShrinkHammerConfig.cs
@@ -0,0 +1,33 @@
+using BepInEx.Configuration;
+
+namespace RacesOfValheim
+{
+ ///
+ /// The Shrink Hammer's one number: the size it builds at, from a quarter of the vanilla piece up
+ /// to the vanilla size. Bigger than vanilla is Trol's Hammer's job. Alt + scroll with the hammer
+ /// in hand writes this same entry (BuildScale), so the slider in Configuration Manager and the
+ /// wheel always agree, and the size survives a restart.
+ ///
+ public static class ShrinkHammerConfig
+ {
+ public static ConfigEntry ScaleFactor;
+
+ public static void Bind(ConfigFile config)
+ {
+ ScaleFactor = config.Bind("Shrink Hammer", "Scale factor", 1f,
+ new ConfigDescription("The size of the pieces the Shrink Hammer builds, against the " +
+ "vanilla piece: 1 is vanilla size, 0.25 a quarter. Hold Alt and " +
+ "scroll in build mode to change it in steps of 0.05. Cost and " +
+ "drop never change. A ship keeps its physics at any size.",
+ new AcceptableValueRange(0.25f, 1f)));
+ }
+
+ /// The multiplier a new placement should use; 1 for a value typed into the .cfg
+ /// file that would make a piece too small to see, hit or remove.
+ public static float ActiveFactor()
+ {
+ if (ScaleFactor == null) return 1f;
+ return ScaleFactor.Value > 0.01f ? ScaleFactor.Value : 1f;
+ }
+ }
+}
diff --git a/JotunnModStub/ShrinkHammer/ShrinkHammerItem.cs b/JotunnModStub/ShrinkHammer/ShrinkHammerItem.cs
new file mode 100644
index 0000000..ea1c5a7
--- /dev/null
+++ b/JotunnModStub/ShrinkHammer/ShrinkHammerItem.cs
@@ -0,0 +1,77 @@
+using Jotunn.Configs;
+using Jotunn.Entities;
+using Jotunn.Managers;
+using UnityEngine;
+
+namespace RacesOfValheim
+{
+ ///
+ /// The Shrink Hammer: the builder's hammer for small work, down to a quarter of the vanilla size.
+ /// Any race can craft it. Built the same way as : a clone of the
+ /// vanilla Hammer that keeps the vanilla piece table, so every piece, including those other mods
+ /// add, is in its menu at the same cost. The size lives on the placement (TrolsHammerPatches,
+ /// BuildScale), never on the piece prefabs.
+ ///
+ public static class ShrinkHammerItem
+ {
+ public const string PrefabName = "ShrinkHammer";
+ public const string DisplayName = "$rov_item_shrinkhammer_name";
+
+ private const string SourcePrefab = "Hammer";
+ private const string Label = "ShrinkHammer";
+
+ public static void Register()
+ {
+ GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(PrefabName, SourcePrefab);
+ ItemDrop drop = prefab != null ? prefab.GetComponent() : null;
+ if (drop == null || drop.m_itemData == null || drop.m_itemData.m_shared == null)
+ {
+ Jotunn.Logger.LogWarning($"[{Label}] Could not clone {SourcePrefab}; {DisplayName} not registered.");
+ return;
+ }
+
+ ItemDrop.ItemData.SharedData shared = drop.m_itemData.m_shared;
+ shared.m_name = DisplayName;
+ shared.m_description = "$rov_item_shrinkhammer_desc";
+ Sprite icon = HammerIcon.Load("ShrinkHammer_icon.png");
+ if (icon != null) shared.m_icons = new[] { icon };
+
+ ItemManager.Instance.AddItem(new CustomItem(prefab, fixReference: false));
+ ItemManager.Instance.AddRecipe(new CustomRecipe(new RecipeConfig
+ {
+ Item = PrefabName,
+ Amount = 1,
+ CraftingStation = CraftingStations.Workbench,
+ MinStationLevel = 1,
+ Requirements = new[]
+ {
+ new RequirementConfig("FineWood", 2, 0, true),
+ new RequirementConfig("Resin", 2, 0, true),
+ },
+ }));
+
+ Jotunn.Logger.LogInfo($"[{Label}] {DisplayName} registered on the vanilla hammer's piece table.");
+ }
+
+ /// Whether an item in hand is this hammer; the display name is the fallback for an
+ /// ItemData built before ObjectDB finished, as in TrolsHammerItem.
+ public static bool IsShrinkHammer(ItemDrop.ItemData item)
+ {
+ if (item == null) return false;
+ if (item.m_dropPrefab != null) return item.m_dropPrefab.name == PrefabName;
+ return item.m_shared != null && item.m_shared.m_name == DisplayName;
+ }
+ }
+
+ /// The two hammers' own icons, painted offline (scripts/paint_hammer_icons.py) and
+ /// embedded in the DLL.
+ internal static class HammerIcon
+ {
+ public static Sprite Load(string resource)
+ {
+ Texture2D texture = PieceLook.LoadTexture(resource);
+ if (texture == null) return null;
+ return Sprite.Create(texture, new Rect(0f, 0f, texture.width, texture.height), new Vector2(0.5f, 0.5f));
+ }
+ }
+}
diff --git a/JotunnModStub/Skadi/DrakeFormBehavior.cs b/JotunnModStub/Skadi/DrakeFormBehavior.cs
index c66e735..b76674f 100644
--- a/JotunnModStub/Skadi/DrakeFormBehavior.cs
+++ b/JotunnModStub/Skadi/DrakeFormBehavior.cs
@@ -45,21 +45,37 @@ namespace RacesOfValheim
// level for a short window past this before letting it start sinking.
public float LastPoweredTime { get; set; }
- // The drake's numbers for DirectedFlightPatch. Base flight stays free on purpose - the
- // drake arrives at the Elder, long before the player has the stamina pool to pay for
- // simply staying airborne - so only the sprint costs anything.
- public float TurnSpeed => SkadiConfig.FlightTurnSpeed.Value;
- public float GlideSpeed => SkadiConfig.FlightGlideSpeed.Value;
- public float BoostSpeed => SkadiConfig.FlightBoostSpeed.Value;
- public float SprintSpeed => SkadiConfig.FlightSprintSpeed.Value;
- public float ReverseSpeed => SkadiConfig.FlightReverseSpeed.Value;
+ // This form's numbers for DirectedFlightPatch. The Drake's base flight defaults to free on
+ // purpose - it arrives at the Elder, long before the player has the stamina pool to pay
+ // for simply staying airborne - so only its sprint costs anything. The Moder pays for
+ // every beat. The Fader never flies, so it falls back on the Drake's set unread.
+ private SkadiConfig.FormFlight Flight =>
+ formRules != null && formRules.Form == SkadiProgression.FormType.Moder ? SkadiConfig.ModerFlight : SkadiConfig.DrakeFlight;
+
+ 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
// wings are dragging themselves free, not racing.
- public float LiftoffSpeed => SkadiConfig.FlightLiftoffSpeed.Value;
- public float HoverSeconds => SkadiConfig.FlightHoverSeconds.Value;
- public float PoweredStaminaPerSecond => 0f;
- public float SprintStaminaPerSecond => SkadiConfig.FlightSprintStaminaPerSecond.Value;
- public bool CanPower => true;
+ public float LiftoffSpeed => Flight.LiftoffSpeed.Value;
+ public float HoverSeconds => Flight.HoverSeconds.Value;
+ public float PoweredStaminaPerSecond => Flight.PoweredStaminaPerSecond.Value * EncumberedCostFactor();
+ public float SprintStaminaPerSecond => Flight.SprintStaminaPerSecond.Value * EncumberedCostFactor();
+ 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;
@@ -171,7 +187,11 @@ namespace RacesOfValheim
(SkadiConfig.FlightToggleKey.Value.IsDownIgnoringHeldKeys() || RaceInput.PadAttackDown(1)) &&
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;
LastPoweredTime = Time.time;
@@ -291,6 +311,29 @@ namespace RacesOfValheim
return true;
}
+ ///
+ /// 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.
+ ///
+ 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;
+
+ ///
+ /// 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.
+ ///
+ private IEnumerator WaitForHit(int baseline, float started)
+ {
+ while (AttackEvents == baseline && Time.time - started < HitEventTimeout) yield return null;
+ }
+
private IEnumerator PerformAttackCoroutine(int button)
{
lastAttackTime = Time.time;
@@ -389,13 +432,18 @@ namespace RacesOfValheim
breathingUntil = Time.time + projDelay + projCount * 0.05f + 0.5f;
}
+ int hitBaseline = AttackEvents;
+ float triggeredAt = Time.time;
SetAttackTrigger(attackTrigger);
- yield return new WaitForSeconds(projDelay);
-
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)
@@ -495,13 +543,18 @@ namespace RacesOfValheim
breathingUntil = Time.time + projDelay + projCount * 0.05f + 0.5f;
}
+ int hitBaseline = AttackEvents;
+ float triggeredAt = Time.time;
SetAttackTrigger(attackTrigger);
- yield return new WaitForSeconds(projDelay);
-
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)
@@ -563,7 +616,28 @@ namespace RacesOfValheim
// 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
// 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";
+
+ ///
+ /// 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.
+ ///
+ 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;
@@ -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");
Collider[] hits = Physics.OverlapSphere(attackPoint, radius, layerMask);
+ FormMelee.LogSwing(FormLabel, hits.Length);
+ ItemDrop.ItemData.SharedData shared = FormMelee.CreatureWeapon(weapon);
System.Collections.Generic.HashSet hitObjects = new System.Collections.Generic.HashSet();
+ bool hitCreature = false;
foreach (Collider hit in hits)
{
@@ -592,18 +669,29 @@ namespace RacesOfValheim
if (characterTarget != null && characterTarget == Player.m_localPlayer) continue;
GameObject targetObj = (target as MonoBehaviour)?.gameObject;
- if (targetObj != null)
- {
- if (hitObjects.Contains(targetObj)) continue;
- hitObjects.Add(targetObj);
- }
+ // 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 (targetObj != null && hitObjects.Contains(targetObj)) continue;
Vector3 targetCenter = hit.bounds.center;
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;
- 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();
// Frost-flavoured maul; SkadiDamagePatch tops this up with the per-tier frost bonus.
@@ -619,9 +707,15 @@ namespace RacesOfValheim
hitData.m_toolTier = 0;
hitData.SetAttacker(Player.m_localPlayer);
+ if (targetObj != null) hitObjects.Add(targetObj);
+ FormMelee.LogHit(FormLabel, target, totalDamage);
target.Damage(hitData);
FormMelee.GrantAdrenaline(target);
+ shared?.m_hitEffect.Create(targetCenter, Quaternion.identity);
+ if (characterTarget != null) hitCreature = true;
}
+
+ if (hitCreature) FormMelee.RaiseSkill(Skills.SkillType.Unarmed);
}
private void OnDestroy()
diff --git a/JotunnModStub/Skadi/SkadiConfig.cs b/JotunnModStub/Skadi/SkadiConfig.cs
index 133d7c1..8efb771 100644
--- a/JotunnModStub/Skadi/SkadiConfig.cs
+++ b/JotunnModStub/Skadi/SkadiConfig.cs
@@ -69,15 +69,38 @@ namespace RacesOfValheim
public static ConfigEntry FaderSpinDamage;
public static ConfigEntry FaderSpinRadius;
- // ─── Directed flight (Drake/Moder) ────────────────────────────────────
- public static ConfigEntry FlightTurnSpeed;
- public static ConfigEntry FlightGlideSpeed;
- public static ConfigEntry FlightBoostSpeed;
- public static ConfigEntry FlightSprintSpeed;
- public static ConfigEntry FlightReverseSpeed;
- public static ConfigEntry FlightLiftoffSpeed;
- public static ConfigEntry FlightHoverSeconds;
- public static ConfigEntry FlightSprintStaminaPerSecond;
+ // ─── Dragon forms: flight and timing, one set per form ───────────────────
+ // One section for all three, as Dissolution asked for the bat's knobs on each form: the
+ // keys carry the form's name and an Order, so Configuration Manager lists Drake, then
+ // Moder, then Fader instead of mixing them alphabetically.
+ public class FormFlight
+ {
+ public ConfigEntry TurnSpeed;
+ public ConfigEntry GlideSpeed;
+ public ConfigEntry BoostSpeed;
+ public ConfigEntry SprintSpeed;
+ public ConfigEntry ReverseSpeed;
+ public ConfigEntry LiftoffSpeed;
+ public ConfigEntry HoverSeconds;
+ public ConfigEntry PoweredStaminaPerSecond;
+ public ConfigEntry SprintStaminaPerSecond;
+ public ConfigEntry Encumbered;
+ public ConfigEntry EncumberedExtraCost;
+ }
+
+ public class FormTiming
+ {
+ // -1 keeps the boss-tier table in SkadiProgression, so an untouched .cfg plays as before.
+ public ConfigEntry MaxDuration;
+ public ConfigEntry DurationPerState;
+ public ConfigEntry 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)
{
@@ -164,23 +187,69 @@ namespace RacesOfValheim
FaderSpinRadius = config.Bind(attacks, "Fader Spin Radius", 5f,
new ConfigDescription("Hit-sweep radius for the Skeleton Dragon's spin attack.", new AcceptableValueRange(1f, 15f)));
- const string flight = "Skadi - Directed Flight";
- FlightTurnSpeed = config.Bind(flight, "Turn Speed", 120f,
- new ConfigDescription("Degrees per second the dragon form turns to face its heading.", new AcceptableValueRange(10f, 360f)));
- FlightGlideSpeed = config.Bind(flight, "Glide Speed", 5f,
- new ConfigDescription("Speed while gliding unpowered (no W/S held).", new AcceptableValueRange(0f, 30f)));
- FlightBoostSpeed = config.Bind(flight, "Boost Speed", 12f,
- new ConfigDescription("Speed while holding W without sprinting.", new AcceptableValueRange(0f, 50f)));
- FlightSprintSpeed = config.Bind(flight, "Sprint Speed", 22f,
- new ConfigDescription("Speed while holding W and Shift, stamina permitting.", new AcceptableValueRange(0f, 60f)));
- FlightReverseSpeed = config.Bind(flight, "Reverse Speed", 7f,
- new ConfigDescription("Speed while beating backwards (S).", new AcceptableValueRange(0f, 30f)));
- FlightLiftoffSpeed = config.Bind(flight, "Liftoff Speed", 9f,
- new ConfigDescription("Climb speed while clawing out of water.", new AcceptableValueRange(0f, 30f)));
- FlightHoverSeconds = config.Bind(flight, "Hover Seconds", 5f,
- new ConfigDescription("How long level flight holds altitude after the last powered input before it starts to sink.", new AcceptableValueRange(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(0f, 60f)));
+ // Was "Skadi - Directed Flight", one set of numbers for both flying forms. The Drake is
+ // the scout: quick, nimble, free to fly, grounded by a heavy pack. The Moder is the
+ // freighter: slow to turn and paying for every beat, but it lifts what the Drake cannot.
+ const string forms = "Skadi - Dragon Forms";
+ int order = 1000;
+ DrakeFlight = BindFlight(config, forms, "Drake", ref order,
+ turn: 180f, glide: 6f, boost: 14f, sprint: 26f, reverse: 8f, liftoff: 9f, hover: 3f,
+ powered: 0f, sprintCost: 10f, encumbered: AswidConfig.EncumberedMode.Blocked, extraCost: 0.25f);
+ DrakeTiming = BindTiming(config, forms, "Drake", ref order);
+ ModerFlight = BindFlight(config, forms, "Moder", ref order,
+ turn: 80f, glide: 5f, boost: 10f, sprint: 18f, reverse: 6f, liftoff: 9f, hover: 8f,
+ powered: 3f, sprintCost: 15f, encumbered: AswidConfig.EncumberedMode.Allowed, extraCost: 0.25f);
+ ModerTiming = BindTiming(config, forms, "Moder", ref order);
+ FaderTiming = BindTiming(config, forms, "Fader", ref order);
+ }
+
+ 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(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(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(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(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(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(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(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(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(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(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(-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(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(-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)
diff --git a/JotunnModStub/Skadi/SkadiPatches.cs b/JotunnModStub/Skadi/SkadiPatches.cs
index 94b1c56..b7560c2 100644
--- a/JotunnModStub/Skadi/SkadiPatches.cs
+++ b/JotunnModStub/Skadi/SkadiPatches.cs
@@ -408,7 +408,11 @@ namespace RacesOfValheim
public static bool Prefix(Humanoid __instance)
{
if (__instance != Player.m_localPlayer) return true;
- return __instance.GetComponentInChildren() == null;
+ if (__instance.GetComponentInChildren() == null) return true;
+
+ // The dragon's own clip calling its blow: the hit cue for the form's melee.
+ DrakeFormBehavior.NotifyAttackTrigger();
+ return false;
}
}
}
diff --git a/JotunnModStub/Skadi/SkadiProgression.cs b/JotunnModStub/Skadi/SkadiProgression.cs
index 63abac7..26a2579 100644
--- a/JotunnModStub/Skadi/SkadiProgression.cs
+++ b/JotunnModStub/Skadi/SkadiProgression.cs
@@ -85,7 +85,9 @@ namespace RacesOfValheim
rules.Form = FormType.Drake;
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)
@@ -112,7 +114,9 @@ namespace RacesOfValheim
rules.CooldownMinutes = 10f;
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)
@@ -125,7 +129,27 @@ namespace RacesOfValheim
rules.CooldownMinutes = 0f;
rules.CanAttackInForm = true;
}
- return rules.Form != FormType.None ? rules : null;
+ if (rules.Form == FormType.None) return null;
+ ApplyTiming(rules, SkadiConfig.FaderTiming, state);
+ return rules;
+ }
+
+ ///
+ /// 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.
+ ///
+ 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;
}
}
}
diff --git a/JotunnModStub/Skadi/SkadiRace.cs b/JotunnModStub/Skadi/SkadiRace.cs
index 8a5ff45..820a80a 100644
--- a/JotunnModStub/Skadi/SkadiRace.cs
+++ b/JotunnModStub/Skadi/SkadiRace.cs
@@ -79,11 +79,11 @@ namespace RacesOfValheim
// drake one used for the passive blessing.
Sprite dragonIcon = GetItemIcon("TrophyDragonQueen") ?? GetItemIcon("TrophyHatchling");
- skadiCdSE = ScriptableObject.CreateInstance();
- skadiCdSE.name = "SE_SkadiCooldown";
- skadiCdSE.m_name = "$rov_se_skadi_formcd_name";
- skadiCdSE.m_icon = dragonIcon;
- ItemManager.Instance.AddStatusEffect(new CustomStatusEffect(skadiCdSE, fixReference: false));
+ // One cooldown per form, so a Drake cooldown set in the config never holds the Moder
+ // back, nor the other way round. The Moder keeps the original name.
+ skadiCdSE = RegisterFormCooldown(SkadiProgression.FormType.Moder, "$rov_se_skadi_formcd_name", dragonIcon);
+ RegisterFormCooldown(SkadiProgression.FormType.Drake, "$rov_se_skadi_drakecd_name", GetItemIcon("TrophyHatchling") ?? dragonIcon);
+ RegisterFormCooldown(SkadiProgression.FormType.SkeletonDragon, "$rov_se_skadi_fadercd_name", GetItemIcon("TrophyFader") ?? dragonIcon);
skadiFormSE = ScriptableObject.CreateInstance();
skadiFormSE.name = "SE_SkadiForm";
@@ -124,6 +124,26 @@ namespace RacesOfValheim
if (se != null) se.m_ttl = seconds;
}
+ private static SE_FormCooldown RegisterFormCooldown(SkadiProgression.FormType form, string displayName, Sprite icon)
+ {
+ SE_FormCooldown cd = ScriptableObject.CreateInstance();
+ 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)
{
GameObject trophy = PrefabManager.Cache.GetPrefab(prefabName)?.gameObject;
@@ -687,7 +707,7 @@ namespace RacesOfValheim
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)
{
float m_time = HarmonyLib.Traverse.Create(cdSE).Field