diff --git a/.gitignore b/.gitignore
index e1a2a2e..f7973c2 100644
--- a/.gitignore
+++ b/.gitignore
@@ -27,6 +27,4 @@ Thumbs.db
*.lnk
# How to setup Configuration Manager
-CONFIGURATION-MANAGER-HOWTO.md
-# Written by scripts/publish.* on a Release build from the root README; never edit or commit it.
-/JotunnModStub/Package/README.md
+CONFIGURATION-MANAGER-HOWTO.md
\ No newline at end of file
diff --git a/JotunnModStub/Alfar/AlfarArchon.cs b/JotunnModStub/Alfar/AlfarArchon.cs
index 079d7a6..0be4415 100644
--- a/JotunnModStub/Alfar/AlfarArchon.cs
+++ b/JotunnModStub/Alfar/AlfarArchon.cs
@@ -119,10 +119,7 @@ namespace RacesOfValheim
if (Time.time >= nextPulse)
{
nextPulse = Time.time + AlfarPowerConfig.ArchonPulseInterval.Value;
- // The pulse fires on its own while the form lasts, so it earns what an aura does:
- // a tenth of a hit per second, once per pulse that struck something.
- if (AlfarPowers.Pulse(player, AlfarPowerConfig.ArchonPulseRadius.Value, AlfarPowerConfig.ArchonPulseDamage.Value))
- FormMelee.RaiseSkill(Skills.SkillType.ElementalMagic, 0.1f * AlfarPowerConfig.ArchonPulseInterval.Value);
+ AlfarPowers.Pulse(player, AlfarPowerConfig.ArchonPulseRadius.Value, AlfarPowerConfig.ArchonPulseDamage.Value);
}
}
diff --git a/JotunnModStub/Alfar/AlfarChestGlow.cs b/JotunnModStub/Alfar/AlfarChestGlow.cs
deleted file mode 100644
index dc529ff..0000000
--- a/JotunnModStub/Alfar/AlfarChestGlow.cs
+++ /dev/null
@@ -1,79 +0,0 @@
-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 9efa86a..e8fc1d9 100644
--- a/JotunnModStub/Alfar/AlfarChests.cs
+++ b/JotunnModStub/Alfar/AlfarChests.cs
@@ -61,15 +61,12 @@ namespace RacesOfValheim
public static void Register()
{
RegisterOne(EntryName, "$rov_piece_alfar_inngangskista_name", "$rov_piece_alfar_inngangskista_desc",
- "$rov_hover_alfar_inngangskista", new Color(0.62f, 0.80f, 1f, 1f),
- AlfarInputChest.Build, "AlfarInputChest_icon.png");
+ new Color(0.62f, 0.80f, 1f, 1f));
RegisterOne(WoodName, "$rov_piece_alfar_eldividarkista_name", "$rov_piece_alfar_eldividarkista_desc",
- "$rov_hover_alfar_eldividarkista", new Color(0.85f, 0.62f, 0.36f, 1f),
- AlfarFireChest.Build, "AlfarFireChest_icon.png");
+ new Color(0.85f, 0.62f, 0.36f, 1f));
}
- private static void RegisterOne(string pieceName, string display, string description, string hoverName, Color tint,
- System.Func build, string iconResource)
+ private static void RegisterOne(string pieceName, string display, string description, Color tint)
{
GameObject source = PrefabManager.Cache.GetPrefab("piece_chest_wood");
if (source == null)
@@ -94,19 +91,15 @@ 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 = hoverName;
+ if (container != null) container.m_name = display;
Piece piece = prefab.GetComponent();
if (piece == null) { Jotunn.Logger.LogWarning("[Alfar] The chest has no Piece: " + pieceName); return; }
piece.m_name = display;
piece.m_description = description;
- // 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;
+ AlfarConstructs.Tint(prefab, tint);
PieceManager.Instance.AddPiece(new CustomPiece(prefab, fixReference: false, new PieceConfig
{
@@ -114,7 +107,7 @@ namespace RacesOfValheim
Description = description,
PieceTable = PieceTables.Hammer,
Category = PieceCategories.Crafting,
- Icon = icon,
+ Icon = piece.m_icon,
Requirements = requirements.ToArray(),
}));
@@ -137,12 +130,5 @@ 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/AlfarConfig.cs b/JotunnModStub/Alfar/AlfarConfig.cs
index 558c0a7..1769a1a 100644
--- a/JotunnModStub/Alfar/AlfarConfig.cs
+++ b/JotunnModStub/Alfar/AlfarConfig.cs
@@ -39,26 +39,17 @@ namespace RacesOfValheim
public static ConfigEntry WidthScale;
///
- /// Scales the almond eyes (EyeExtent). The default 0.8 is the tuned grey look; raise it for
- /// bigger eyes.
+ /// 1 is the Sverm's size, which is what the design asked to try first ("se non va li
+ /// allarghiamo"). Raise it to enlarge the eyes: 1.6 is roughly a grey from the films.
///
public static ConfigEntry EyeSizeMultiplier;
- // A grey's eyes, on the Sverm's eye spot: offsets are metres in the head bone's OWN frame
- // at human scale, so they land on the same part of the face at any body scale.
- // Pushed apart and forward of the Sverm's, because an almond this wide would otherwise
- // meet its twin over the nose and sink into the cheek.
- public const float EyeSeparation = 0.037f;
- public const float EyeForward = 0.090f;
- public const float EyeHeight = 0.183f;
-
- // Full width, height and depth of one eye in metres at Eye Size Multiplier 1. The saved
- // default of 0.8 makes that 50 x 28 x 18 mm.
- public static readonly Vector3 EyeExtent = new Vector3(0.0625f, 0.035f, 0.0225f);
-
- // Degrees. Slant raises the outer corner; wrap turns each eye out toward its temple.
- public const float EyeSlant = 22f;
- public const float EyeWrap = 20f;
+ // The eye geometry is the Sverm's, unchanged (SvermVisuals): offsets are metres in the head
+ // bone's OWN frame, so they land on the same part of the face at any body scale.
+ public const float EyeSeparation = 0.032f;
+ public const float EyeForward = 0.081f;
+ public const float EyeHeight = 0.181f;
+ public const float EyeSize = 0.062f;
// ─── Eitr: diet, shield, soft fall ───────────────────────────────────
@@ -161,7 +152,7 @@ namespace RacesOfValheim
new AcceptableValueRange(0.7f, 1.2f)));
EyeSizeMultiplier = config.Bind(look, "Eye Size Multiplier", 0.8f,
- new ConfigDescription("Scales the black almond eyes. 0.8 is the default look; raise it for bigger eyes.",
+ new ConfigDescription("1 = the Sverm's eye size; 0.8 is slightly smaller. Raise to enlarge the black eyes.",
new AcceptableValueRange(0.5f, 3f)));
}
}
diff --git a/JotunnModStub/Alfar/AlfarDroneAI.cs b/JotunnModStub/Alfar/AlfarDroneAI.cs
index b319ceb..59d8fea 100644
--- a/JotunnModStub/Alfar/AlfarDroneAI.cs
+++ b/JotunnModStub/Alfar/AlfarDroneAI.cs
@@ -58,13 +58,6 @@ 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();
@@ -148,7 +141,6 @@ namespace RacesOfValheim
private float m_nextFightScan;
private float m_fightUntil;
- private bool m_fighting;
private ZNetView m_nview;
private Character m_character;
@@ -176,11 +168,6 @@ 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;
@@ -213,16 +200,6 @@ 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()
@@ -316,17 +293,7 @@ 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;
@@ -334,43 +301,20 @@ namespace RacesOfValheim
else if (Time.time >= m_nextFightScan)
{
m_nextFightScan = Time.time + FightScanInterval;
- // FindClosestEnemy takes its first match at ANY distance (it only compares against
- // maxDistance once it holds one), so with a deer anywhere in the loaded zones it never
- // returned null and vanilla kept the tick: the drone idled about instead of working.
- Character enemy = BaseAI.FindClosestEnemy(m_character, transform.position, FightRange);
- if (enemy != null && Vector3.Distance(enemy.transform.position, transform.position) <= FightRange)
+ if (BaseAI.FindClosestEnemy(m_character, transform.position, FightRange) != null)
{
m_fightUntil = Time.time + FightLinger;
}
}
- 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;
- }
+ if (Time.time >= m_fightUntil) 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.
@@ -445,34 +389,17 @@ 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)
{
- job = Time.time < m_farmReadyAt
+ m_job = Time.time < m_farmReadyAt
? new Job { Kind = "wait", Point = transform.position, Label = "Waiting" }
: new Job { Kind = "farm_finish", Point = m_farmSpot.Value, Label = "Gathering" };
+ return;
}
- // A delivery is a job like any other and gets its own clock. It used to return early here
- // and inherit the load's deadline: a slow trip, or a fight on the way, left it already late,
- // so it timed out on the first tick, was planned again, timed out again, every frame - the
- // drone froze with wood in hand next to the kiln (10790 timeouts in one player's log).
- else if (m_payload.Count > 0) job = PlanDelivery(anchor.Value);
- else job = PlanWork(anchor.Value);
- if (job != null && (m_job == null || m_job.Kind != job.Kind || m_job.Target != job.Target))
- {
- m_jobDeadline = Time.time + JobTimeout;
- }
- if (m_job != null && !ReferenceEquals(m_job, job)) Release(m_job.Claim);
- if (job != null) Claim(job.Claim);
- m_job = job;
- }
-
- private Job PlanWork(Vector3 anchor)
- {
+ if (m_payload.Count > 0) { m_job = PlanDelivery(anchor.Value); return; }
// The forge has no clock: a smelter holds its ore indefinitely and puts its own output on
// the floor, so PlanRescue would ask a question whose answer is always no. The smith is a
@@ -488,7 +415,15 @@ namespace RacesOfValheim
// base: repairs, the fields, and last the tidying of the entry chest.
Job job = PlanRescue();
job = job ?? PlanCollect() ?? PlanFuel() ?? PlanLoad();
- return job ?? PlanRepair(anchor) ?? PlanFarm(anchor) ?? PlanSort();
+ 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;
}
///
@@ -617,7 +552,7 @@ namespace RacesOfValheim
Kind = "collect",
Target = best.Id,
Claim = best.Id,
- Point = ApproachPoint(best),
+ Point = best.Position,
Hurry = true,
Label = "Saving the food",
};
@@ -648,7 +583,7 @@ namespace RacesOfValheim
Kind = "collect",
Target = best.Id,
Claim = best.Id,
- Point = ApproachPoint(best),
+ Point = best.Position,
Label = "Collecting",
};
}
@@ -778,37 +713,20 @@ 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) && !unreachable)
+ if (station != null && station.Alive && station.Operable && AcceptsAnything(station))
{
return new Job
{
Kind = "deposit_station",
Target = target,
- Point = ApproachPoint(station),
+ Point = station.Position,
Label = "Loading " + Describe(),
};
}
// The station is gone, full or cold. The goods are ours to put back, not to hold.
m_nview.GetZDO().Set(KeyTarget, ZDOID.None);
-
- // 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();
@@ -841,7 +759,7 @@ namespace RacesOfValheim
{
Kind = "deposit_station",
Target = consumer.Id,
- Point = ApproachPoint(consumer),
+ Point = consumer.Position,
Label = "Loading " + Describe(),
};
}
@@ -1500,25 +1418,16 @@ 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))
- {
- if (!spoke) spoke = Say("rov_msg_alfar_drone_sort_keep", name, KeepRepeatSeconds);
- continue;
- }
+ if (!IsWood(name) && AnyStationAccepts(name)) continue;
Container destination = DestinationFor(name);
- if (destination == null)
- {
- if (!spoke) spoke = Say("rov_msg_alfar_drone_sort_nowhere", name, NowhereRepeatSeconds);
- continue;
- }
+ if (destination == null) continue;
m_sortItem = name;
m_sortDest = ZdoOf(destination);
@@ -1534,119 +1443,6 @@ 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;
@@ -1667,169 +1463,6 @@ 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
@@ -2000,7 +1633,7 @@ namespace RacesOfValheim
"Wood", "FineWood", "RoundLog", "ElderBark", "YggdrasilWood", "Blackwood",
};
- internal static bool IsWood(string prefabName) => s_woodFamily.Contains(prefabName);
+ private static bool IsWood(string prefabName) => s_woodFamily.Contains(prefabName);
///
/// The first thing a station will take, and the chest it is in: raw material from the ENTRY chest
diff --git a/JotunnModStub/Alfar/AlfarDrones.cs b/JotunnModStub/Alfar/AlfarDrones.cs
index 669d0c0..7cef524 100644
--- a/JotunnModStub/Alfar/AlfarDrones.cs
+++ b/JotunnModStub/Alfar/AlfarDrones.cs
@@ -105,10 +105,6 @@ 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))
{
@@ -255,100 +251,34 @@ namespace RacesOfValheim
public float Radius = 12f;
public float LiveSeconds = 120f;
- // The job lives in the drone's ZDO, not only in these fields: Valheim destroys a creature
- // when its zone unloads and builds a fresh one when the zone comes back, and the fresh
- // one had a zero Centre, so it searched around the world origin and stood idle. The
- // birth time is network time, so a rebuilt drone does not get a new two minutes either.
- private static readonly int CentreKey = "rov_graf_centre".GetStableHashCode();
- private static readonly int RadiusKey = "rov_graf_radius".GetStableHashCode();
- private static readonly int LifeKey = "rov_graf_life".GetStableHashCode();
- private static readonly int BornKey = "rov_graf_born".GetStableHashCode();
-
- private const float Reach = 4f;
-
- private bool loaded;
- private double bornAt;
+ private float born;
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 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)
+ private void Start()
{
- 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;
+ born = Time.time;
}
public bool Tick(MonsterAI ai, float dt)
{
- if (!loaded) Load();
-
- if (Now - bornAt >= LiveSeconds)
+ if (Time.time - born >= LiveSeconds)
{
ZNetView nview = GetComponent();
if (nview != null && nview.IsValid() && nview.IsOwner()) ZNetScene.instance.Destroy(gameObject);
return true;
}
- // A deposit another drone just broke is still there until the end of the frame, with a
- // dead network view: drop it and look again.
- if (target == null || !target.gameObject.activeInHierarchy || !Live(target)) target = FindDeposit();
- Vector3 point = Vector3.zero;
- Collider area = target != null ? NearestArea(target, out point) : null;
- if (area == null) { target = null; ai.StopMoving(); return true; }
+ if (target == null || !target.gameObject.activeInHierarchy) target = FindDeposit();
+ if (target == null) { ai.StopMoving(); return true; }
- // Measured to the closest point of the rock, not to its root: a copper deposit's root
- // sits at its base inside the mesh, so a drone aiming there stopped on top of the rock
- // and never came within reach.
+ Vector3 point = target.transform.position;
float distance = Vector3.Distance(transform.position, point);
- lastDistance = distance;
- if (distance > Reach)
+ if (distance > 3.5f)
{
if (MoveToMethod != null) MoveToMethod.Invoke(ai, new object[] { dt, point + Vector3.up * 1.5f, 2f, true });
return true;
@@ -357,30 +287,15 @@ namespace RacesOfValheim
ai.StopMoving();
if (Time.time < nextStrike) return true;
nextStrike = Time.time + 1f;
- Strike(target, area, point);
- strikes++;
+ Strike(target);
return true;
}
private static string[] names;
- private static string namesSource;
+ private static string[] Deposits => names ?? (names = AlfarNexusConfig.MinerDeposits.Value.Split(
+ new[] { ',' }, System.StringSplitOptions.RemoveEmptyEntries));
- // 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)
+ private bool IsPrecious(string prefabName)
{
foreach (string wanted in Deposits)
{
@@ -395,11 +310,12 @@ namespace RacesOfValheim
float bestDistance = float.MaxValue;
foreach (Collider collider in Physics.OverlapSphere(Centre, Radius, ~0, QueryTriggerInteraction.Ignore))
{
- Component deposit = DepositOf(collider);
+ Component deposit = collider.GetComponentInParent();
+ if (deposit == null) deposit = collider.GetComponentInParent();
+ if (deposit == null) deposit = collider.GetComponentInParent();
if (deposit == null) continue;
- if (!Live(deposit)) continue;
- string prefabName = DepositName(deposit);
+ string prefabName = Utils.GetPrefabName(deposit.gameObject);
if (!IsPrecious(prefabName)) continue;
float distance = Vector3.Distance(transform.position, deposit.transform.position);
@@ -408,289 +324,28 @@ namespace RacesOfValheim
return best;
}
- ///
- /// The live hit area of the deposit closest to the drone, and the closest point on it.
- /// MineRock and MineRock5 only take a hit on one of their own areas; a MineRock with an area
- /// root (tin) keeps its base model collider apart, and a hit on that one is thrown away.
- /// Broken areas are switched off, so only active colliders count.
- ///
- private Collider NearestArea(Component deposit, out Vector3 point)
- {
- point = Vector3.zero;
- MineRock rock = deposit as MineRock;
- GameObject root = rock != null && rock.m_areaRoot != null ? rock.m_areaRoot : deposit.gameObject;
-
- Collider best = null;
- float bestDistance = float.MaxValue;
- foreach (Collider collider in root.GetComponentsInChildren())
- {
- if (collider == null || !collider.enabled) continue;
- Vector3 closest = collider.bounds.ClosestPoint(transform.position);
- float distance = Vector3.Distance(transform.position, closest);
- if (distance < bestDistance) { best = collider; bestDistance = distance; point = closest; }
- }
- return best;
- }
-
- private void Strike(Component deposit, Collider area, Vector3 point)
+ private void Strike(Component deposit)
{
IDestructible destructible = deposit as IDestructible;
- if (destructible == null) { lastHit = $"{deposit.GetType().Name} is not IDestructible"; return; }
+ if (destructible == null) return;
HitData hit = new HitData();
hit.m_damage.m_pickaxe = AlfarNexusConfig.MinerDamage.Value;
hit.m_toolTier = 100;
hit.m_dodgeable = false;
hit.m_blockable = false;
- hit.m_hitCollider = area;
- hit.m_point = point;
- hit.m_dir = (area.bounds.center - transform.position).normalized;
- // Vanilla MineRock (tin) reads the attacker's ZDOID for its hit effects without a null
- // check: a hit with no attacker throws before the area can break.
- hit.SetAttacker(GetComponent());
+ hit.m_point = deposit.transform.position;
+ hit.m_dir = (deposit.transform.position - transform.position).normalized;
- // 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
+ // MineRock5 picks the piece of the rock to hurt from the collider that was hit.
+ Collider collider = deposit.GetComponentInChildren();
+ if (collider != null)
{
- 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;
+ hit.m_hitCollider = collider;
+ hit.m_point = collider.bounds.center;
}
- 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);
- }
+ destructible.Damage(hit);
}
[HarmonyPatch(typeof(MonsterAI), "UpdateAI")]
diff --git a/JotunnModStub/Alfar/AlfarFireChest.cs b/JotunnModStub/Alfar/AlfarFireChest.cs
deleted file mode 100644
index ffff98a..0000000
--- a/JotunnModStub/Alfar/AlfarFireChest.cs
+++ /dev/null
@@ -1,166 +0,0 @@
-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
deleted file mode 100644
index 6f4ea39..0000000
--- a/JotunnModStub/Alfar/AlfarInputChest.cs
+++ /dev/null
@@ -1,137 +0,0 @@
-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/AlfarLevitation.cs b/JotunnModStub/Alfar/AlfarLevitation.cs
index 206c8c7..77f6b9d 100644
--- a/JotunnModStub/Alfar/AlfarLevitation.cs
+++ b/JotunnModStub/Alfar/AlfarLevitation.cs
@@ -48,7 +48,7 @@ namespace RacesOfValheim
float target = 0f;
if (Time.time - AlfarArchon.StartedAt < 0.6f) target = 4f; // lift off
else if (RaceInput.Allowed && JumpHeld()) target = speed;
- else if (RaceInput.Allowed && CrouchHeld()) target = -speed;
+ else if (RaceInput.Allowed && ZInput.GetButton("Crouch")) target = -speed;
Vector3 velocity = flyer.linearVelocity;
velocity.y = Mathf.Lerp(velocity.y, target, 0.25f);
@@ -97,15 +97,9 @@ namespace RacesOfValheim
private static bool JumpHeld()
{
- // "Jump" is the keyboard binding only; the pad's button is a separate "JoyJump", read
- // the way PlayerController reads it, kept off while a radial menu has the pad.
- return ZInput.GetButton("Jump") || (ZInput.GetButton("JoyJump") && !Hud.InRadial());
- }
-
- private static bool CrouchHeld()
- {
- // Same split as jump: PlayerController ORs "Crouch" with "JoyCrouch".
- return ZInput.GetButton("Crouch") || (ZInput.GetButton("JoyCrouch") && !Hud.InRadial());
+ // ZInput's "Jump" covers the space bar and the pad's jump button alike, and respects the
+ // controls the player picked in the settings.
+ return ZInput.GetButton("Jump");
}
private static void FlushSpend(Player player)
diff --git a/JotunnModStub/Alfar/AlfarMiners.cs b/JotunnModStub/Alfar/AlfarMiners.cs
index b2c5a95..59b3b22 100644
--- a/JotunnModStub/Alfar/AlfarMiners.cs
+++ b/JotunnModStub/Alfar/AlfarMiners.cs
@@ -22,11 +22,7 @@ namespace RacesOfValheim
public static void Throw(Player player)
{
- if (Time.time < readyAt)
- {
- player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_alfar_graf_cooldown", Mathf.CeilToInt(readyAt - Time.time)));
- return;
- }
+ if (Time.time < readyAt) return;
Transform aim = GameCamera.instance != null ? GameCamera.instance.transform : player.transform;
Vector3 origin = aim.position;
@@ -80,7 +76,12 @@ namespace RacesOfValheim
GameObject spawned = Object.Instantiate(prefab, where, Quaternion.identity);
AlfarMiner miner = spawned.GetComponent();
- if (miner != null) miner.Assign(point, AlfarPowerConfig.GrafRadius.Value, AlfarPowerConfig.GrafSeconds.Value);
+ if (miner != null)
+ {
+ miner.Centre = point;
+ miner.Radius = AlfarPowerConfig.GrafRadius.Value;
+ miner.LiveSeconds = AlfarPowerConfig.GrafSeconds.Value;
+ }
// Tame at once so nothing flees them and they flee nothing; no anchor, no leash.
MonsterAI ai = spawned.GetComponent();
diff --git a/JotunnModStub/Alfar/AlfarNexus.cs b/JotunnModStub/Alfar/AlfarNexus.cs
index 26024f5..8ba5ac9 100644
--- a/JotunnModStub/Alfar/AlfarNexus.cs
+++ b/JotunnModStub/Alfar/AlfarNexus.cs
@@ -46,9 +46,7 @@ namespace RacesOfValheim
Object.DestroyImmediate(behaviour);
}
- // The floating pyramid; the blue table stays as the fallback if it cannot be built.
- bool pyramid = AlfarNexusLook.Build(prefab);
- if (!pyramid) AlfarConstructs.Tint(prefab, new Color(0.62f, 0.8f, 1f, 1f));
+ AlfarConstructs.Tint(prefab, new Color(0.62f, 0.8f, 1f, 1f));
AlfarNexusBehaviour nexus = prefab.AddComponent();
nexus.m_switch = prefab.AddComponent();
@@ -73,7 +71,7 @@ namespace RacesOfValheim
trader.m_randomUseItemAlreadyRecieved = new List();
trader.m_randomTalkConditionals = new List();
- Sprite icon = (pyramid ? AlfarChests.IconFrom("AlfarNexus_icon.png") : null) ?? BorrowIcon("Eitr") ?? BorrowIcon("SurtlingCore");
+ Sprite icon = BorrowIcon("Eitr") ?? BorrowIcon("SurtlingCore");
Piece piece = prefab.GetComponent() ?? prefab.AddComponent();
piece.m_craftingStation = null;
diff --git a/JotunnModStub/Alfar/AlfarNexusConfig.cs b/JotunnModStub/Alfar/AlfarNexusConfig.cs
index 84ffd4c..59c4020 100644
--- a/JotunnModStub/Alfar/AlfarNexusConfig.cs
+++ b/JotunnModStub/Alfar/AlfarNexusConfig.cs
@@ -89,13 +89,8 @@ namespace RacesOfValheim
DroneZapDamage = config.Bind(drone, "Zap Damage", 1f, new ConfigDescription("Lightning damage of a drone's defensive zap.", new AcceptableValueRange(0f, 100f)));
DroneZapInterval = config.Bind(drone, "Zap Interval", 2f, new ConfigDescription("Seconds between a drone's zaps.", new AcceptableValueRange(0.2f, 30f)));
- // Copper deposits are rock4_copper (and rock4_copper_frac once hit), crypt scrap is mudpile;
- // the first default missed both, so a config still holding it is moved to the new one.
- const string oldTargets = "MineRock_Copper,MineRock_Tin,MineRock_Iron,silvervein,rock3_silver,giant_brain";
- const string targets = "rock4_copper,MineRock_Copper,MineRock_Tin,MineRock_Iron,mudpile,silvervein,rock3_silver,giant_brain";
- MinerDeposits = config.Bind(drone, "Mining Targets", targets,
+ MinerDeposits = config.Bind(drone, "Mining Targets", "MineRock_Copper,MineRock_Tin,MineRock_Iron,silvervein,rock3_silver,giant_brain",
new ConfigDescription("Comma separated parts of prefab names the mining drones dig (case does not matter). Soft tissue comes from giant_brain."));
- if (MinerDeposits.Value == oldTargets) MinerDeposits.Value = targets;
MinerDamage = config.Bind(drone, "Mining Damage", 40f, new ConfigDescription("Pickaxe damage each mining drone does per second to a deposit.", new AcceptableValueRange(1f, 1000f)));
WildPickables = config.Bind(drone, "Wild Plants Harvested", "Pickable_Mushroom,Pickable_Dandelion,Pickable_Thistle,RaspberryBush,BlueberryBush,CloudberryBush",
diff --git a/JotunnModStub/Alfar/AlfarNexusLook.cs b/JotunnModStub/Alfar/AlfarNexusLook.cs
deleted file mode 100644
index 34c1fe7..0000000
--- a/JotunnModStub/Alfar/AlfarNexusLook.cs
+++ /dev/null
@@ -1,217 +0,0 @@
-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 73864de..5d5e5ea 100644
--- a/JotunnModStub/Alfar/AlfarPatches.cs
+++ b/JotunnModStub/Alfar/AlfarPatches.cs
@@ -38,37 +38,6 @@ 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 8a02b61..dc7c52b 100644
--- a/JotunnModStub/Alfar/AlfarPowers.cs
+++ b/JotunnModStub/Alfar/AlfarPowers.cs
@@ -148,17 +148,12 @@ namespace RacesOfValheim
}
/// A pulse of lightning on every hostile creature within a radius of the Alfr.
- /// True if it struck at least one creature.
- public static bool Pulse(Player player, float radius, float damage)
+ public static void Pulse(Player player, float radius, float damage)
{
- bool struck = false;
foreach (Character character in CharactersIn(player.transform.position, radius))
{
- if (!IsHostile(player, character)) continue;
- Strike(player, character, damage, character.GetCenterPoint());
- struck = true;
+ if (IsHostile(player, character)) Strike(player, character, damage, character.GetCenterPoint());
}
- return struck;
}
private static IEnumerable CharactersIn(Vector3 center, float radius)
@@ -182,64 +177,35 @@ 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;
- if (NearestHit(player, origin, direction, distance, out RaycastHit wall))
+ RaycastHit[] hits = Physics.RaycastAll(origin, direction, distance, ~0, QueryTriggerInteraction.Ignore);
+ float nearest = float.MaxValue;
+ foreach (RaycastHit hit in hits)
{
- 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)
+ if (hit.collider.GetComponentInParent() == player) continue;
+ if (hit.distance < nearest)
{
- // 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;
+ nearest = hit.distance;
+ destination = hit.point - direction * 0.6f;
}
}
- if (!Pay(player, AlfarPowerConfig.SkridCost.Value)) return;
+ // 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;
+ }
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.
@@ -339,34 +305,6 @@ namespace RacesOfValheim
// ─── Geisli: the beam ────────────────────────────────────────────────
- ///
- /// The pad's way to hold the beam. Every pad button is taken in vanilla's Classic layout, so,
- /// like Skadi's Cold Spell, the beam borrows the secondary attack: bare-handed, or in the
- /// archon form, which has no weapons anyway. The radial entry only gives a single press,
- /// which cannot hold a beam.
- ///
- private static bool PadBeamHeld(Player player) =>
- !RaceInput.RadialOpen && RaceInput.PadAttackHeld(2) &&
- (AlfarArchon.Active || RaceInput.EmptyHanded(player));
-
- ///
- /// Swallows the unarmed secondary (the kick) while the pad's secondary attack is the beam,
- /// the same way SkadiAttackPatch does for the Cold Spell.
- ///
- [HarmonyPatch(typeof(Humanoid), "StartAttack")]
- public static class Alfar_GeisliPadKick_Patch
- {
- public static bool Prefix(Humanoid __instance, bool secondaryAttack, ref bool __result)
- {
- if (!secondaryAttack || __instance != Player.m_localPlayer) return true;
- Player player = (Player)__instance;
- if (!AlfarVisuals.IsAlfarPlayer(player) || !Unlocked(AlfarPowerConfig.GeisliState)) return true;
- if (!PadBeamHeld(player)) return true;
- __result = false;
- return false;
- }
- }
-
private static LineRenderer beamLine;
private static readonly List beamArcs = new List();
private static GameObject beamFx;
@@ -386,7 +324,7 @@ namespace RacesOfValheim
private static void TickBeam(Player player)
{
bool wanted = RaceInput.Allowed && !player.IsDead() && Unlocked(AlfarPowerConfig.GeisliState) &&
- (AlfarPowerConfig.GeisliKey.Value.IsPressedIgnoringHeldKeys() || PadBeamHeld(player));
+ AlfarPowerConfig.GeisliKey.Value.IsPressedIgnoringHeldKeys();
if (!wanted)
{
@@ -430,11 +368,7 @@ namespace RacesOfValheim
AlfarEitr.Spend(player, cost);
}
- if (IsHostile(player, target))
- {
- Strike(player, target, AlfarPowerConfig.BeamDps.Value * tick, end);
- FormMelee.RaiseSkill(Skills.SkillType.ElementalMagic, tick); // a full hit per second on target
- }
+ if (IsHostile(player, target)) Strike(player, target, AlfarPowerConfig.BeamDps.Value * tick, end);
}
private static void RaiseHand(Player player)
@@ -586,19 +520,14 @@ 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/Alfar/AlfarVisuals.cs b/JotunnModStub/Alfar/AlfarVisuals.cs
index aa6df6e..51d4cd1 100644
--- a/JotunnModStub/Alfar/AlfarVisuals.cs
+++ b/JotunnModStub/Alfar/AlfarVisuals.cs
@@ -161,67 +161,35 @@ namespace RacesOfValheim
}
if (eyes == null) return;
- PlaceEyes(player, eyes);
+ PlaceEyes(headBone, eyes);
}
- ///
- /// A grey's eyes: wide black almonds, outer corners raised, wrapping round the sides of the
- /// face. Each is a sphere squashed to an ellipsoid and turned in the skull's own frame.
- ///
- /// FIXED HEAD-LOCAL UNITS, never headBone.lossyScale. The Alfar Visual is scaled
- /// non-uniformly, so the head's lossyScale is only an approximation that changes as the
- /// head turns; recomputed on the 0.5s cosmetic pass it made the eyes trail the face. The
- /// face is skinned to the same bone through the same matrices, so a constant local offset
- /// stays glued to it at any body scale, and PlaceEyes only has to run when the eyes change.
- ///
- private static void PlaceEyes(Player player, Transform holder)
+ private static void PlaceEyes(Transform headBone, Transform holder)
{
+ Vector3 lossy = headBone.lossyScale;
+ if (Mathf.Abs(lossy.x) < 0.0001f || Mathf.Abs(lossy.y) < 0.0001f || Mathf.Abs(lossy.z) < 0.0001f) return;
+
EyeFrame frame = holder.GetComponent();
if (frame == null) return;
- const float toLocal = PlayerFace.MetresToHeadLocal;
+ // The Visual is scaled non-uniformly (thinner than tall), so lossyScale has three
+ // different components and a single divisor would squash the spheres. Each axis is
+ // divided by its own.
+ Vector3 toLocal = new Vector3(1f / lossy.x, 1f / lossy.y, 1f / lossy.z);
+ float eyeSize = AlfarConfig.EyeSize * AlfarConfig.EyeSizeMultiplier.Value;
- float height = AlfarConfig.EyeHeight;
- float separation = AlfarConfig.EyeSeparation;
- float size = AlfarConfig.EyeSizeMultiplier.Value;
- PlayerFace.AdjustEyes(player, ref height, ref separation, ref size);
-
- Quaternion facing = Quaternion.LookRotation(frame.LocalForward, frame.LocalUp);
+ Vector3 baseOffset = frame.LocalForward * AlfarConfig.EyeForward + frame.LocalUp * AlfarConfig.EyeHeight;
for (int i = 0; i < holder.childCount; i++)
{
Transform eye = holder.GetChild(i);
- // Index 0 is offset against the right axis, so it is the model's left eye. The
- // slant and the wrap are mirrored so both outer corners go up and back.
+ // Index 0 is offset against the right axis, so it is the model's left eye.
float side = i == 0 ? -1f : 1f;
+ Vector3 offset = baseOffset + frame.LocalRight * (side * AlfarConfig.EyeSeparation);
- // This eye's hand corrections (RaceEyeTuning).
- float forward = AlfarConfig.EyeForward;
- float eyeHeight = height;
- float eyeSeparation = separation;
- float eyeSize = size;
- float wrap = AlfarConfig.EyeWrap;
- float slant = AlfarConfig.EyeSlant;
- float tilt = 0f;
- RaceEyeTuning.Eye tuning = RaceEyeTuning.For(AlfarConfig.RaceId, player, side);
- if (tuning != null)
- {
- forward += tuning.Forward;
- eyeHeight += tuning.Height;
- eyeSeparation += tuning.Separation;
- eyeSize *= tuning.Size;
- tilt = tuning.RotX;
- wrap += tuning.RotY;
- slant += tuning.RotZ;
- }
-
- Vector3 offset = frame.LocalForward * forward + frame.LocalUp * eyeHeight
- + frame.LocalRight * (side * eyeSeparation);
-
- eye.localPosition = offset * toLocal;
- eye.localRotation = facing * Quaternion.Euler(tilt, wrap * side, slant * side);
- eye.localScale = AlfarConfig.EyeExtent * (eyeSize * toLocal);
+ eye.localPosition = Vector3.Scale(offset, toLocal);
+ eye.localScale = Vector3.Scale(Vector3.one * eyeSize, toLocal);
}
}
@@ -266,8 +234,9 @@ namespace RacesOfValheim
}
///
- /// Black with a wet sheen: no emission, but smooth enough to catch a highlight, which is
- /// what makes a grey's eyes read as eyes and not as two holes punched in the face.
+ /// Matte black, and nothing else: the colour is black, the emission is black, and the two
+ /// properties that make a lit shader shine are zeroed where the shader has them. The
+ /// Sverm's eyes burn; these must read as holes.
///
private static Material BlackMaterial(Shader shader)
{
@@ -275,9 +244,10 @@ namespace RacesOfValheim
material.color = Color.black;
if (material.HasProperty("_EmissionColor")) material.SetColor("_EmissionColor", Color.black);
- if (material.HasProperty("_Glossiness")) material.SetFloat("_Glossiness", 0.8f);
- if (material.HasProperty("_Smoothness")) material.SetFloat("_Smoothness", 0.8f);
+ if (material.HasProperty("_Glossiness")) material.SetFloat("_Glossiness", 0f);
+ if (material.HasProperty("_Smoothness")) material.SetFloat("_Smoothness", 0f);
if (material.HasProperty("_Metallic")) material.SetFloat("_Metallic", 0f);
+ if (material.HasProperty("_SpecColor")) material.SetColor("_SpecColor", Color.black);
return material;
}
diff --git a/JotunnModStub/Assets/AlfarFireChest/AlfarFireChest_d.png b/JotunnModStub/Assets/AlfarFireChest/AlfarFireChest_d.png
deleted file mode 100644
index 6f380b1..0000000
Binary files a/JotunnModStub/Assets/AlfarFireChest/AlfarFireChest_d.png and /dev/null differ
diff --git a/JotunnModStub/Assets/AlfarFireChest/AlfarFireChest_icon.png b/JotunnModStub/Assets/AlfarFireChest/AlfarFireChest_icon.png
deleted file mode 100644
index 8a4077f..0000000
Binary files a/JotunnModStub/Assets/AlfarFireChest/AlfarFireChest_icon.png and /dev/null differ
diff --git a/JotunnModStub/Assets/AlfarInputChest/AlfarInputChest_d.png b/JotunnModStub/Assets/AlfarInputChest/AlfarInputChest_d.png
deleted file mode 100644
index 6ede24f..0000000
Binary files a/JotunnModStub/Assets/AlfarInputChest/AlfarInputChest_d.png and /dev/null differ
diff --git a/JotunnModStub/Assets/AlfarInputChest/AlfarInputChest_icon.png b/JotunnModStub/Assets/AlfarInputChest/AlfarInputChest_icon.png
deleted file mode 100644
index 761ff83..0000000
Binary files a/JotunnModStub/Assets/AlfarInputChest/AlfarInputChest_icon.png and /dev/null differ
diff --git a/JotunnModStub/Assets/AlfarNexus/AlfarNexus_face.png b/JotunnModStub/Assets/AlfarNexus/AlfarNexus_face.png
deleted file mode 100644
index 2dff3cb..0000000
Binary files a/JotunnModStub/Assets/AlfarNexus/AlfarNexus_face.png and /dev/null differ
diff --git a/JotunnModStub/Assets/AlfarNexus/AlfarNexus_glow.png b/JotunnModStub/Assets/AlfarNexus/AlfarNexus_glow.png
deleted file mode 100644
index d88a980..0000000
Binary files a/JotunnModStub/Assets/AlfarNexus/AlfarNexus_glow.png and /dev/null differ
diff --git a/JotunnModStub/Assets/AlfarNexus/AlfarNexus_icon.png b/JotunnModStub/Assets/AlfarNexus/AlfarNexus_icon.png
deleted file mode 100644
index a85c891..0000000
Binary files a/JotunnModStub/Assets/AlfarNexus/AlfarNexus_icon.png and /dev/null differ
diff --git a/JotunnModStub/Assets/AlfarNexus/AlfarNexus_n.png b/JotunnModStub/Assets/AlfarNexus/AlfarNexus_n.png
deleted file mode 100644
index 1940c2a..0000000
Binary files a/JotunnModStub/Assets/AlfarNexus/AlfarNexus_n.png and /dev/null differ
diff --git a/JotunnModStub/Assets/CookCloth/CookCloth_d.png b/JotunnModStub/Assets/CookCloth/CookCloth_d.png
deleted file mode 100644
index 905ec99..0000000
Binary files a/JotunnModStub/Assets/CookCloth/CookCloth_d.png and /dev/null differ
diff --git a/JotunnModStub/Assets/CookCloth/CookCloth_n.png b/JotunnModStub/Assets/CookCloth/CookCloth_n.png
deleted file mode 100644
index 7603df9..0000000
Binary files a/JotunnModStub/Assets/CookCloth/CookCloth_n.png and /dev/null differ
diff --git a/JotunnModStub/Assets/CookCloth/CookCloth_worn_d.png b/JotunnModStub/Assets/CookCloth/CookCloth_worn_d.png
deleted file mode 100644
index d36ee7c..0000000
Binary files a/JotunnModStub/Assets/CookCloth/CookCloth_worn_d.png and /dev/null differ
diff --git a/JotunnModStub/Assets/Hammers/ShrinkHammer_icon.png b/JotunnModStub/Assets/Hammers/ShrinkHammer_icon.png
deleted file mode 100644
index a7328f5..0000000
Binary files a/JotunnModStub/Assets/Hammers/ShrinkHammer_icon.png and /dev/null differ
diff --git a/JotunnModStub/Assets/Hammers/TrolsHammer_icon.png b/JotunnModStub/Assets/Hammers/TrolsHammer_icon.png
deleted file mode 100644
index 99e1761..0000000
Binary files a/JotunnModStub/Assets/Hammers/TrolsHammer_icon.png and /dev/null differ
diff --git a/JotunnModStub/Assets/SmithMail/SmithMail_d.png b/JotunnModStub/Assets/SmithMail/SmithMail_d.png
deleted file mode 100644
index 5ecb47d..0000000
Binary files a/JotunnModStub/Assets/SmithMail/SmithMail_d.png and /dev/null differ
diff --git a/JotunnModStub/Assets/SmithMail/SmithMail_m.png b/JotunnModStub/Assets/SmithMail/SmithMail_m.png
deleted file mode 100644
index 0227d0f..0000000
Binary files a/JotunnModStub/Assets/SmithMail/SmithMail_m.png and /dev/null differ
diff --git a/JotunnModStub/Assets/SmithMail/SmithMail_n.png b/JotunnModStub/Assets/SmithMail/SmithMail_n.png
deleted file mode 100644
index 9198ee1..0000000
Binary files a/JotunnModStub/Assets/SmithMail/SmithMail_n.png and /dev/null differ
diff --git a/JotunnModStub/Assets/SmithMail/SmithMail_worn_d.png b/JotunnModStub/Assets/SmithMail/SmithMail_worn_d.png
deleted file mode 100644
index a90bd1c..0000000
Binary files a/JotunnModStub/Assets/SmithMail/SmithMail_worn_d.png and /dev/null differ
diff --git a/JotunnModStub/Aswid/AswidBatAggro.cs b/JotunnModStub/Aswid/AswidBatAggro.cs
new file mode 100644
index 0000000..3bb4e6f
--- /dev/null
+++ b/JotunnModStub/Aswid/AswidBatAggro.cs
@@ -0,0 +1,182 @@
+using HarmonyLib;
+using UnityEngine;
+
+namespace RacesOfValheim
+{
+ ///
+ /// Why nothing in Valheim ever attacked the bat, and the smallest honest fix for it.
+ ///
+ /// The bat flies on Player.m_debugFly - the developer no-clip flag - because that is the only
+ /// flight vanilla actually has, and it is what BatFormBehavior sets and WarVultureMount reuses.
+ /// What nobody noticed is that vanilla reads that same flag as "this player is not really
+ /// here". Six places, all read out of assembly_valheim with Cecil rather than guessed:
+ ///
+ /// BaseAI.CanHearTarget - first line: the target is a Player in debug fly -> return false.
+ /// BaseAI.CanSeeTarget - the same first line, the same false.
+ /// BaseAI.FindEnemy - its HuntPlayer fallback throws the player away for the same reason.
+ /// MonsterAI.UpdateSleep - a sleeping monster refuses to wake for one, twice over.
+ /// Character.ApplyDamage - first line: IsDebugFlying -> return, the hit does nothing.
+ /// Character.RPC_Damage - the same.
+ ///
+ /// So the bat was never merely ignored: it was invulnerable as well, and both facts came out of
+ /// the one flag. There was nothing wrong with the Aswid's own code, which is why nothing in it
+ /// looked wrong.
+ ///
+ /// The fix keeps the flag - it IS the flight - and lies about it in exactly the places that
+ /// decide aggro and damage, and nowhere else:
+ ///
+ /// Player.InDebugFlyMode() is forced false for a bat unconditionally. That is safe, and it is
+ /// the reason this file is short: a scan of the whole assembly says that method has
+ /// exactly three callers, and all three are the sensing paths listed above. No part of
+ /// flight, camera, stamina or motion goes through it.
+ /// Player.IsDebugFlying() is NOT forced false, because Character.UpdateMotion reads it and
+ /// that read is what holds the bat in the air. It is only forced false while the call
+ /// stack is inside one of the three vanilla methods that must not honour it, which is
+ /// what the depth counter below is for.
+ ///
+ /// Both halves sit behind their own config toggle, so a bat can be made visible-but-immortal,
+ /// or put back the way it was, without touching code.
+ ///
+ public static class AswidBatForm
+ {
+ ///
+ /// The ZDO flag AswidRace writes when the form goes up. Replicated, so it answers for
+ /// remote players too - which matters here, because the machine asking "is this player a
+ /// bat" is whichever one owns the monster, not the bat's own.
+ ///
+ public const string BatZdoKey = "Aswid_IsBatForm";
+
+ private static readonly int BatFormHash = "SE_BatForm".GetStableHashCode();
+
+ // How deep we currently are inside vanilla calls that must not see the debug-fly flag. A
+ // counter and not a bool: ApplyDamage runs inside RPC_Damage, so the frames nest.
+ private static int unmaskDepth;
+
+ public static bool Unmasked => unmaskDepth > 0;
+ public static void PushUnmask() { unmaskDepth++; }
+ public static void PopUnmask() { if (unmaskDepth > 0) unmaskDepth--; }
+
+ ///
+ /// The ZDO first and the status effect only as a fallback: the ZDO is the one that is true
+ /// on every client, and the status effect covers the local player during the frames of the
+ /// transform where the ZDO write has not landed yet.
+ ///
+ public static bool IsBat(Player player)
+ {
+ if (player == null) return false;
+
+ ZNetView nview = player.GetComponent();
+ if (nview != null && nview.IsValid() && nview.GetZDO().GetBool(BatZdoKey, false)) return true;
+
+ return player == Player.m_localPlayer &&
+ player.GetSEMan() != null &&
+ player.GetSEMan().HaveStatusEffect(BatFormHash);
+ }
+ }
+
+ ///
+ /// The whole of the aggro fix. See AswidBatForm for why patching this one method flat is safe,
+ /// and why patching IsDebugFlying flat would drop the bat out of the sky instead.
+ ///
+ [HarmonyPatch(typeof(Player), "InDebugFlyMode")]
+ public static class Aswid_BatIsVisibleToAI_Patch
+ {
+ public static void Postfix(Player __instance, ref bool __result)
+ {
+ if (!__result) return;
+ if (AswidConfig.BatFormAggro != null && !AswidConfig.BatFormAggro.Value) return;
+ if (AswidBatForm.IsBat(__instance)) __result = false;
+ }
+ }
+
+ ///
+ /// The scoped half. Only ever fires inside the three vanilla methods that push the counter, and
+ /// only for a player who is a bat - so the flag still reads true everywhere flight, motion, the
+ /// camera and Player.UpdateStats look at it.
+ ///
+ [HarmonyPatch(typeof(Player), "IsDebugFlying")]
+ public static class Aswid_BatIsDebugFlying_Patch
+ {
+ public static void Postfix(Player __instance, ref bool __result)
+ {
+ if (!__result || !AswidBatForm.Unmasked) return;
+ if (AswidBatForm.IsBat(__instance)) __result = false;
+ }
+ }
+
+ ///
+ /// A hit landing on a bat. Finalizer rather than Postfix throughout this file: the counter has
+ /// to come back down even when the patched method throws, and a Postfix does not run then. A
+ /// void Finalizer leaves the original exception alone, so nothing is swallowed either.
+ ///
+ [HarmonyPatch(typeof(Character), "ApplyDamage")]
+ public static class Aswid_BatTakesDamage_Patch
+ {
+ public static void Prefix(Character __instance, ref bool __state)
+ {
+ __state = (AswidConfig.BatFormVulnerable == null || AswidConfig.BatFormVulnerable.Value)
+ && __instance is Player player && AswidBatForm.IsBat(player);
+ if (__state) AswidBatForm.PushUnmask();
+ }
+
+ public static void Finalizer(bool __state)
+ {
+ if (__state) AswidBatForm.PopUnmask();
+ }
+ }
+
+ /// The networked half of the same thing: a hit sent by another machine.
+ [HarmonyPatch(typeof(Character), "RPC_Damage")]
+ public static class Aswid_BatTakesRemoteDamage_Patch
+ {
+ public static void Prefix(Character __instance, ref bool __state)
+ {
+ __state = (AswidConfig.BatFormVulnerable == null || AswidConfig.BatFormVulnerable.Value)
+ && __instance is Player player && AswidBatForm.IsBat(player);
+ if (__state) AswidBatForm.PushUnmask();
+ }
+
+ public static void Finalizer(bool __state)
+ {
+ if (__state) AswidBatForm.PopUnmask();
+ }
+ }
+
+ ///
+ /// Sleepers. Unlike the two above this cannot pre-check who the player is - UpdateSleep picks
+ /// the closest one itself, and that may be a remote bat - so the counter goes up for the whole
+ /// call and the per-player test happens in the IsDebugFlying postfix, where it costs nothing:
+ /// that postfix only runs at all for a character who is already flying.
+ ///
+ [HarmonyPatch(typeof(MonsterAI), "UpdateSleep")]
+ public static class Aswid_BatWakesSleepers_Patch
+ {
+ public static void Prefix(ref bool __state)
+ {
+ __state = AswidConfig.BatFormAggro == null || AswidConfig.BatFormAggro.Value;
+ if (__state) AswidBatForm.PushUnmask();
+ }
+
+ public static void Finalizer(bool __state)
+ {
+ if (__state) AswidBatForm.PopUnmask();
+ }
+ }
+
+ ///
+ /// Dying as a bat only became possible with the patches above, and the revert path could not
+ /// handle it: AswidRace.Update() returns early on IsDead(), so the coroutine that takes the
+ /// form down never starts. The debug-fly flag would stay on and the ZDO would stay true, which
+ /// is a respawned player floating over the ground with a bat drawn on them.
+ ///
+ [HarmonyPatch(typeof(Player), "OnDeath")]
+ public static class Aswid_BatDiesAsBat_Patch
+ {
+ public static void Prefix(Player __instance)
+ {
+ if (__instance != Player.m_localPlayer) return;
+ if (AswidRace.Instance == null) return;
+ AswidRace.Instance.HardResetBatForm();
+ }
+ }
+}
diff --git a/JotunnModStub/Aswid/AswidBatFlight.cs b/JotunnModStub/Aswid/AswidBatFlight.cs
new file mode 100644
index 0000000..e101fb7
--- /dev/null
+++ b/JotunnModStub/Aswid/AswidBatFlight.cs
@@ -0,0 +1,57 @@
+using HarmonyLib;
+using UnityEngine;
+
+namespace RacesOfValheim
+{
+ ///
+ /// How fast the bat flies, as a factor on vanilla's own debug-fly speed.
+ ///
+ /// The form flies on Player.m_debugFly (see AswidBatForm for why), so its speed is whatever
+ /// Character.UpdateDebugFly decides. Read out of assembly_valheim rather than assumed, that
+ /// method ends with:
+ ///
+ /// m_currentVel = Vector3.Lerp(m_currentVel, b, 0.5f);
+ /// m_body.linearVelocity = m_currentVel;
+ ///
+ /// where b is m_moveDir times m_debugFlySpeed - a public STATIC INT, 20 by default, times 2.5
+ /// while the run key is held.
+ ///
+ /// Two ways to make that faster were rejected before this one:
+ ///
+ /// Retuning m_debugFlySpeed around the call. It is shared by every character in the game and
+ /// it is an int, so a 1.35x multiplier would land on 27 and a 1.37x on the same 27 - the
+ /// slider would move in 5% steps and would be writing a global while it did it.
+ ///
+ /// Scaling m_currentVel itself, which is what WarVultureMount does for the bird. That field
+ /// is the input to the NEXT frame's lerp, so scaling it feeds back: with a factor s the
+ /// velocity settles at 0.5s/(1-0.5s) times vanilla, not s times it, and at s >= 2 it does
+ /// not settle at all.
+ ///
+ /// So only the rigidbody is scaled, and m_currentVel is left exactly as vanilla wrote it. The
+ /// lerp keeps smoothing the same trajectory it always did - the ramp up, the ease off, the
+ /// standstill at zero input - and the bat simply covers it faster. Linear in the slider, with
+ /// nothing to accumulate.
+ ///
+ [HarmonyPatch(typeof(Character), "UpdateDebugFly")]
+ public static class Aswid_BatFlightSpeed_Patch
+ {
+ public static void Postfix(Character __instance, Vector3 ___m_currentVel, Rigidbody ___m_body)
+ {
+ // Bound from RacesOfValheim.Awake(), before harmony.PatchAll() - the null check is for
+ // the config that failed to bind at all, not for a race between the two.
+ if (AswidConfig.BatFormFlightSpeed == null) return;
+
+ float multiplier = AswidConfig.BatFormFlightSpeed.Value;
+ if (Mathf.Approximately(multiplier, 1f)) return;
+
+ // Local player only. Every other machine's bat moves on its replicated position, and
+ // scaling velocity here would fight that sync rather than help it.
+ Player player = __instance as Player;
+ if (player == null || player != Player.m_localPlayer) return;
+ if (___m_body == null) return;
+ if (!AswidBatForm.IsBat(player)) return;
+
+ ___m_body.linearVelocity = ___m_currentVel * multiplier;
+ }
+ }
+}
diff --git a/JotunnModStub/Aswid/AswidBatForm.cs b/JotunnModStub/Aswid/AswidBatForm.cs
deleted file mode 100644
index 2ac80c7..0000000
--- a/JotunnModStub/Aswid/AswidBatForm.cs
+++ /dev/null
@@ -1,170 +0,0 @@
-using HarmonyLib;
-using UnityEngine;
-
-namespace RacesOfValheim
-{
- ///
- /// Whether a player is a bat, on any client.
- ///
- /// Stamina Flight flies on m_flying (DirectedFlight.cs), which vanilla's AI and damage never
- /// look at, so monsters notice and hurt that bat with no help.
- ///
- /// Free Flight flies on vanilla's debug-fly flag, and vanilla reads that flag as "this player
- /// is not really here". Six places, read out of assembly_valheim:
- ///
- /// BaseAI.CanHearTarget, BaseAI.CanSeeTarget and BaseAI's HuntPlayer fallback ask
- /// Player.InDebugFlyMode() and drop the player.
- /// MonsterAI.UpdateSleep asks IsDebugFlying() and will not wake, twice over.
- /// Character.ApplyDamage and Character.RPC_Damage ask IsDebugFlying() and drop the hit.
- ///
- /// The patches below keep the flag (it IS the flight) and lie about it in exactly those
- /// places, for bats only. InDebugFlyMode() is forced false flat: those three AI paths are its
- /// only callers. IsDebugFlying() cannot be: Character.UpdateMotion reads it to hold the bat in
- /// the air, so it reads false only while the call stack is inside one of the methods that push
- /// the counter. The patches were removed with the old flight in v1.6.1 and came back with it.
- ///
- public static class AswidBatForm
- {
- ///
- /// The ZDO flag AswidRace writes when the form goes up. Replicated, so it answers for
- /// remote players too.
- ///
- public const string BatZdoKey = "Aswid_IsBatForm";
-
- private static readonly int BatFormHash = "SE_BatForm".GetStableHashCode();
-
- // How deep we are inside vanilla calls that must not see the debug-fly flag. A counter,
- // not a bool: ApplyDamage runs inside RPC_Damage, so the frames nest.
- private static int unmaskDepth;
-
- public static bool Unmasked => unmaskDepth > 0;
- public static void PushUnmask() { unmaskDepth++; }
- public static void PopUnmask() { if (unmaskDepth > 0) unmaskDepth--; }
-
- ///
- /// The ZDO first and the status effect only as a fallback: the ZDO is the one that is true
- /// on every client, and the status effect covers the local player during the frames of the
- /// transform where the ZDO write has not landed yet.
- ///
- public static bool IsBat(Player player)
- {
- if (player == null) return false;
-
- ZNetView nview = player.GetComponent();
- if (nview != null && nview.IsValid() && nview.GetZDO().GetBool(BatZdoKey, false)) return true;
-
- return player == Player.m_localPlayer &&
- player.GetSEMan() != null &&
- player.GetSEMan().HaveStatusEffect(BatFormHash);
- }
- }
-
- /// Free Flight: monsters see and hear a bat. See AswidBatForm for why this one is safe flat.
- [HarmonyPatch(typeof(Player), "InDebugFlyMode")]
- public static class Aswid_BatIsVisibleToAI_Patch
- {
- public static void Postfix(Player __instance, ref bool __result)
- {
- if (__result && AswidBatForm.IsBat(__instance)) __result = false;
- }
- }
-
- ///
- /// The scoped half: false only inside the methods that push the counter, so flight, motion,
- /// the camera and UpdateStats still read the flag as true.
- ///
- [HarmonyPatch(typeof(Player), "IsDebugFlying")]
- public static class Aswid_BatIsDebugFlying_Patch
- {
- public static void Postfix(Player __instance, ref bool __result)
- {
- if (!__result || !AswidBatForm.Unmasked) return;
- if (AswidBatForm.IsBat(__instance)) __result = false;
- }
- }
-
- ///
- /// A hit landing on a free-flying bat. Finalizer rather than Postfix: the counter has to come
- /// down even when the method throws, and a void Finalizer leaves the exception alone.
- ///
- [HarmonyPatch(typeof(Character), "ApplyDamage")]
- public static class Aswid_BatTakesDamage_Patch
- {
- public static void Prefix(Character __instance, ref bool __state)
- {
- __state = __instance is Player player && AswidBatForm.IsBat(player);
- if (__state) AswidBatForm.PushUnmask();
- }
-
- public static void Finalizer(bool __state)
- {
- if (__state) AswidBatForm.PopUnmask();
- }
- }
-
- /// The networked half of the same thing: a hit sent by another machine.
- [HarmonyPatch(typeof(Character), "RPC_Damage")]
- public static class Aswid_BatTakesRemoteDamage_Patch
- {
- public static void Prefix(Character __instance, ref bool __state)
- {
- __state = __instance is Player player && AswidBatForm.IsBat(player);
- if (__state) AswidBatForm.PushUnmask();
- }
-
- public static void Finalizer(bool __state)
- {
- if (__state) AswidBatForm.PopUnmask();
- }
- }
-
- ///
- /// 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
- /// runs its test for a player already debug flying.
- ///
- [HarmonyPatch(typeof(MonsterAI), "UpdateSleep")]
- public static class Aswid_BatWakesSleepers_Patch
- {
- public static void Prefix() { AswidBatForm.PushUnmask(); }
- public static void Finalizer() { AswidBatForm.PopUnmask(); }
- }
-
- ///
- /// The revert path cannot handle a bat that dies: AswidRace.Update() returns early on IsDead(),
- /// so the coroutine that takes the form down never starts. The flight flag would stay on and
- /// the ZDO would stay true, which is a respawned player floating over the ground with a bat
- /// drawn on them.
- ///
- [HarmonyPatch(typeof(Player), "OnDeath")]
- public static class Aswid_BatDiesAsBat_Patch
- {
- public static void Prefix(Player __instance)
- {
- if (__instance != Player.m_localPlayer) return;
- if (AswidRace.Instance == null) return;
- AswidRace.Instance.HardResetBatForm();
- }
- }
-}
diff --git a/JotunnModStub/Aswid/AswidBloodRefinery.cs b/JotunnModStub/Aswid/AswidBloodRefinery.cs
index a127b5a..c119d53 100644
--- a/JotunnModStub/Aswid/AswidBloodRefinery.cs
+++ b/JotunnModStub/Aswid/AswidBloodRefinery.cs
@@ -338,6 +338,8 @@ namespace RacesOfValheim
// The raw -> cooked table the Draugh already maintains is the source of truth.
meatToCooked = new Dictionary(DraughFoodPatches.rawToCookedMapping);
meatToCooked.Remove("GreydwarfEye"); // stew ingredient, not flesh
+ meatToCooked["AsksvinMeat"] = "CookedAsksvinMeat";
+ meatToCooked["BoneMawSerpentMeat"] = "CookedBoneMawSerpentMeat";
foreach (string stationName in CookingStationPrefabs)
{
diff --git a/JotunnModStub/Aswid/AswidConfig.cs b/JotunnModStub/Aswid/AswidConfig.cs
index 57bc11a..da24f9d 100644
--- a/JotunnModStub/Aswid/AswidConfig.cs
+++ b/JotunnModStub/Aswid/AswidConfig.cs
@@ -33,81 +33,13 @@ namespace RacesOfValheim
public static ConfigEntry BloodMagicSkillGainMultiplier;
public static ConfigEntry SurtlingFormDamageBonus;
- // ─── Stamina ─────────────────────────────────────────────────────────────
- // The race used to have infinite stamina. Now it has a large pool that grows with each
- // boss, on top of what its devoured food gives - added, never assigned, so stamina mods
- // still stack.
- public static ConfigEntry BaseStaminaBonus;
- public static ConfigEntry StaminaBonusPerState;
- public static ConfigEntry StaminaCostMultiplier;
-
- // ─── Weaknesses ──────────────────────────────────────────────────────────
- // The Discord reports said the race had no real downsides. Each weakness has its own
- // switch, so a single player can drop one; on a server the host's values win.
- public static ConfigEntry SunlightEnabled;
- public static ConfigEntry SunHealthRegenPenalty;
- public static ConfigEntry SunStaminaRegenPenalty;
- public static ConfigEntry SunSpeedPenalty;
- public static ConfigEntry SunHealthLossPerSecond;
- public static ConfigEntry SunHealthFloor;
- public static ConfigEntry FireWeaknessEnabled;
- public static ConfigEntry FireWeakness;
- public static ConfigEntry FaderRemovesFireWeakness;
- public static ConfigEntry PierceWeaknessEnabled;
- public static ConfigEntry PierceWeakness;
-
- // ─── Running Water ─────────────────────────────────────────────────────
- // Lore says a vampire cannot cross running water unaided (Dagaz's report). Swimming costs
- // more, and open water - sea, river or lake - burns, swimming or flying over it; a boat
- // carries you, which the lore allows, though the camera still sways on board. The camera sway is a per-player comfort choice and stays local
- // (ConfigSync's "camera sway" key part).
- public static ConfigEntry RunningWaterEnabled;
- public static ConfigEntry WaterOceanOnly;
- public static ConfigEntry SwimStaminaMultiplier;
- public static ConfigEntry SeaHealthLossPerSecond;
- public static ConfigEntry SeaStaminaDrainPerSecond;
- public static ConfigEntry SeaHealthFloor;
- public static ConfigEntry SeaCameraSway;
- public static ConfigEntry SeaCameraSwayStrength;
-
// ─── Bat Form ────────────────────────────────────────────────────────────
- // The bat flies on the same directed flight as the Skadi's drakes (DirectedFlight.cs),
- // with its own numbers. It used to fly on vanilla's debug-fly flag: 50 m/s, free, blind
- // to carry weight, and ignored by every monster until AswidBatAggro lied to six vanilla
- // methods about it. The old flight came back as Free Flight, for players who want it
- // (building tall); AswidBatForm holds the aggro patches it needs.
- public enum EncumberedMode { Allowed, Blocked }
- public enum BatFlightRuleMode { PlayerChoice, AlwaysStaminaFlight, AlwaysFreeFlight }
-
- public static ConfigEntry FreeBatFlight;
- public static ConfigEntry BatFlightRule;
-
- /// Which flight a bat taken now gets: the server's rule first, then the player's own pick.
- public static bool UsesFreeBatFlight()
- {
- switch (BatFlightRule.Value)
- {
- case BatFlightRuleMode.AlwaysStaminaFlight: return false;
- case BatFlightRuleMode.AlwaysFreeFlight: return true;
- default: return FreeBatFlight.Value;
- }
- }
-
- public static ConfigEntry BatTurnSpeed;
- public static ConfigEntry BatGlideSpeed;
- public static ConfigEntry BatBoostSpeed;
- public static ConfigEntry BatSprintSpeed;
- public static ConfigEntry BatReverseSpeed;
- public static ConfigEntry BatLiftoffSpeed;
- public static ConfigEntry BatHoverSeconds;
- public static ConfigEntry BatPoweredStaminaPerSecond;
- public static ConfigEntry BatSprintStaminaPerSecond;
- public static ConfigEntry BatEncumbered;
- public static ConfigEntry BatEncumberedExtraCost;
- public static ConfigEntry BatMaxDuration;
- public static ConfigEntry BatDurationPerState;
- public static ConfigEntry BatCooldown;
- public static ConfigEntry BatCombatLock;
+ // Both of these undo something vanilla does to any player on the debug-fly flag, which is
+ // what the bat flies on. See AswidBatAggro for the six vanilla methods involved.
+ public static ConfigEntry BatFormAggro;
+ public static ConfigEntry BatFormVulnerable;
+ // A factor on vanilla's debug-fly speed, not a speed in metres - see AswidBatFlight.
+ public static ConfigEntry BatFormFlightSpeed;
// ─── Vampiric Aura (passive, always active) ──────────────────────────────
public static ConfigEntry AuraTickInterval;
@@ -116,8 +48,6 @@ namespace RacesOfValheim
public static ConfigEntry AuraBaseDamage;
public static ConfigEntry AuraBloodMagicScaling;
public static ConfigEntry AuraExecuteThreshold;
- public static ConfigEntry AuraInBatForm;
- public static ConfigEntry BatAuraUnlockState;
// ─── Superhuman Senses (tier 5+ passive) ─────────────────────────────────
public static ConfigEntry SensesRadius;
@@ -132,12 +62,6 @@ namespace RacesOfValheim
// ─── Devour ────────────────────────────────────────────────────────────
public static ConfigEntry DevourCooldown;
- // What a devoured creature feeds - see AswidRace.ApplyFoodBalance.
- public static ConfigEntry DevourHealthMultiplier;
- public static ConfigEntry DevourStaminaShare;
- public static ConfigEntry EarlyStaminaShare;
- public static ConfigEntry FoodCapBase;
- public static ConfigEntry FoodCapPerBiome;
// ─── Domination (tier 6+ ability, native Interact key) ───────────────────
public static ConfigEntry EnslaveCooldown;
@@ -206,95 +130,13 @@ namespace RacesOfValheim
SurtlingFormDamageBonus = config.Bind(combat, "Surtling Form Damage Bonus", 30f,
new ConfigDescription("Flat damage added to every attack once the tier 8 Surtling form is unlocked.", new AcceptableValueRange(0f, 100f)));
- const string stamina = "Aswid - Stamina";
- BaseStaminaBonus = config.Bind(stamina, "Base Stamina Bonus", 25f,
- new ConfigDescription("Max stamina added on top of the game's base 75 and your food, before any boss.", new AcceptableValueRange(0f, 300f)));
- StaminaBonusPerState = config.Bind(stamina, "Stamina Bonus Per State", 10f,
- new ConfigDescription("Max stamina added per progression state (8 at Fader).", new AcceptableValueRange(0f, 50f)));
- StaminaCostMultiplier = config.Bind(stamina, "Stamina Cost Multiplier", 1f,
- new ConfigDescription("Multiplies every stamina cost: sprinting, swimming, attacks, blocking. 1 is the normal cost, 0.5 half. There is no infinite setting on purpose; set the bonuses above high instead.", new AcceptableValueRange(0.1f, 2f)));
-
- const string weak = "Aswid - Weaknesses";
- SunlightEnabled = config.Bind(weak, "Sunlight", true,
- new ConfigDescription("Weakens you by day while you stand under open sky. A roof (the same test as the game's Sheltered status), a dungeon, the Swamp, the Mistlands, the night and your own Eclipse all shield you.", null));
- SunHealthRegenPenalty = config.Bind(weak, "Sunlight Health Regen Penalty", 0.5f,
- new ConfigDescription("Health regeneration lost in sunlight. 0.5 = half.", new AcceptableValueRange(0f, 1f)));
- SunStaminaRegenPenalty = config.Bind(weak, "Sunlight Stamina Regen Penalty", 0.25f,
- new ConfigDescription("Stamina regeneration lost in sunlight. 0.25 = a quarter.", new AcceptableValueRange(0f, 1f)));
- SunSpeedPenalty = config.Bind(weak, "Sunlight Speed Penalty", 0.1f,
- new ConfigDescription("Movement speed lost in sunlight. 0.1 = 10% slower.", new AcceptableValueRange(0f, 0.9f)));
- SunHealthLossPerSecond = config.Bind(weak, "Sunlight Health Loss Per Second", 0.5f,
- new ConfigDescription("Health the sun burns away each second. 0 turns it off.", new AcceptableValueRange(0f, 10f)));
- SunHealthFloor = config.Bind(weak, "Sunlight Health Floor", 0.3f,
- new ConfigDescription("The sun stops burning at this fraction of your max health, so it weakens you but never kills you. 0.3 = 30%.", new AcceptableValueRange(0f, 1f)));
- FireWeaknessEnabled = config.Bind(weak, "Fire Weakness", true,
- new ConfigDescription("Fire, burning included, hurts more.", null));
- FireWeakness = config.Bind(weak, "Fire Weakness Amount", 0.25f,
- new ConfigDescription("Extra fire damage taken. 0.25 = 25% more. Resistance meads and armour still reduce it.", new AcceptableValueRange(0f, 2f)));
- FaderRemovesFireWeakness = config.Bind(weak, "Fader Removes Fire Weakness", true,
- new ConfigDescription("Defeating Fader, the boss that grants the Surtling form, ends the fire weakness.", null));
- PierceWeaknessEnabled = config.Bind(weak, "Pierce Weakness", true,
- new ConfigDescription("Pierce damage (arrows, spears, stakes) hurts more. Mist Form's immunity still wins.", null));
- PierceWeakness = config.Bind(weak, "Pierce Weakness Amount", 0.2f,
- new ConfigDescription("Extra pierce damage taken. 0.2 = 20% more.", new AcceptableValueRange(0f, 2f)));
-
- const string water = "Aswid - Running Water";
- RunningWaterEnabled = config.Bind(water, "Running Water", true,
- new ConfigDescription("Swimming costs more stamina, and open water - the sea, rivers, lakes - hurts you while you swim in it or fly over it. Standing on, steering or sitting in a boat protects you. Wading, docks and bridges are safe.", null));
- WaterOceanOnly = config.Bind(water, "Ocean Only", false,
- new ConfigDescription("Limits the burn, the drain and the camera sway to the Ocean biome, leaving rivers and lakes alone. The swim stamina cost applies everywhere either way.", null));
- SwimStaminaMultiplier = config.Bind(water, "Swim Stamina Multiplier", 2f,
- new ConfigDescription("Multiplies the stamina swimming costs, anywhere. At 0 stamina the game's own drowning starts. Around 5 and up, swimming any distance is no longer possible.", new AcceptableValueRange(1f, 10f)));
- SeaHealthLossPerSecond = config.Bind(water, "Open Water Health Loss Per Second", 1f,
- new ConfigDescription("Health open water burns away each second.", new AcceptableValueRange(0f, 20f)));
- SeaStaminaDrainPerSecond = config.Bind(water, "Open Water Stamina Drain Per Second", 2f,
- new ConfigDescription("Stamina open water drains each second, on top of what swimming or flying costs.", new AcceptableValueRange(0f, 30f)));
- SeaHealthFloor = config.Bind(water, "Open Water Health Floor", 0.1f,
- new ConfigDescription("The water's burn stops at this fraction of your max health. Drowning, once your stamina runs out, has no floor.", new AcceptableValueRange(0f, 1f)));
- SeaCameraSway = config.Bind(water, "Camera Sway", true,
- new ConfigDescription("The camera rolls gently while you are out on the water, on a boat too, as if seasick. Local: each player chooses for themselves.", null));
- SeaCameraSwayStrength = config.Bind(water, "Camera Sway Strength", 1f,
- new ConfigDescription("How far the camera rolls. 1 is about 4 degrees. Local.", new AcceptableValueRange(0f, 3f)));
-
const string batform = "Aswid - Bat Form";
- FreeBatFlight = config.Bind(batform, "Free Bat Flight", false,
- new ConfigDescription("Off: Stamina Flight, the settings below. On: the old Free Flight, up to 50 m/s with no stamina cost and no weight limit; Jump rises, Left Ctrl sinks. Your own choice, unless the server's Bat Flight Rule forces one. Takes effect the next time you become a bat."));
- BatFlightRule = config.Bind(batform, "Bat Flight Rule", BatFlightRuleMode.PlayerChoice,
- new ConfigDescription("Server rule. PlayerChoice: each player's Free Bat Flight setting decides. AlwaysStaminaFlight / AlwaysFreeFlight: every bat flies that way. On a server only the host's or the server's value counts."));
- // Same controls as the Skadi's drake: aim with the camera, W beats forward, Shift
- // sprints, S beats backwards, and letting go hovers briefly before gliding down.
- BatTurnSpeed = config.Bind(batform, "Turn Speed", 180f,
- new ConfigDescription("Degrees per second the bat turns towards where you aim.", new AcceptableValueRange(30f, 720f)));
- BatGlideSpeed = config.Bind(batform, "Glide Speed", 6f,
- new ConfigDescription("Speed while gliding down with no key held, in m/s.", new AcceptableValueRange(0f, 30f)));
- // Not "Flight Speed": that key held the old debug-fly multiplier, and an existing .cfg
- // would load its 1 here as one metre per second.
- BatBoostSpeed = config.Bind(batform, "Boost Speed", 13f,
- new ConfigDescription("Speed while holding W, in m/s. Costs the powered stamina below.", new AcceptableValueRange(0f, 60f)));
- BatSprintSpeed = config.Bind(batform, "Sprint Speed", 24f,
- new ConfigDescription("Speed while holding W and Shift, in m/s. Costs the sprint stamina on top. The old bat flew at 50.", new AcceptableValueRange(0f, 80f)));
- BatReverseSpeed = config.Bind(batform, "Reverse Speed", 8f,
- new ConfigDescription("Speed while holding S, in m/s. Costs the powered stamina.", new AcceptableValueRange(0f, 40f)));
- BatLiftoffSpeed = config.Bind(batform, "Liftoff Speed", 9f,
- new ConfigDescription("Climb speed out of water, in m/s. Always free, so a bat that touches the sea can still leave it.", new AcceptableValueRange(0f, 30f)));
- BatHoverSeconds = config.Bind(batform, "Hover Seconds", 3f,
- new ConfigDescription("How long the bat holds its height after the last powered beat before it starts to glide down.", new AcceptableValueRange(0f, 30f)));
- BatPoweredStaminaPerSecond = config.Bind(batform, "Flight Stamina Per Second", 3f,
- new ConfigDescription("Stamina per second while holding W or S. Out of stamina, the bat can only glide. 0 makes flight free, like the drake's.", new AcceptableValueRange(0f, 60f)));
- BatSprintStaminaPerSecond = config.Bind(batform, "Sprint Stamina Per Second", 12f,
- new ConfigDescription("Extra stamina per second while sprinting, on top of the flight cost.", new AcceptableValueRange(0f, 60f)));
- BatEncumbered = config.Bind(batform, "While Encumbered", EncumberedMode.Allowed,
- new ConfigDescription("Allowed: the bat flies while you carry too much, at the extra stamina cost below. Blocked: you cannot take bat form while encumbered, and a bat that becomes encumbered in the air can only glide down.", null));
- BatEncumberedExtraCost = config.Bind(batform, "Encumbered Extra Stamina Cost", 0.15f,
- new ConfigDescription("With 'Allowed' above: how much more flight and sprint cost while encumbered. 0.15 = 15% more.", new AcceptableValueRange(0f, 1f)));
- BatMaxDuration = config.Bind(batform, "Max Duration", 0f,
- new ConfigDescription("Seconds the bat form lasts before you turn back on your own. 0 means no limit: stamina is the limit.", new AcceptableValueRange(0f, 3600f)));
- BatDurationPerState = config.Bind(batform, "Duration Per State", 0f,
- new ConfigDescription("Seconds added to the max duration per progression state. Does nothing while the max duration is 0.", new AcceptableValueRange(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)));
+ BatFormAggro = config.Bind(batform, "Monsters Notice The Bat", true,
+ new ConfigDescription("Lets monsters see, hear and wake up for a player in Bat Form. Vanilla refuses to notice anyone flying on the debug-fly flag, which is the flag the form uses - turn this off to go back to a bat nothing ever looks at."));
+ BatFormVulnerable = config.Bind(batform, "The Bat Can Be Hurt", true,
+ new ConfigDescription("Lets damage land on a player in Bat Form. Same cause as the setting above: vanilla drops every hit on a debug-flying character. Turn this off for a bat that is noticed and chased but cannot be killed."));
+ BatFormFlightSpeed = config.Bind(batform, "Flight Speed", 1f,
+ new ConfigDescription("How fast the bat flies, as a multiplier on the game's own flight speed (20 m/s, and 2.5x that while the run key is held). 1 is untouched, 2 is twice as fast, 0.5 is half. Local only - it changes how your own bat moves, not anyone else's.", new AcceptableValueRange(0.25f, 3f)));
const string aura = "Aswid - Vampiric Aura";
AuraTickInterval = config.Bind(aura, "Tick Interval", 0.25f,
@@ -309,10 +151,6 @@ namespace RacesOfValheim
new ConfigDescription("Extra damage per tick at 100 Blood Magic skill (scales linearly from 0).", new AcceptableValueRange(0f, 20f)));
AuraExecuteThreshold = config.Bind(aura, "Execute Threshold", 0.20f,
new ConfigDescription("Non-boss enemies at or below this fraction of max health are executed by the aura instead of merely damaged.", new AcceptableValueRange(0f, 1f)));
- AuraInBatForm = config.Bind(aura, "Active In Bat Form", false,
- new ConfigDescription("Lets the aura drain while you are a bat from the start, as it did before. Off: the bat has no aura until the unlock state below.", null));
- BatAuraUnlockState = config.Bind(aura, "Bat Form Unlock State", 7,
- new ConfigDescription("The progression state at which the bat gets its aura back (7 = The Queen). 0 means never, so only the setting above can turn it on.", new AcceptableValueRange(0, 8)));
const string senses = "Aswid - Superhuman Senses";
SensesRadius = config.Bind(senses, "Detection Radius", 100f,
@@ -335,23 +173,6 @@ namespace RacesOfValheim
const string devour = "Aswid - Devour";
DevourCooldown = config.Bind(devour, "Consume Cooldown", 5f,
new ConfigDescription("How long one body stays drunk-dry, in seconds. A single death is reported to the devour more than once - by two damage patches, by the aura's execute, by a thrall's kill - and this is the window that keeps those from feeding you twice off the same corpse. It is per body, not per player: killing a whole pack at once devours every one of them. One second is used as the floor, so no corpse feeds you twice even at 0.", new AcceptableValueRange(0f, 60f)));
- DevourHealthMultiplier = config.Bind(devour, "Health Multiplier", 0.9f,
- new ConfigDescription("Scales the health every devoured creature feeds you. 1 is the old amount.", new AcceptableValueRange(0f, 2f)));
- DevourStaminaShare = config.Bind(devour, "Stamina Share", 0.10f,
- new ConfigDescription("Fraction of that health turned into stamina instead, for creatures past the Black Forest. 0.1 = 10%.", new AcceptableValueRange(0f, 1f)));
- EarlyStaminaShare = config.Bind(devour, "Early Creature Stamina Share", 0.60f,
- new ConfigDescription("The same, for Meadows and Black Forest creatures. Above 0.5 they feed more stamina than health. Set it equal to the one above to treat every creature alike.", new AcceptableValueRange(0f, 1f)));
- FoodCapBase = config.Bind(devour, "Food Health Cap Base", 15f,
- new ConfigDescription("Creatures with no hand-set meal feed half their health. That is capped at this plus the per-biome value times the biome's number (Meadows 1 ... Deep North 8). With the defaults: Black Forest 45, Mountains 75, Plains 90.", new AcceptableValueRange(0f, 150f)));
- FoodCapPerBiome = config.Bind(devour, "Food Health Cap Per Biome", 15f,
- new ConfigDescription("See the base cap above.", new AcceptableValueRange(0f, 50f)));
-
- // Jotunn's server sync assigns Value, which fires SettingChanged, so the server's
- // numbers reach the foods the same way a local drag does.
- foreach (var entry in new[] { DevourHealthMultiplier, DevourStaminaShare, EarlyStaminaShare, FoodCapBase, FoodCapPerBiome })
- {
- entry.SettingChanged += (_, __) => AswidRace.ApplyAllFoodBalance();
- }
const string domination = "Aswid - Domination";
EnslaveCooldown = config.Bind(domination, "Enslave Cooldown", 900f,
@@ -476,7 +297,7 @@ namespace RacesOfValheim
new ConfigDescription("As above, around the third axis. The default half turn is what rights the borrowed socket, which arrives upside down on a player's head bone.",
new AcceptableValueRange(-180f, 180f), new ConfigurationManagerAttributes { Order = 58 }));
- EyeSmoke = config.Bind(eyes, "Eye Smoke", false,
+ EyeSmoke = config.Bind(eyes, "Eye Smoke", true,
new ConfigDescription("Lights the smoke the creature carries inside its own sockets and leaves switched off. Tinted to match the eyes, so it turns with them at the last stage.",
null, new ConfigurationManagerAttributes { Order = 50 }));
EyeFlatColorShader = config.Bind(eyes, "Eye Flat Colour Shader", false,
diff --git a/JotunnModStub/Aswid/AswidPatches.cs b/JotunnModStub/Aswid/AswidPatches.cs
index b607ad9..6f4be0a 100644
--- a/JotunnModStub/Aswid/AswidPatches.cs
+++ b/JotunnModStub/Aswid/AswidPatches.cs
@@ -219,32 +219,6 @@ namespace RacesOfValheim
}
}
- ///
- /// Fire and pierce hurt the Aswid more: fire for the old way vampires end, pierce for the
- /// stake. A plain multiplier, like the Trol's fire weakness, rather than DamageModifier.Weak,
- /// which is a fixed +50% with nothing in between. ApplyDamage runs after resistances, so a
- /// fire resistance mead still helps, and Mist Form's pierce immunity has already zeroed the
- /// pierce by the time this sees it.
- ///
- [HarmonyPatch(typeof(Character), "ApplyDamage")]
- public static class Aswid_Weakness_Patch
- {
- public static void Prefix(Character __instance, ref HitData hit)
- {
- if (__instance != Player.m_localPlayer || !AswidRace.IsAswid()) return;
-
- if (AswidRace.HasFireWeakness(BossProgressionManager.GetCurrentProgressionState()) && hit.m_damage.m_fire > 0f)
- {
- hit.m_damage.m_fire *= 1f + AswidConfig.FireWeakness.Value;
- }
-
- if (AswidConfig.PierceWeaknessEnabled.Value && hit.m_damage.m_pierce > 0f)
- {
- hit.m_damage.m_pierce *= 1f + AswidConfig.PierceWeakness.Value;
- }
- }
- }
-
[HarmonyPatch(typeof(Humanoid), "StartAttack")]
public static class Aswid_Attack_Patch
{
@@ -523,7 +497,7 @@ namespace RacesOfValheim
{
public static bool Prefix(Hud __instance, Player player)
{
- if (player == Player.m_localPlayer && DraughRace.IsDraugh())
+ if (player == Player.m_localPlayer && (AswidRace.IsAswid() || DraughRace.IsDraugh()))
{
if (__instance.m_staminaBar2Root != null && __instance.m_staminaBar2Root.gameObject.activeSelf)
{
@@ -533,8 +507,7 @@ namespace RacesOfValheim
}
// Vanilla switches the bar on once, when the HUD is built, and never again. Without
- // this a player who left the Draugh had no stamina bar until relog - and an Aswid
- // updating from a version that still hid it would have none either.
+ // this a player who left the Aswid or the Draugh had no stamina bar until relog.
if (player == Player.m_localPlayer && __instance.m_staminaBar2Root != null
&& !__instance.m_staminaBar2Root.gameObject.activeSelf)
{
@@ -624,13 +597,6 @@ namespace RacesOfValheim
{
bool isBat = nview.GetZDO().GetBool("Aswid_IsBatForm", false);
bool isMist = nview.GetZDO().GetBool("Aswid_IsMistForm", false);
-
- // The bat flies on m_flying, which only the bat's own client sets. Mirror it here
- // and switch gravity off for the duration, or this copy sinks to the terrain
- // whatever altitude is replicated - the same fix ZdoVisualSync applies to drakes.
- HarmonyLib.Traverse.Create(player).Field("m_flying").SetValue(isBat);
- Rigidbody body = player.GetComponent();
- if (body != null && body.useGravity == isBat) body.useGravity = !isBat;
Transform playerVisual = player.transform.Find("Visual");
@@ -854,104 +820,6 @@ namespace RacesOfValheim
stamina += extraFood.m_stamina;
eitr += extraFood.m_eitr;
}
-
- // Added on top of whatever vanilla and other mods put here, never assigned: a mod that
- // raises max stamina has to keep raising it for an Aswid too.
- stamina += AswidRace.GetStaminaBonus(BossProgressionManager.GetCurrentProgressionState());
- }
- }
-
- ///
- /// The Aswid's stamina. It used to be infinite: the Skeleton's UseStamina skip covered the
- /// Aswid too, which made every stamina mod, food and skill meaningless for the race (the Discord
- /// reports that started the rebalance). The cost is now scaled rather than skipped, so the
- /// call still reaches vanilla - and any other mod patching it - with a smaller number.
- ///
- [HarmonyPatch(typeof(Player), "UseStamina")]
- public static class Aswid_UseStamina_Patch
- {
- public static void Prefix(Player __instance, ref float v)
- {
- if (__instance != Player.m_localPlayer || !AswidRace.IsAswid()) return;
- v *= AswidConfig.StaminaCostMultiplier.Value;
-
- if (Aswid_SwimCost_Patch.Swimming && AswidConfig.RunningWaterEnabled.Value)
- {
- v *= AswidConfig.SwimStaminaMultiplier.Value;
- }
- }
- }
-
- ///
- /// Marks the frames where vanilla charges for a swim stroke, so Aswid_UseStamina_Patch can
- /// make that one cost dearer. Player.OnSwimming is the only place swimming spends stamina,
- /// and it also runs the drowning check right after - which is what makes a high multiplier
- /// play as "cannot swim" without any code of ours deciding who drowns.
- ///
- [HarmonyPatch(typeof(Player), "OnSwimming")]
- public static class Aswid_SwimCost_Patch
- {
- public static bool Swimming { get; private set; }
-
- public static void Prefix(Player __instance)
- {
- Swimming = __instance == Player.m_localPlayer;
- }
-
- public static void Finalizer()
- {
- Swimming = false;
- }
- }
-
- ///
- /// The seasick camera: a slow roll while the Aswid is out on the water, on a boat too. Applied after
- /// vanilla has settled the camera's rotation for the frame, as a roll around the view axis,
- /// so it never moves where the player aims - only how the horizon sits.
- ///
- [HarmonyPatch(typeof(GameCamera), "GetCameraPosition")]
- public static class Aswid_SeaCameraSway_Patch
- {
- private const float DegreesAtStrengthOne = 4f;
- private static float sway;
-
- public static void Postfix(float dt, ref Quaternion rot)
- {
- bool on = AswidRace.OnWater && AswidConfig.SeaCameraSway.Value && AswidRace.IsAswid() &&
- Player.m_localPlayer != null && !Player.m_localPlayer.IsDead();
-
- // Eased in and out over about a second, so leaving the sea does not snap the horizon.
- sway = Mathf.MoveTowards(sway, on ? 1f : 0f, dt);
- if (sway <= 0f) return;
-
- float t = Time.time;
- float roll = (Mathf.Sin(t * 0.9f) + 0.4f * Mathf.Sin(t * 2.3f)) * DegreesAtStrengthOne *
- AswidConfig.SeaCameraSwayStrength.Value * sway;
- rot *= Quaternion.AngleAxis(roll, Vector3.forward);
- }
- }
-
- ///
- /// 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;
}
}
diff --git a/JotunnModStub/Aswid/AswidRace.cs b/JotunnModStub/Aswid/AswidRace.cs
index 8367a64..fb949a3 100644
--- a/JotunnModStub/Aswid/AswidRace.cs
+++ b/JotunnModStub/Aswid/AswidRace.cs
@@ -191,11 +191,6 @@ namespace RacesOfValheim
if (c != null)
{
float foodHp = Mathf.Min(c.m_health / 2f, 150f);
- // The formula alone only knows how big a creature is, not where it
- // lives - a Black Forest troll came out at 150. Only these get the
- // per-biome cap in ApplyFoodBalance; the hand-set values below are
- // choices, not formula output, and keep theirs.
- bool fromFormula = true;
// Capped at 50 minutes: a tough creature like the Barka would otherwise
// feed for over an hour.
float burnTime = Mathf.Min(c.m_health * 2f, 3000f);
@@ -206,38 +201,24 @@ namespace RacesOfValheim
{
burnTime = 1200f; // 20 minutes
}
- else if (mobName == "JotunWitch") { foodHp = 120f; burnTime = 3600f; fromFormula = false; } // 60 minutes
- else if (mobName == "ElakingMole") { foodHp = 100f; burnTime = 1800f; fromFormula = false; } // 30 minutes
- else if (mobName.StartsWith("Dverger") && mobName != "DvergerDeepNorth") { foodHp = 90f; burnTime = 1500f; fromFormula = false; } // 25 minutes
- else if (mobName == "DvergerDeepNorth") { foodHp = 100f; burnTime = 1800f; fromFormula = false; } // 30 minutes
- else if (mobName == "Greyling") { foodHp = 20f; burnTime = 1200f; fromFormula = false; }
- else if (mobName == "Greydwarf") { foodHp = 25f; burnTime = 1200f; fromFormula = false; }
- else if (mobName == "Greydwarf_Shaman") { foodHp = 30f; burnTime = 1200f; fromFormula = false; }
- else if (mobName == "Greydwarf_Elite") { foodHp = 60f; burnTime = 1800f; fromFormula = false; }
+ else if (mobName == "JotunWitch") { foodHp = 120f; burnTime = 3600f; } // 60 minutes
+ else if (mobName == "ElakingMole") { foodHp = 100f; burnTime = 1800f; } // 30 minutes
+ else if (mobName.StartsWith("Dverger") && mobName != "DvergerDeepNorth") { foodHp = 90f; burnTime = 1500f; } // 25 minutes
+ else if (mobName == "DvergerDeepNorth") { foodHp = 100f; burnTime = 1800f; } // 30 minutes
+ else if (mobName == "Greyling") { foodHp = 20f; burnTime = 1200f; }
+ else if (mobName == "Greydwarf") { foodHp = 25f; burnTime = 1200f; }
+ else if (mobName == "Greydwarf_Shaman") { foodHp = 30f; burnTime = 1200f; }
+ else if (mobName == "Greydwarf_Elite") { foodHp = 60f; burnTime = 1800f; }
customItem.ItemDrop.m_itemData.m_shared.m_food = foodHp;
customItem.ItemDrop.m_itemData.m_shared.m_foodStamina = 0f;
customItem.ItemDrop.m_itemData.m_shared.m_foodEitr = 0f;
customItem.ItemDrop.m_itemData.m_shared.m_foodBurnTime = burnTime;
customItem.ItemDrop.m_itemData.m_shared.m_foodRegen = Mathf.Max(1f, foodHp / 15f);
- if (fromFormula) formulaFoods.Add(foodName);
}
}
}
- // What the item gives before any balance setting, kept so ApplyFoodBalance can be
- // rerun from scratch whenever a setting changes or the server's values arrive.
- var shared = customItem.ItemDrop.m_itemData.m_shared;
- baseFoods[foodName] = new BaseFood
- {
- Mob = mobName,
- Health = shared.m_food,
- Stamina = shared.m_foodStamina,
- Regen = shared.m_foodRegen,
- Shared = shared
- };
- ApplyFoodBalance(foodName);
-
GameObject trophyPrefab = Jotunn.Managers.PrefabManager.Cache.GetPrefab(trophyName);
if (trophyPrefab != null)
{
@@ -253,82 +234,10 @@ namespace RacesOfValheim
}
}
- private class BaseFood
- {
- public string Mob;
- public float Health;
- public float Stamina;
- public float Regen;
- public ItemDrop.ItemData.SharedData Shared;
- }
-
- private static readonly Dictionary baseFoods = new Dictionary();
- private static readonly HashSet formulaFoods = new HashSet();
-
- ///
- /// The biome each edible creature lives in, as a number from 1 (Meadows) to 8 (Deep North).
- /// It decides two things: the cap on formula-made foods, and which creatures count as early
- /// game (1 and 2) for the larger stamina share. A creature missing here counts as tier 8,
- /// which means uncapped in practice and never early.
- ///
- private static readonly Dictionary mobBiomeTier = new Dictionary
- {
- { "Boar", 1 }, { "Neck", 1 }, { "Deer", 1 }, { "Greyling", 1 },
- { "Greydwarf", 2 }, { "Greydwarf_Elite", 2 }, { "Greydwarf_Shaman", 2 }, { "Troll", 2 },
- { "Leech", 3 },
- { "Wolf", 4 }, { "Fenring", 4 }, { "Fenring_Cultist", 4 }, { "Ulv", 4 }, { "Hatchling", 4 },
- { "Lox", 5 }, { "Goblin", 5 }, { "GoblinArcher", 5 }, { "GoblinShaman", 5 }, { "GoblinBrute", 5 }, { "Deathsquito", 5 },
- { "Hare", 6 }, { "Seeker", 6 }, { "SeekerBrood", 6 }, { "SeekerBrute", 6 }, { "Gjall", 6 }, { "Tick", 6 },
- { "Dverger", 6 }, { "DvergerMage", 6 }, { "DvergerMageFire", 6 }, { "DvergerMageIce", 6 }, { "DvergerMageSupport", 6 },
- { "Asksvin", 7 }, { "Volture", 7 }, { "DvergerAshlands", 7 },
- };
-
- public const int EarlyBiomeTier = 2;
-
- private static int GetBiomeTier(string mob) => mobBiomeTier.TryGetValue(mob, out int tier) ? tier : 8;
-
- ///
- /// Rewrites one devour food from its unbalanced base and the current settings. The Discord
- /// reports said even weak kills fed too much health; Dissolution asked for about 10% less,
- /// and for early creatures to feed stamina more than health. So: health is scaled first,
- /// then a share of it moves over to stamina. Vanilla meals the food was cloned from keep
- /// the stamina they already had, the share goes on top.
- ///
- /// Writing the shared data is enough to reach every copy: eaten foods, the extra slot and
- /// the tooltip all read the same SharedData through their ItemData.
- ///
- private static void ApplyFoodBalance(string foodName)
- {
- if (!baseFoods.TryGetValue(foodName, out BaseFood food) || food.Shared == null) return;
-
- int tier = GetBiomeTier(food.Mob);
- float health = food.Health;
- if (formulaFoods.Contains(foodName))
- {
- health = Mathf.Min(health, AswidConfig.FoodCapBase.Value + AswidConfig.FoodCapPerBiome.Value * tier);
- }
-
- float healthMultiplier = AswidConfig.DevourHealthMultiplier.Value;
- health *= healthMultiplier;
-
- float share = tier <= EarlyBiomeTier ? AswidConfig.EarlyStaminaShare.Value : AswidConfig.DevourStaminaShare.Value;
- float moved = health * share;
-
- food.Shared.m_food = health - moved;
- food.Shared.m_foodStamina = food.Stamina + moved;
- // Regen follows the health the food ends up giving, cap included, so a troll capped
- // to 40 health does not keep the 10 per tick its old 150 earned.
- float healthRatio = food.Health > 0f ? food.Shared.m_food / food.Health : 0f;
- food.Shared.m_foodRegen = Mathf.Max(1f, food.Regen * healthRatio);
- }
-
- /// Hooked to the balance settings, which also fire when the server's values arrive.
- public static void ApplyAllFoodBalance()
- {
- foreach (string foodName in baseFoods.Keys) ApplyFoodBalance(foodName);
- }
-
private float m_tintCheckTimer = 0f;
+ private float sensesCheckTimer = 0f;
+
+ private Dictionary activeSensesLight = new Dictionary();
public static float GetEnslaveCooldown()
{
@@ -370,7 +279,6 @@ namespace RacesOfValheim
{
seman.RemoveStatusEffect(myHash);
}
- HunterSenses.Clear();
return;
}
@@ -379,8 +287,64 @@ namespace RacesOfValheim
seman.AddStatusEffect(myHash, true);
}
- int markHash = "SE_AswidSensesMark".GetStableHashCode();
- HunterSenses.Tick(AswidConfig.SensesRadius.Value, c => c.GetSEMan().AddStatusEffect(markHash, true));
+ sensesCheckTimer -= Time.deltaTime;
+ if (sensesCheckTimer <= 0f)
+ {
+ sensesCheckTimer = AswidConfig.SensesRefreshInterval.Value; // TTL is 2s
+
+ List allChars = Character.GetAllCharacters();
+ Vector3 myPos = Player.m_localPlayer.transform.position;
+
+ int markHash = "SE_AswidSensesMark".GetStableHashCode();
+ HashSet inRangeChars = new HashSet();
+
+ foreach (var c in allChars)
+ {
+ if (c == null || c == Player.m_localPlayer || c.IsDead() || c.IsTamed()) continue;
+
+ float dist = Vector3.Distance(c.transform.position, myPos);
+ if (dist <= AswidConfig.SensesRadius.Value)
+ {
+ try
+ {
+ inRangeChars.Add(c);
+ c.GetSEMan().AddStatusEffect(markHash, true); // Keep the malus as requested
+
+ // Locally generate the visual
+ if (!activeSensesLight.ContainsKey(c))
+ {
+ GameObject lightObj = new GameObject("AswidSensesLight");
+ lightObj.transform.SetParent(c.transform);
+ lightObj.transform.position = c.GetCenterPoint();
+
+ Light pLight = lightObj.AddComponent();
+ pLight.type = LightType.Point;
+ pLight.color = Color.green;
+ pLight.range = AswidConfig.SensesLightRange.Value;
+ pLight.intensity = AswidConfig.SensesLightIntensity.Value;
+ pLight.shadows = LightShadows.None;
+
+ activeSensesLight[c] = lightObj;
+ }
+ }
+ catch (Exception ex)
+ {
+ Jotunn.Logger.LogError($"[Aswid] Error processing mob {c.name}: {ex}");
+ }
+ }
+ }
+
+ List keysToRemove = new List();
+ foreach (var kvp in activeSensesLight)
+ {
+ if (kvp.Key == null || kvp.Key.IsDead() || !inRangeChars.Contains(kvp.Key))
+ {
+ if (kvp.Value != null) Destroy(kvp.Value);
+ keysToRemove.Add(kvp.Key);
+ }
+ }
+ foreach (var k in keysToRemove) activeSensesLight.Remove(k);
+ }
}
catch (Exception ex)
{
@@ -388,6 +352,15 @@ namespace RacesOfValheim
}
}
+ private void ClearSuperhumanSenses()
+ {
+ foreach (var kvp in activeSensesLight)
+ {
+ if (kvp.Value != null) Destroy(kvp.Value);
+ }
+ activeSensesLight.Clear();
+ }
+
private bool? wasNight = null;
private void Update()
@@ -441,8 +414,6 @@ namespace RacesOfValheim
{
updateTimer = 0f;
UpdateAswidState();
- UpdateSunlight(UpdateInterval);
- UpdateOpenSea(UpdateInterval);
}
try
@@ -609,38 +580,9 @@ namespace RacesOfValheim
return;
}
- if (AswidConfig.BatEncumbered.Value == AswidConfig.EncumberedMode.Blocked && Player.m_localPlayer.IsEncumbered())
- {
- Player.m_localPlayer.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_aswid_too_heavy_for_bat"));
- 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)
- {
- Player.m_localPlayer.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_aswid_bat_cooldown", Mathf.CeilToInt(cooldownLeft)));
- return;
- }
-
RunFormRoutine(TransformIntoBatRoutine(rules));
}
- // When the bat form last ended, for the optional cooldown. Starts far enough back that a
- // 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.
@@ -714,7 +656,7 @@ namespace RacesOfValheim
/// Update() has already bailed out on IsDead(), so a coroutine started here would be the
/// only thing still running on a corpse.
///
- /// Leaving the form up costs more than a missing animation: m_flying stays on, so the
+ /// Leaving the form up costs more than a missing animation: m_debugFly stays on, so the
/// respawned player floats; Aswid_IsBatForm stays true in the ZDO, so every other client
/// keeps drawing a bat over a body that is walking around as a person; and the 5% scale
/// stays on the transform. Called from Aswid_BatDiesAsBat_Patch.
@@ -740,13 +682,12 @@ namespace RacesOfValheim
if (nview != null && nview.IsValid())
{
nview.GetZDO().Set("Aswid_IsBatForm", false);
+ nview.GetZDO().Set(ZDOVars.s_debugFly, false);
}
- // Now, not when the destroyed model's OnDestroy gets round to it at the end of the frame.
- BatFormBehavior.SetFlying(false);
+ Traverse.Create(player).Field("m_debugFly").SetValue(false);
player.transform.localScale = Vector3.one;
- lastBatEndTime = Time.time;
IsTransformed = false;
activeRules = null;
isTransformingSequence = false;
@@ -846,7 +787,6 @@ namespace RacesOfValheim
}
Player.m_localPlayer.transform.localScale = endScale;
- lastBatEndTime = Time.time;
IsTransformed = false;
activeRules = null;
isTransformingSequence = false;
@@ -1131,14 +1071,13 @@ namespace RacesOfValheim
private float damageTickTimer = 0f;
///
- /// The Vampiric Aura drains on its own, with no key to hold (as a bat only once
- /// BatAuraAllowed says so) - but it does not
+ /// The Vampiric Aura drains on its own, in every form, with no key to hold - but it does not
/// distinguish traders from monsters, so it can execute Haldor/Hildir on approach. AuraEnabled
/// (toggled with Devour on the same key) is the escape hatch for that.
///
private void HandleVampiricAura()
{
- if (!AuraEnabled || (IsBatForm() && !BatAuraAllowed(BossProgressionManager.GetCurrentProgressionState())))
+ if (!AuraEnabled)
{
damageTickTimer = 0f;
return;
@@ -1151,24 +1090,6 @@ namespace RacesOfValheim
PerformLifeDrain();
}
- private static bool IsBatForm()
- {
- return Player.m_localPlayer.GetSEMan().HaveStatusEffect("SE_BatForm".GetStableHashCode());
- }
-
- ///
- /// Whether the aura drains while the player is a bat. Off until the Queen by default: a bat
- /// gliding over enemies that cannot reach it, draining them the whole way, was the "unfun
- /// optimal way to play" Dissolution reported. The flag turns it back on for everyone; the
- /// unlock state brings it back as a late-game reward, 0 meaning never.
- ///
- public static bool BatAuraAllowed(int state)
- {
- if (AswidConfig.AuraInBatForm.Value) return true;
- int unlock = AswidConfig.BatAuraUnlockState.Value;
- return unlock > 0 && state >= unlock;
- }
-
/// Half damage as a human, full as a bat, double as mist.
private float GetAuraFormMultiplier()
{
@@ -1191,7 +1112,6 @@ 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)
{
@@ -1242,16 +1162,10 @@ 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)
{
@@ -1357,10 +1271,7 @@ namespace RacesOfValheim
// up, but there used to be nothing to see either. Silence is what made
// a refused meal indistinguishable from a devour that never fired:
// vanilla's own "can't eat more" line, localized for free.
- // The token carries a $1 for the food's name, which vanilla's CanEat
- // fills in; sent bare, players read "can't eat more $1".
- Player.m_localPlayer.Message(MessageHud.MessageType.TopLeft,
- Localization.instance.Localize("$msg_nomore", addedItem.m_shared.m_name));
+ Player.m_localPlayer.Message(MessageHud.MessageType.TopLeft, "$msg_nomore");
}
}
else
@@ -1409,136 +1320,6 @@ namespace RacesOfValheim
}
}
- /// Fader's Surtling form ends it, unless the setting keeps it for good.
- public static bool HasFireWeakness(int state)
- {
- if (!AswidConfig.FireWeaknessEnabled.Value) return false;
- return !(AswidConfig.FaderRemovesFireWeakness.Value && state >= 8);
- }
-
- private static readonly int SunlightHash = "SE_AswidSunlight".GetStableHashCode();
-
- ///
- /// The V Rising weakness: by day, under open sky, the sun saps the Aswid. Anything that
- /// keeps the sky off you counts as shade - a roof by vanilla's own shelter test, a dungeon,
- /// the Swamp's and Mistlands' gloom, the night, and the Aswid's own Eclipse, which makes
- /// that spell an answer to the sun rather than only a damage boost.
- ///
- private void UpdateSunlight(float dt)
- {
- Player player = Player.m_localPlayer;
- SEMan seman = player.GetSEMan();
-
- bool exposed = InSunlight(player);
- bool has = seman.HaveStatusEffect(SunlightHash);
-
- if (!exposed)
- {
- if (has) seman.RemoveStatusEffect(SunlightHash, true);
- return;
- }
-
- if (!has) seman.AddStatusEffect(SunlightHash, true);
- (seman.GetStatusEffect(SunlightHash) as SE_AswidSunlight)?.Refresh();
-
- // SetHealth rather than Damage or UseHealth: a burn every second should not stagger,
- // interrupt a swing or flash the screen red each time. Never below the floor, so
- // the sun can wear you down but never be what kills you.
- float floor = player.GetMaxHealth() * AswidConfig.SunHealthFloor.Value;
- float health = player.GetHealth();
- float loss = AswidConfig.SunHealthLossPerSecond.Value * dt;
- if (loss > 0f && health > floor)
- {
- player.SetHealth(Mathf.Max(floor, health - loss));
- }
- }
-
- private bool InSunlight(Player player)
- {
- if (!AswidConfig.SunlightEnabled.Value) return false;
- if (EnvMan.instance == null || !EnvMan.IsDay()) return false;
- if (IsEclipseActive) return false;
- if (player.InInterior() || player.InShelter()) return false;
-
- Heightmap.Biome biome = player.GetCurrentBiome();
- return biome != Heightmap.Biome.Swamp && biome != Heightmap.Biome.Mistlands;
- }
-
- private static readonly int OpenSeaHash = "SE_AswidOpenSea".GetStableHashCode();
-
- // How deep the water under an airborne Aswid has to be before it counts. Keeps a hop over
- // a puddle or a swamp ditch from registering; a bat over a river or a lake still does.
- private const float MinFlyOverDepth = 1f;
-
- /// True while the local Aswid is out on the water, boat or not. Read by the camera sway.
- public static bool OnWater { get; private set; }
-
- ///
- /// Dagaz's running water: open water burns and drains an Aswid in it or over it, swimming
- /// or flying - a bat cannot simply cross a lake or the sea. A boat carries you across, as
- /// the lore allows: on board there is no burn and no drain, but the sea still turns your
- /// stomach, so the camera keeps swaying.
- ///
- private void UpdateOpenSea(float dt)
- {
- Player player = Player.m_localPlayer;
- SEMan seman = player.GetSEMan();
-
- bool onBoat = OnBoat(player);
- bool exposed = !onBoat && InOpenWater(player);
- OnWater = AswidConfig.RunningWaterEnabled.Value && (exposed || (onBoat && BiomeAllowed(player)));
-
- bool has = seman.HaveStatusEffect(OpenSeaHash);
- if (!exposed)
- {
- if (has) seman.RemoveStatusEffect(OpenSeaHash, true);
- return;
- }
- if (!has) seman.AddStatusEffect(OpenSeaHash, true);
-
- float drain = AswidConfig.SeaStaminaDrainPerSecond.Value * dt;
- if (drain > 0f) player.UseStamina(drain);
-
- // SetHealth for the same reasons as the sun: no stagger, no flash each second.
- float floor = player.GetMaxHealth() * AswidConfig.SeaHealthFloor.Value;
- float health = player.GetHealth();
- float loss = AswidConfig.SeaHealthLossPerSecond.Value * dt;
- if (loss > 0f && health > floor)
- {
- player.SetHealth(Mathf.Max(floor, health - loss));
- }
- }
-
- private static bool OnBoat(Player player)
- {
- return player.GetStandingOnShip() != null || player.IsAttachedToShip() || player.GetControlledShip() != null;
- }
-
- /// The Ocean-only setting, if on, limits everything here to the sea.
- private static bool BiomeAllowed(Player player)
- {
- return !AswidConfig.WaterOceanOnly.Value || player.GetCurrentBiome() == Heightmap.Biome.Ocean;
- }
-
- ///
- /// In water or over it. Valheim has one water plane for the sea, the rivers and the lakes
- /// alike, so "the terrain under you is below the water level" finds all three. Swimming
- /// counts wherever it happens. In the air it takes a metre of water below, so a jump over
- /// a puddle does not; standing on anything solid - a dock, a bridge, a shallow bank you
- /// are wading on - does not count, since the ground ray only sees terrain and would
- /// otherwise read a dock as open water.
- ///
- private static bool InOpenWater(Player player)
- {
- if (!AswidConfig.RunningWaterEnabled.Value) return false;
- if (!BiomeAllowed(player)) return false;
- if (player.IsSwimming()) return true;
- if (player.IsOnGround() || ZoneSystem.instance == null) return false;
-
- float depth = ZoneSystem.instance.m_waterLevel - ZoneSystem.instance.GetGroundHeight(player.transform.position);
- return depth >= MinFlyOverDepth;
- }
-
private void UpdateAswidState()
{
AswidSpectralClaw.PurgeAll(Player.m_localPlayer); // feature disabled for now, see AswidSpectralClaw.cs
@@ -1563,12 +1344,6 @@ namespace RacesOfValheim
}
}
- /// Max stamina the race adds on top of food, at the given progression state.
- public static float GetStaminaBonus(int state)
- {
- return AswidConfig.BaseStaminaBonus.Value + AswidConfig.StaminaBonusPerState.Value * state;
- }
-
public static bool IsAswid()
{
return Player.m_localPlayer != null &&
diff --git a/JotunnModStub/Aswid/AswidStatusEffects.cs b/JotunnModStub/Aswid/AswidStatusEffects.cs
index d788f5c..0a91feb 100644
--- a/JotunnModStub/Aswid/AswidStatusEffects.cs
+++ b/JotunnModStub/Aswid/AswidStatusEffects.cs
@@ -65,45 +65,6 @@ namespace RacesOfValheim
}
}
- ///
- /// Sunlight on an exposed Aswid. Its numbers are rewritten from AswidConfig every time
- /// AswidRace.UpdateSunlight runs, so a slider moves them live; the health loss is not a stat
- /// and is applied by that same tick.
- ///
- public class SE_AswidSunlight : SE_Stats
- {
- public override void Setup(Character character)
- {
- base.Setup(character);
- name = "SE_AswidSunlight";
- m_name = "$rov_se_aswid_sunlight_name";
- m_tooltip = "$rov_se_aswid_sunlight_tooltip";
- Refresh();
- }
-
- public void Refresh()
- {
- m_healthRegenMultiplier = 1f - AswidConfig.SunHealthRegenPenalty.Value;
- m_staminaRegenMultiplier = 1f - AswidConfig.SunStaminaRegenPenalty.Value;
- m_speedModifier = -AswidConfig.SunSpeedPenalty.Value;
- }
- }
-
- ///
- /// Open water under an Aswid off a boat. Only a marker: the burn and the drain are applied by
- /// AswidRace.UpdateOpenSea, and the camera sway reads AswidRace.OnWater.
- ///
- public class SE_AswidOpenSea : SE_Stats
- {
- public override void Setup(Character character)
- {
- base.Setup(character);
- name = "SE_AswidOpenSea";
- m_name = "$rov_se_aswid_opensea_name";
- m_tooltip = "$rov_se_aswid_opensea_tooltip";
- }
- }
-
public class SE_MistForm : SE_Stats
{
public override void Setup(Character character)
@@ -163,16 +124,6 @@ namespace RacesOfValheim
ItemManager.Instance.AddStatusEffect(new CustomStatusEffect(batForm, fixReference: false));
- var sunlight = ScriptableObject.CreateInstance();
- sunlight.name = "SE_AswidSunlight";
- sunlight.m_icon = PrefabManager.Cache.GetPrefab("TrophySurtling")?.m_itemData.m_shared.m_icons[0];
- ItemManager.Instance.AddStatusEffect(new CustomStatusEffect(sunlight, fixReference: false));
-
- var openSea = ScriptableObject.CreateInstance();
- openSea.name = "SE_AswidOpenSea";
- openSea.m_icon = PrefabManager.Cache.GetPrefab("TrophySerpent")?.m_itemData.m_shared.m_icons[0];
- ItemManager.Instance.AddStatusEffect(new CustomStatusEffect(openSea, fixReference: false));
-
var mistForm = ScriptableObject.CreateInstance();
mistForm.name = "SE_MistForm";
mistForm.m_icon = PrefabManager.Cache.GetPrefab("TrophyWraith")?.m_itemData.m_shared.m_icons[0];
diff --git a/JotunnModStub/Aswid/AswidVisuals.cs b/JotunnModStub/Aswid/AswidVisuals.cs
index c0822ad..b118424 100644
--- a/JotunnModStub/Aswid/AswidVisuals.cs
+++ b/JotunnModStub/Aswid/AswidVisuals.cs
@@ -58,12 +58,6 @@ namespace RacesOfValheim
private const float BaseEyeHeight = 0.181f;
private const float BaseEyeSeparation = 0.032f;
- // The borrowed socket at the size the Skeleton wears it, times the config multiplier, was
- // two green blocks on the face; at half it was smaller than the painted eye underneath,
- // which then showed round it. Applied before the multiplier, so a saved config keeps its
- // meaning as "relative to the default".
- private const float BaseEyeScale = 0.75f;
-
// ─── Race check ─────────────────────────────────────────────────────
///
@@ -105,10 +99,6 @@ namespace RacesOfValheim
// built again rather than merely moved.
public string SourceModel = "";
public bool FlatShader;
-
- // Which body the base pose was measured for: the female face puts the eyes elsewhere
- // (PlayerFace), so a change of body model is a rebuild too.
- public bool Female;
}
/// The pose an eye was authored at on the creature. Everything else is a delta on this.
@@ -190,8 +180,7 @@ namespace RacesOfValheim
EyeFrame existing = eyes.GetComponent();
if (existing == null ||
existing.SourceModel != AswidConfig.EyeSourceModel.Value ||
- existing.FlatShader != AswidConfig.EyeFlatColorShader.Value ||
- existing.Female != PlayerFace.IsFemale(player))
+ existing.FlatShader != AswidConfig.EyeFlatColorShader.Value)
{
eyes.name = EyesName + "_Removed";
Object.Destroy(eyes.gameObject);
@@ -320,6 +309,9 @@ namespace RacesOfValheim
float scale = GetPlayerScale(player) * toLocal;
+ Vector3 shift = frame.LocalForward * (AswidConfig.EyeForwardOffset.Value * scale)
+ + frame.LocalUp * (AswidConfig.EyeHeightOffset.Value * scale);
+
for (int i = 0; i < holder.childCount; i++)
{
Transform eye = holder.GetChild(i);
@@ -332,16 +324,6 @@ namespace RacesOfValheim
float side = Mathf.Sign(Vector3.Dot(authored.Position, frame.LocalRight));
if (side == 0f) side = i == 0 ? -1f : 1f;
- // This eye's hand corrections (RaceEyeTuning), on top of the race's own offsets.
- RaceEyeTuning.Eye tuning = RaceEyeTuning.For("Aswid", player, side);
- float forward = AswidConfig.EyeForwardOffset.Value + (tuning != null ? tuning.Forward : 0f);
- float height = AswidConfig.EyeHeightOffset.Value + (tuning != null ? tuning.Height : 0f);
- float separation = AswidConfig.EyeSeparationOffset.Value + (tuning != null ? tuning.Separation : 0f);
- float size = AswidConfig.EyeSizeMultiplier.Value * (tuning != null ? tuning.Size : 1f);
-
- Vector3 shift = frame.LocalForward * (forward * scale)
- + frame.LocalUp * (height * scale);
-
// YAW IS MIRRORED, the other two are not. Turning both eyes the same way on Y
// makes the pair look sideways - both point off the same shoulder, because a face
// is symmetric about its centre line and yaw is the axis that crosses it. Negating
@@ -350,31 +332,15 @@ namespace RacesOfValheim
//
// Pitch and roll are shared deliberately: both eyes looking up is a face looking
// up, and mirroring either of those would cross them instead of aiming them.
- //
- // This twist is on the HEAD BONE's raw axes (it multiplies from the left), and on
- // this rig those are not the face's: bone X points out of the face and bone Z
- // sideways. The defaults were dialled in against that, so it stays as it is.
Quaternion twist = Quaternion.Euler(
AswidConfig.EyeRotationX.Value,
AswidConfig.EyeRotationY.Value * side,
AswidConfig.EyeRotationZ.Value);
- // The RaceEyeTuning corrections turn the eye on the FACE's axes instead: conjugated by
- // the face frame, X tips it, Y turns it toward the temple and Z raises the outer
- // corner, the same on both eyes. Added to the bone-axis twist above, X rolled the
- // eyes and a mirrored Z tipped one up and the other down.
- Quaternion nudge = Quaternion.identity;
- if (tuning != null)
- {
- nudge = authored.Rotation
- * Quaternion.Euler(tuning.RotX, tuning.RotY * side, tuning.RotZ * side)
- * Quaternion.Inverse(authored.Rotation);
- }
-
eye.localPosition = authored.Position + shift +
- frame.LocalRight * (side * separation * scale);
- eye.localRotation = nudge * twist * authored.Rotation;
- eye.localScale = authored.Scale * size;
+ frame.LocalRight * (side * AswidConfig.EyeSeparationOffset.Value * scale);
+ eye.localRotation = twist * authored.Rotation;
+ eye.localScale = authored.Scale * AswidConfig.EyeSizeMultiplier.Value;
}
}
@@ -458,12 +424,6 @@ namespace RacesOfValheim
MeasureFrame(player, headBone, frame);
frame.SourceModel = modelName;
frame.FlatShader = AswidConfig.EyeFlatColorShader.Value;
- frame.Female = PlayerFace.IsFemale(player);
-
- float baseHeight = BaseEyeHeight;
- float baseSeparation = BaseEyeSeparation;
- float baseSize = BaseEyeScale;
- PlayerFace.AdjustEyes(player, ref baseHeight, ref baseSeparation, ref baseSize);
// canonicalToFrame turns "face forward, as authored" into "face forward, on THIS
// rig's own axes" - the rotation that carries the ordinary (X,Y,Z) convention onto
@@ -498,8 +458,8 @@ namespace RacesOfValheim
float toLocal = 1f / headBone.lossyScale.x;
Vector3 basePosition = frame.LocalForward * (BaseEyeForward * toLocal)
- + frame.LocalUp * (baseHeight * toLocal)
- + frame.LocalRight * (side * baseSeparation * toLocal);
+ + frame.LocalUp * (BaseEyeHeight * toLocal)
+ + frame.LocalRight * (side * BaseEyeSeparation * toLocal);
// The socket's own authored tilt is skipped for the same reason its position is -
// canonicalToFrame alone (face forward, on this rig's axes) is what the config's
@@ -521,7 +481,7 @@ namespace RacesOfValheim
// this object at on a real skeleton. Divided into the new parent's scale, the pair
// lands at exactly the size vanilla wears them, which is the whole point of
// borrowing them instead of drawing spheres.
- Vector3 baseScale = source.lossyScale * (toLocal * baseSize);
+ Vector3 baseScale = source.lossyScale * toLocal;
// Remembered before anything moves it, because everything the config does is
// expressed as a delta on this.
diff --git a/JotunnModStub/Aswid/BatFormBehavior.cs b/JotunnModStub/Aswid/BatFormBehavior.cs
index e712fec..ef51ba2 100644
--- a/JotunnModStub/Aswid/BatFormBehavior.cs
+++ b/JotunnModStub/Aswid/BatFormBehavior.cs
@@ -1,169 +1,86 @@
using HarmonyLib;
using UnityEngine;
+using Jotunn.Managers;
namespace RacesOfValheim
{
///
/// The bat's flight, held on for as long as the worn model exists.
///
- /// The bat flies on Character.m_flying and is steered by DirectedFlightPatch, the same
- /// controls as the Skadi's drake; this class only hands over the bat's own numbers and keeps
- /// the flag up. It used to fly on vanilla's debug-fly flag, which ignored carry weight, cost
- /// nothing, moved at 50 m/s and made every monster blind to the player - the Discord reports
- /// that started the 2026 rebalance.
+ /// Debug fly has two halves, and this used to write only one. The field Player.m_debugFly is
+ /// what the local player's own physics reads; ZDOVars.s_debugFly is what every OTHER client
+ /// reads, because Character.IsDebugFlying consults the ZDO whenever it is not the owner. With
+ /// only the field written, a bat flew on its own screen and fell, walked and swam on everyone
+ /// else's - the fault WarVultureMount.SetFlying already names in its own summary. Both halves
+ /// go through SetFlying below now, so there is one place that can ever get it wrong again.
///
- /// Other clients learn the bat is airborne from Aswid_IsBatForm in the ZDO, which
- /// Aswid_MultiplayerVisuals_Patch mirrors into their copy's m_flying.
- ///
- /// FREE FLIGHT. A player who picks it (or a server that forces it, AswidConfig.UsesFreeBatFlight)
- /// gets the old flight back: vanilla's debug fly, both halves (the field for the local physics,
- /// s_debugFly in the ZDO for everyone else), and no DirectedFlight. The mode is read once, when
- /// the form goes up. AswidBatForm keeps monsters seeing and hurting a free-flying bat.
+ /// Writing the ZDO every frame is not network spam: ZDO.Set(int, bool) bottoms out in
+ /// ZDOExtraData.Set, which returns false when the value is unchanged, and only a true return
+ /// bumps the data revision. Read out of the assembly rather than assumed, because "every frame"
+ /// deserved the check.
///
- public class BatFormBehavior : MonoBehaviour, IDirectedFlyer
+ public class BatFormBehavior : MonoBehaviour
{
- private static readonly System.Reflection.FieldInfo FlyingField =
- AccessTools.Field(typeof(Character), "m_flying");
private static readonly System.Reflection.FieldInfo DebugFlyField =
AccessTools.Field(typeof(Player), "m_debugFly");
private Animator anim;
private AswidProgression.FormRules formRules;
- private float startTime;
- private bool warnedTooHeavy;
- private bool expired;
- private bool free;
public void Initialize(AswidProgression.FormRules rules)
{
this.formRules = rules;
}
- // ─── IDirectedFlyer ─────────────────────────────────────────────────────
- // A bat is never grounded on purpose: it flies for as long as the form lasts.
- public bool IsFlying => true;
- public float LastPoweredTime { get; set; }
- public float TurnSpeed => AswidConfig.BatTurnSpeed.Value;
- public float GlideSpeed => AswidConfig.BatGlideSpeed.Value;
- public float BoostSpeed => AswidConfig.BatBoostSpeed.Value;
- public float SprintSpeed => AswidConfig.BatSprintSpeed.Value;
- public float ReverseSpeed => AswidConfig.BatReverseSpeed.Value;
- public float LiftoffSpeed => AswidConfig.BatLiftoffSpeed.Value;
- public float HoverSeconds => AswidConfig.BatHoverSeconds.Value;
- public float PoweredStaminaPerSecond => AswidConfig.BatPoweredStaminaPerSecond.Value * EncumberedCostFactor();
- public float SprintStaminaPerSecond => AswidConfig.BatSprintStaminaPerSecond.Value * EncumberedCostFactor();
- public bool CanPower => !(IsEncumbered() && AswidConfig.BatEncumbered.Value == AswidConfig.EncumberedMode.Blocked);
-
- private static bool IsEncumbered()
- {
- return Player.m_localPlayer != null && Player.m_localPlayer.IsEncumbered();
- }
-
- private static float EncumberedCostFactor()
- {
- return IsEncumbered() ? 1f + AswidConfig.BatEncumberedExtraCost.Value : 1f;
- }
-
- ///
- /// The form's lifetime in seconds at the current state, or 0 for no limit. The per-state
- /// bonus is Dissolution's "scales with boss progression", and only means anything on top
- /// of a base limit.
- ///
- public static float MaxDuration()
- {
- float max = AswidConfig.BatMaxDuration.Value;
- if (max <= 0f) return 0f;
- return max + AswidConfig.BatDurationPerState.Value * BossProgressionManager.GetCurrentProgressionState();
- }
-
private void Start()
{
anim = GetComponentInChildren();
- startTime = Time.time;
- LastPoweredTime = Time.time;
- free = AswidConfig.UsesFreeBatFlight();
- if (!free) DirectedFlight.Register(this);
- Hold();
+ SetFlying(true);
}
private void Update()
{
- Player player = Player.m_localPlayer;
- if (player == null || player.IsDead()) return;
+ if (Player.m_localPlayer == null || Player.m_localPlayer.IsDead()) return;
- // Held every frame rather than set once, for the same reason the debug-fly flag was:
- // anything that clears it mid-form (a vanilla reset, another mod) would drop the bat
- // into walking with the model still on.
- Hold();
-
- // Free Flight ignores weight, so only Stamina Flight warns about it.
- if (!free)
- {
- if (!CanPower && !warnedTooHeavy)
- {
- warnedTooHeavy = true;
- player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_aswid_bat_too_heavy_to_beat"));
- }
- else if (CanPower)
- {
- warnedTooHeavy = false;
- }
- }
-
- float max = MaxDuration();
- if (max > 0f && !expired && Time.time - startTime >= max && AswidRace.Instance != null)
- {
- expired = true;
- player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_aswid_bat_form_fades"));
- AswidRace.Instance.ForceRevert();
- }
+ // Ensure flight remains on continuously
+ SetFlying(true);
+ // Sync Animator
if (anim != null)
{
- Vector3 vel = player.GetVelocity();
+ Vector3 vel = Player.m_localPlayer.GetVelocity();
vel.y = 0f;
- anim.SetFloat("forward_speed", vel.magnitude);
+ float speed = vel.magnitude;
+
+ // Bats don't necessarily have a complex animator like players,
+ // but if they do have a speed or flying parameter, we set it here.
+ anim.SetFloat("forward_speed", speed);
anim.SetBool("flying", true);
}
}
private void OnDestroy()
{
- DirectedFlight.Unregister(this);
SetFlying(false);
}
- private void Hold()
- {
- if (free) SetDebugFly(true);
- else SetFlying(true);
- }
-
///
- /// The local half of Stamina Flight. The remote half is the Aswid_IsBatForm ZDO flag
- /// AswidRace already writes, so there is nothing to replicate here. Turning it off also
- /// turns debug fly off, so every exit path ends both flights whichever one was up.
+ /// Both halves of debug fly, always together. The field write survives a missing or invalid
+ /// ZNetView on purpose: without it a bat whose networking went away mid-flight would keep
+ /// flying on foot forever, which is the worse of the two failures.
///
- public static void SetFlying(bool flying)
+ private static void SetFlying(bool flying)
{
Player player = Player.m_localPlayer;
if (player == null) return;
- if (FlyingField != null) FlyingField.SetValue(player, flying);
- if (!flying) SetDebugFly(false);
- }
- ///
- /// Both halves of debug fly, for Free Flight. The ZDO write every frame is not network
- /// spam: ZDO.Set returns early when the value is unchanged.
- ///
- private static void SetDebugFly(bool flying)
- {
- Player player = Player.m_localPlayer;
- if (player == null) return;
if (DebugFlyField != null) DebugFlyField.SetValue(player, flying);
ZNetView nview = player.GetComponent();
- if (nview != null && nview.IsValid() && nview.IsOwner()) nview.GetZDO().Set(ZDOVars.s_debugFly, flying);
+ if (nview != null && nview.IsValid() && nview.IsOwner())
+ {
+ nview.GetZDO().Set(ZDOVars.s_debugFly, flying);
+ }
}
}
}
diff --git a/JotunnModStub/Audio/trolsbuilding.ogg b/JotunnModStub/Audio/trolsbuilding.ogg
deleted file mode 100644
index 697f323..0000000
Binary files a/JotunnModStub/Audio/trolsbuilding.ogg and /dev/null differ
diff --git a/JotunnModStub/Audio/trolsdeath.ogg b/JotunnModStub/Audio/trolsdeath.ogg
deleted file mode 100644
index 9f5ea11..0000000
Binary files a/JotunnModStub/Audio/trolsdeath.ogg and /dev/null differ
diff --git a/JotunnModStub/Butler/BoneServant.cs b/JotunnModStub/Butler/BoneServant.cs
index 59ef5d7..714016f 100644
--- a/JotunnModStub/Butler/BoneServant.cs
+++ b/JotunnModStub/Butler/BoneServant.cs
@@ -218,7 +218,6 @@ namespace RacesOfValheim
}
prefab.transform.localScale = Vector3.one * TableScale;
- Dress(prefab, family);
ServantTableBehaviour table = prefab.AddComponent();
table.m_switch = prefab.AddComponent();
@@ -256,65 +255,6 @@ namespace RacesOfValheim
}));
}
- // The look, in the table's own space BEFORE TableScale, so sizes are divided by it to come out
- // in real metres. The cover lies where the map was: x -2.06 to 0.62, read off the mesh. Its top
- // is the Dvergar bank's PileHeight, on the same vanilla mesh; the mesh's own height is no use
- // here, since the writing desk stands taller than the map.
- private const float CoverTop = 1.05f;
- private static readonly Vector3 TradeSpot = new Vector3(-0.75f, CoverTop, 0.2f);
- private static readonly Vector3 SkullSpot = new Vector3(-1.55f, CoverTop, 0.35f);
- private const float AnvilSize = 0.75f;
- private const float MealSize = 0.6f;
- private const float SkullSize = 0.45f;
-
- ///
- /// The map painted over - a sheet of chainmail for the smith, a red and white tablecloth for the
- /// cook - with the trade's own work on it (an anvil, a meal) and a skeleton's skull beside it.
- ///
- private static void Dress(GameObject prefab, ButlerFamily family)
- {
- bool forge = family == ButlerFamily.Forge;
- LayCover(prefab, forge ? "SmithMail" : "CookCloth", metal: forge);
-
- float metres = 1f / TableScale;
- if (forge)
- {
- ModelBorrow.Attach(prefab.transform, "TableAnvil", "forge_ext2",
- TradeSpot, Quaternion.identity, AnvilSize * metres, "Butler", activeOnly: true);
- }
- else
- {
- ModelBorrow.Attach(prefab.transform, "TableMeal", "MeatPlatter",
- TradeSpot, Quaternion.identity, MealSize * metres, "Butler", activeOnly: true);
- }
- ModelBorrow.Attach(prefab.transform, "TableSkull", "TrophySkeleton",
- SkullSpot, Quaternion.Euler(0f, -150f, 0f), SkullSize * metres, "Butler", activeOnly: true);
- }
-
- ///
- /// The cartography table's own textures with the map painted over, offline:
- /// scripts/paint_cook_cloth.py (CookCloth) and scripts/paint_smith_mail.py (SmithMail). Each set
- /// has its own worn texture for a damaged table (a stained cloth, rusted mail) and its own normal
- /// map, so the coastline's relief does not show through. The mail also brings a metallic map,
- /// which is what makes the rings shine; the cloth keeps vanilla's, which is metal nowhere.
- ///
- private static void LayCover(GameObject prefab, string set, bool metal)
- {
- var cover = new System.Collections.Generic.Dictionary();
- AddCover(cover, "Cartographer_d", set + "_d.png", false);
- AddCover(cover, "Cartographer_worn_d", set + "_worn_d.png", false);
- AddCover(cover, "Cartographer_n", set + "_n.png", true);
- if (metal) AddCover(cover, "Cartographer_m", set + "_m.png", true);
- PieceLook.Retexture(prefab.transform, cover);
- }
-
- private static void AddCover(System.Collections.Generic.Dictionary cover,
- string vanilla, string resource, bool linear)
- {
- Texture2D texture = PieceLook.LoadTexture(resource, linear);
- if (texture != null) cover[vanilla] = texture;
- }
-
public static void EnsureKnown(Player player)
{
if (player == null) return;
diff --git a/JotunnModStub/Butler/BoneServantAI.cs b/JotunnModStub/Butler/BoneServantAI.cs
index 2c165db..db77b6d 100644
--- a/JotunnModStub/Butler/BoneServantAI.cs
+++ b/JotunnModStub/Butler/BoneServantAI.cs
@@ -270,11 +270,7 @@ namespace RacesOfValheim
else if (Time.time >= m_nextFightScan)
{
m_nextFightScan = Time.time + FightScanInterval;
- // FindClosestEnemy takes its first match at ANY distance (it only compares against
- // maxDistance once it holds one), so with a deer anywhere in the loaded zones it never
- // returned null and vanilla kept the tick: the worker idled about instead of working.
- Character enemy = BaseAI.FindClosestEnemy(m_character, transform.position, FightRange);
- if (enemy != null && Vector3.Distance(enemy.transform.position, transform.position) <= FightRange)
+ if (BaseAI.FindClosestEnemy(m_character, transform.position, FightRange) != null)
{
m_fightUntil = Time.time + FightLinger;
}
@@ -363,22 +359,8 @@ namespace RacesOfValheim
Scan(anchor.Value);
ExpirePenalties();
- // 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 (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;
- }
- 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
@@ -390,7 +372,13 @@ 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;
- return job ?? PlanCollect() ?? PlanFuel() ?? PlanLoad();
+ 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;
}
///
@@ -642,10 +630,8 @@ 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) && !IsPenalised(target))
+ if (station != null && station.Alive && station.Operable && AcceptsAnything(station))
{
return new Job
{
diff --git a/JotunnModStub/Butler/ServantTableBehaviour.cs b/JotunnModStub/Butler/ServantTableBehaviour.cs
index 44346b0..e4964e6 100644
--- a/JotunnModStub/Butler/ServantTableBehaviour.cs
+++ b/JotunnModStub/Butler/ServantTableBehaviour.cs
@@ -143,8 +143,7 @@ namespace RacesOfValheim
string status = servant.Status;
if (string.IsNullOrEmpty(status)) status = ModText.Get("rov_hover_butler_waiting");
- // m_title is a $token, and a hover text goes to the HUD as it is: nothing localizes it later.
- return Localization.instance.Localize(m_title) + "\n" + status;
+ return m_title + "\n" + status;
}
///
diff --git a/JotunnModStub/ConfigSync.cs b/JotunnModStub/ConfigSync.cs
index fbf16b6..1ba4dce 100644
--- a/JotunnModStub/ConfigSync.cs
+++ b/JotunnModStub/ConfigSync.cs
@@ -31,8 +31,6 @@ 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",
@@ -44,13 +42,9 @@ namespace RacesOfValheim
private static readonly string[] LocalKeyParts =
{
"marker light", "tint", "colour", "color", "glow", "swarm scale", "log rounds", "debug",
- // The Aswid's seasick camera: motion makes some players ill, so a server cannot force it.
- "camera sway",
// Each player picks their own True Form: a player model mod (VRM and the like) breaks
// under the troll costume, so a server cannot be allowed to force the costume on.
"legacy true form",
- // The player's own pick of bat flight; the synced Bat Flight Rule can override it.
- "free bat flight",
};
public static void Apply(ConfigFile config)
diff --git a/JotunnModStub/DebugConfig.cs b/JotunnModStub/DebugConfig.cs
deleted file mode 100644
index ae763e0..0000000
--- a/JotunnModStub/DebugConfig.cs
+++ /dev/null
@@ -1,32 +0,0 @@
-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/DirectedFlight.cs b/JotunnModStub/DirectedFlight.cs
deleted file mode 100644
index f68a094..0000000
--- a/JotunnModStub/DirectedFlight.cs
+++ /dev/null
@@ -1,263 +0,0 @@
-using System.Reflection;
-using HarmonyLib;
-using UnityEngine;
-
-namespace RacesOfValheim
-{
- ///
- /// A form that flies on Character's native flying-creature movement (m_flying) and is steered
- /// by DirectedFlightPatch. The Skadi's drakes were the first; the Aswid's bat moved onto it from
- /// vanilla's debug-fly flag in the 2026 rebalance, so the two share one set of controls and
- /// differ only in the numbers each form hands back here.
- ///
- public interface IDirectedFlyer
- {
- /// False while the form is on the ground on purpose (a landed drake).
- bool IsFlying { get; }
-
- /// Time.time of the last powered or grounded moment; the hover window counts from it.
- float LastPoweredTime { get; set; }
-
- float TurnSpeed { get; }
- float GlideSpeed { get; }
- float BoostSpeed { get; }
- float SprintSpeed { get; }
- float ReverseSpeed { get; }
- float LiftoffSpeed { get; }
- float HoverSeconds { get; }
-
- /// Stamina per second for powered flight (forward or reverse). 0 is free.
- float PoweredStaminaPerSecond { get; }
-
- /// Stamina per second for the sprint, charged on top of the powered cost.
- float SprintStaminaPerSecond { get; }
-
- /// False forbids powered flight outright, so the form can only glide and sink.
- bool CanPower { get; }
- }
-
- public static class DirectedFlight
- {
- /// The local player's flying form, if any. Set and cleared by the form itself.
- public static IDirectedFlyer Active { get; private set; }
-
- public static void Register(IDirectedFlyer flyer) { Active = flyer; }
-
- public static void Unregister(IDirectedFlyer flyer)
- {
- if (Active == flyer) Active = null;
- }
-
- /// The active form, only while it is actually in the air.
- public static IDirectedFlyer Flying => Active != null && Active.IsFlying ? Active : null;
- }
-
- // The form flips the player into Character's native flying-creature movement (m_flying = true)
- // instead of the debug-fly noclip, which lets us feed it a full 3D move direction.
- // Character.UpdateFlying normally reads whatever m_moveDir the vanilla input pipeline last
- // wrote (ground-plane WASD relative to camera yaw only); this patch overwrites it every frame
- // with the camera's actual look direction (pitch included) so the player always glides toward
- // wherever the mouse is aiming, with W powering forward, Shift spending stamina for a burst of
- // speed, and S beating backwards away from whatever you are looking at.
- [HarmonyPatch(typeof(Character), "UpdateFlying")]
- public static class DirectedFlightPatch
- {
- // Tangent of the unpowered descent angle: 0.4 sinks at roughly 22 degrees below level.
- private const float DESCENT_SLOPE = 0.4f;
- // How much of the aim heading survives the climb out of water. Mostly up, with enough
- // forward in it that the player still chooses which shore they surface towards.
- private const float LIFTOFF_HEADING_BLEND = 0.35f;
- // How far the left stick has to be pushed before it counts as W or S.
- private const float StickThreshold = 0.5f;
-
- ///
- /// True while the local player is beating backwards this frame. Read by
- /// SkadiReverseFacingPatch, which keeps the body pointed at the camera while it happens.
- ///
- public static bool Reversing { get; private set; }
-
- // The September 2026 hotfix dropped the bool parameter from ZInput.GetJoyLeftStickY.
- // A direct call binds to whichever signature we compiled against and throws
- // MissingMethodException on the other, so resolve it at runtime and accept either.
- private static readonly MethodInfo JoyLeftStickYMethod =
- AccessTools.Method(typeof(ZInput), "GetJoyLeftStickY", new System.Type[0]) ??
- AccessTools.Method(typeof(ZInput), "GetJoyLeftStickY", new[] { typeof(bool) });
-
- private static float JoyLeftStickY()
- {
- if (JoyLeftStickYMethod == null) return 0f;
- return (float)JoyLeftStickYMethod.Invoke(null, JoyLeftStickYArgs);
- }
-
- // Old signature: pass smooth = true, which was its default.
- private static readonly object[] JoyLeftStickYArgs =
- JoyLeftStickYMethod != null && JoyLeftStickYMethod.GetParameters().Length == 1 ? new object[] { true } : null;
-
- public static void Prefix(Character __instance, float dt)
- {
- if (__instance != Player.m_localPlayer) return;
-
- IDirectedFlyer form = DirectedFlight.Flying;
- if (form == null)
- {
- Reversing = false;
- return;
- }
-
- var traverse = Traverse.Create(__instance);
- Vector3 lookDir = Player.m_localPlayer.GetLookDir();
- bool input = RaceInput.Allowed;
- // The pad's half of W/S: the left stick, read with vanilla's own sign -
- // PlayerController.FixedUpdate takes forward as the NEGATED GetJoyLeftStickY.
- // Flight only knows powered forward, reverse or neither, so the stick is a
- // threshold, not a throttle. Steering stays on the camera, i.e. the right stick.
- float stick = -JoyLeftStickY();
- // The keyboard side reads vanilla's own Forward/Backward/Run actions, so a key the
- // player rebound in the settings flies too, not just W, S and Shift.
- bool forward = input && (ZInput.GetButton("Forward") || stick > StickThreshold);
- // Forward wins a W+S mash rather than the two cancelling into a dead hover.
- bool backward = input && !forward && (ZInput.GetButton("Backward") || stick < -StickThreshold);
- // Sprint on a pad is vanilla's run button, wherever the chosen layout puts it.
- bool sprintKey = input && (ZInput.GetButton("Run") || ZInput.GetButton("JoyRun"));
- bool onGround = __instance.IsOnGround();
- // IsSwimming is the exact test UpdateMotion uses to hand the frame to UpdateSwimming
- // instead of UpdateFlying, so it is also the one condition DirectedFlightWaterPatch has
- // to take back. Its half-second tail past leaving the water is welcome here - it
- // keeps the climb going just long enough to clear the surface properly.
- bool inWater = __instance.IsSwimming();
-
- // Powered flight is paid for up front, per frame. A form that cannot pay - out of
- // stamina, or barred from powering at all - falls through to the glide below rather
- // than out of the sky.
- if ((forward || backward) && !(form.CanPower && TrySpendStamina(form.PoweredStaminaPerSecond, dt)))
- {
- forward = false;
- backward = false;
- }
-
- Reversing = backward;
-
- // m_run only picks between the two fly speeds. Every mode now has its own speed, so
- // leave it off and drive all of them through m_flySlowSpeed.
- traverse.Field("m_run").SetValue(false);
-
- // UpdateFlying rotates the body toward m_moveDir on its own, but at m_flyTurnSpeed,
- // which sits at Character's 12 deg/s default because the Player prefab was never set
- // up as a flying creature - a 90 degree turn would take over seven seconds, so the
- // model reads as not turning at all. Give it a speed that suits a flying form.
- traverse.Field("m_flyTurnSpeed").SetValue(form.TurnSpeed);
-
- // Powered flight, ground contact and clawing out of water all refresh the hover
- // window, so none of them can be followed by an immediate sink.
- if (forward || backward || onGround || inWater) form.LastPoweredTime = Time.time;
-
- Vector3 moveDir = lookDir;
- float speed;
-
- if (inWater)
- {
- // Wet wings still beat. Water used to be a trap: UpdateMotion hands a swimming
- // character to UpdateSwimming before it ever looks at m_flying, so a form that
- // touched the sea was stuck paddling with the flight controls doing nothing.
- // DirectedFlightWaterPatch gives the frame back to flight, and this branch spends
- // it climbing regardless of where the camera points, so the surface is always
- // something you break out of rather than something you sit in. Free on purpose:
- // a form that could not pay to leave the water would drown in it.
- moveDir = (Vector3.up + FlatHeading(__instance, lookDir) * LIFTOFF_HEADING_BLEND).normalized;
- speed = form.LiftoffSpeed;
- }
- else if (backward)
- {
- // Straight reverse thrust along the aim, pitch included: look down and beat back
- // and you rise away from what you are looking at, which is the whole point of
- // having a reverse - you can retreat without taking your eyes (or your breath
- // attack, which fires along the same vector) off the target.
- moveDir = -lookDir;
- speed = form.ReverseSpeed;
- }
- else if (forward)
- {
- speed = form.BoostSpeed;
- if (sprintKey && TrySpendStamina(form.SprintStaminaPerSecond, dt)) speed = form.SprintSpeed;
- }
- else if (onGround || Time.time - form.LastPoweredTime < form.HoverSeconds)
- {
- // Holding station: on the ground this keeps a touchdown from sliding the player
- // forward forever, and in the air it gives the beats of level flight before the
- // form starts to sink. m_moveDir stays full length so the body still turns to
- // face the camera, and zeroing the speed (rather than the rigidbody velocity)
- // avoids fighting the AddForce UpdateFlying queues, which caused visible jitter.
- speed = 0f;
- }
- else
- {
- // Unpowered flight is a glide, not a hover with a joystick: drift along the
- // heading the camera faces while losing height, so aiming at the sky without
- // holding W no longer climbs.
- moveDir = (FlatHeading(__instance, lookDir) + Vector3.down * DESCENT_SLOPE).normalized;
- speed = form.GlideSpeed;
- }
-
- traverse.Field("m_moveDir").SetValue(moveDir);
- traverse.Field("m_flySlowSpeed").SetValue(speed);
- }
-
- /// Aim flattened onto the ground plane, falling back to the body's own facing
- /// when the player is looking straight up or down.
- private static Vector3 FlatHeading(Character character, Vector3 lookDir)
- {
- Vector3 heading = new Vector3(lookDir.x, 0f, lookDir.z);
- if (heading.sqrMagnitude < 0.0001f)
- {
- heading = character.transform.forward;
- heading.y = 0f;
- }
- return heading.normalized;
- }
-
- ///
- /// Charges this frame of a per-second cost. Returns false when the player cannot pay.
- /// A rate of zero is always paid, so a free mode costs nothing and never fails.
- ///
- private static bool TrySpendStamina(float perSecond, float dt)
- {
- if (perSecond <= 0f) return true;
-
- Player player = Player.m_localPlayer;
- if (player == null) return false;
-
- float cost = perSecond * dt;
- if (!player.HaveStamina(cost)) return false;
-
- player.UseStamina(cost);
- return true;
- }
- }
-
- ///
- /// Character.UpdateMotion asks IsSwimming before it asks m_flying, so a flying form that
- /// touched water was handed to UpdateSwimming every frame: the flight patch above never ran,
- /// the form paddled on the surface, and there was no way back into the air short of finding
- /// land. Hand those frames back to UpdateFlying, which is the only motion path the two methods
- /// contend over: nothing else calls either of them, and everything that merely asks
- /// IsSwimming - the Wet status, the animator, stamina - is left alone.
- ///
- [HarmonyPatch(typeof(Character), "UpdateSwimming")]
- public static class DirectedFlightWaterPatch
- {
- private static readonly MethodInfo UpdateFlyingMethod = AccessTools.Method(typeof(Character), "UpdateFlying");
-
- public static bool Prefix(Character __instance, float dt)
- {
- if (__instance != Player.m_localPlayer) return true;
- if (DirectedFlight.Flying == null) return true;
-
- // Fail open: if a game update ever renames the method, swim normally rather than
- // freezing the player in place with no motion update at all.
- if (UpdateFlyingMethod == null) return true;
-
- UpdateFlyingMethod.Invoke(__instance, new object[] { dt });
- return false;
- }
- }
-}
diff --git a/JotunnModStub/Draugh/DraughFoodPatches.cs b/JotunnModStub/Draugh/DraughFoodPatches.cs
index a527830..ea56d5c 100644
--- a/JotunnModStub/Draugh/DraughFoodPatches.cs
+++ b/JotunnModStub/Draugh/DraughFoodPatches.cs
@@ -24,16 +24,11 @@ namespace RacesOfValheim
{ "HareMeat", "CookedHareMeat" },
{ "ChickenMeat", "CookedChickenMeat" },
{ "BugMeat", "CookedBugMeat" },
- { "VoltureMeat", "CookedVoltureMeat" },
+ { "VoltureMeat", "RoastedVoltureMeat" },
{ "GreydwarfEye", "DeerStew" },
{ "Entrails", "Sausages" },
{ "Bloodbag", "BloodPudding" },
{ "MooseMeat", "CookedMooseMeat" },
- // Bjorn, the Valheim 1.0 bear.
- { "BjornMeat", "CookedBjornMeat" },
- // Ashlands.
- { "AsksvinMeat", "CookedAsksvinMeat" },
- { "BoneMawSerpentMeat", "CookedBoneMawSerpentMeat" },
// Raw blubber keeps its own name and icon (EdibleUncooked_ copies them from the raw
// item) and gives the stats of Seal Meat Soup.
{ "SealBlubber", "SealSoup" }
diff --git a/JotunnModStub/Dvergar/DvergarBanco.cs b/JotunnModStub/Dvergar/DvergarBanco.cs
index 8f24220..a912a2d 100644
--- a/JotunnModStub/Dvergar/DvergarBanco.cs
+++ b/JotunnModStub/Dvergar/DvergarBanco.cs
@@ -76,12 +76,6 @@ namespace RacesOfValheim
private const float PileHeight = 1.05f;
private const float PileSize = 0.45f;
- // The dressing, in the same unscaled table space as the pile. The pile owns the centre, so the
- // tankard stands just clear of it, on the near side.
- private static readonly Color BankWoodTint = new Color(0.62f, 0.55f, 0.5f, 1f);
- private static readonly Vector3 TankardSpot = new Vector3(0.45f, PileHeight, -0.25f);
- private const float TankardSize = 0.38f;
-
public class Troop
{
public string Id;
@@ -282,12 +276,6 @@ namespace RacesOfValheim
prefab.transform.localScale = Vector3.one * TableScale;
- // A counting table, not a map table: darker wood and a dvergr tankard beside the coin.
- // Tinted BEFORE the tankard goes on, or it would be darkened too.
- PieceLook.Tint(prefab.transform, BankWoodTint);
- ModelBorrow.Attach(prefab.transform, "BankTankard", "Tankard_dvergr",
- TankardSpot, Quaternion.identity, TankardSize, "Dvergar", activeOnly: true);
-
DvergarBancoBehaviour bank = prefab.AddComponent();
foreach (Switch existing in prefab.GetComponentsInChildren(true))
diff --git a/JotunnModStub/Dvergar/DvergarCheapBuilding.cs b/JotunnModStub/Dvergar/DvergarCheapBuilding.cs
deleted file mode 100644
index 9fa25ec..0000000
--- a/JotunnModStub/Dvergar/DvergarCheapBuilding.cs
+++ /dev/null
@@ -1,275 +0,0 @@
-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