RacesOfValheim/JotunnModStub/Dvergar/DvergarBotteBehaviour.cs
Ferdinando 5c5b8c34d2 feat(races): Skadi hollow chain, plus the pending Dvergar and Fenrir ones
Three per-race item chains had accumulated uncommitted. They land
together because FactionMerchantCatalog.cs carries hunks from all
three and cannot be split without interactive staging.

Skadi (new this session):
- SkadiNokkel - "Skadis Nokkel", a StaffSkeleton clone recoloured to
  ice, stripped of its eitr and health costs and of the skeleton
  summon, opening an ice-blue portal to a troll cave the player
  claims as their own. Crafted at the forge after Moder from a
  1500-coin Greater Frost Heart, a DragonTear and a TrophySkeleton.
- SkadiFrostHeart - the bought leg of that recipe, sold by the
  Cultist bench.
- SkadiHollow / SkadiHollowPortal - claims one existing TrollCave02
  in the Black Forest, half a world radius out and south of the
  equator, and opens a linked local portal pair to it.
- RaceCaveBuilding - Skadi and Trol may build inside any troll cave.

Two facts worth keeping, both paid for the hard way:
- a troll cave counts as a DUNGEON, so the flag that refuses a piece
  there is the per-piece Piece.m_allowedInDungeons, not the
  per-location Location.m_noBuild. Player.m_placementStatus names the
  exact refusal reason and is now logged.
- Object.DestroyImmediate is forbidden inside an animation event
  callback, and a staff cast runs in one - it fails silently there.

Also carried in, from earlier sessions and unverified in game:
- Dvergar contract bank and barrel (DvergarBanco*, DvergarBotte*)
- Fenrir Ulvsblod trough (FenrirMangiatoia*)
- the Wolf -> Ulv merchant bench move, so tameable wolves stop
  answering the E key with a shop window

Status: compiles clean with no new warnings. The Skadi chain has NOT
been confirmed working in game - the most recent fix to the troll
cave detection is still untested.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-08 14:58:43 +02:00

267 lines
10 KiB
C#

using System.Collections.Generic;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// The barrel's logic: one brew at a time, one dose per mercenary, poured by hand.
///
/// Two gestures on one key, and the split is the same one the bank uses:
/// - a potion USED on the barrel fills it (and tops it up, if it is the same brew);
/// - a bare E pours a round - and fills it from your pack first if it is empty, so the common
/// case is one click rather than the inventory dance. The Fenrir trough does the same thing
/// with meat, for the same reason.
///
/// Serving is MANUAL and never automatic. An automatic barrel would drink itself dry keeping a
/// buff up on a crew that is standing still doing nothing, and the whole point of a barrel over a
/// flask was that the buff is something you spend on purpose before walking out.
///
/// HONEST LIMIT, in the shape this project writes them: the round is poured by the client that
/// clicked. It claims ownership of each mercenary before adding the effect, so the effect is
/// simulated by someone who has it - but a mercenary that is not loaded on that client cannot be
/// served at all, and in multiplayer the dose count can be spent twice if two players click in the
/// same instant. Neither is worth a handshake for a barrel of mead.
/// </summary>
public class DvergarBotteBehaviour : MonoBehaviour
{
public Switch m_switch;
private const string KeyBrew = "RoV_dvergarBotteBrew";
private const string KeyDoses = "RoV_dvergarBotteDoses";
private ZNetView m_nview;
private void Awake()
{
m_nview = GetComponent<ZNetView>();
if (m_nview == null || m_nview.GetZDO() == null) return;
if (m_switch != null)
{
m_switch.m_onUse = OnUse;
m_switch.m_onHover = Hover;
}
m_nview.Register<string, int>("RoV_DvergarBotteFill", RPC_Fill);
m_nview.Register<int>("RoV_DvergarBotteSpend", RPC_Spend);
}
// ---------------------------------------------------------------- interaction
private bool OnUse(Switch caller, Humanoid user, ItemDrop.ItemData item)
{
Player player = user as Player;
if (player == null) return false;
Inventory inventory = player.GetInventory();
if (inventory == null) return false;
// A drink handed to the barrel always fills it, whatever is already in there.
if (item != null)
{
string prefabName = item.m_dropPrefab != null ? item.m_dropPrefab.name : null;
if (!DvergarBotte.IsBrew(prefabName))
{
player.Message(MessageHud.MessageType.Center, "$msg_wontwork");
return false;
}
return Fill(player, inventory, item, prefabName);
}
// Bare hands: pour a round if there is one, otherwise go looking for something to pour.
if (GetDoses() > 0) return Serve(player);
ItemDrop.ItemData found = FindAnyBrew(inventory);
if (found == null)
{
player.Message(MessageHud.MessageType.Center, "It is empty, and so are you.");
return false;
}
return Fill(player, inventory, found, found.m_dropPrefab.name);
}
private ItemDrop.ItemData FindAnyBrew(Inventory inventory)
{
foreach (ItemDrop.ItemData candidate in inventory.GetAllItems())
{
if (candidate == null || candidate.m_dropPrefab == null) continue;
if (DvergarBotte.IsBrew(candidate.m_dropPrefab.name)) return candidate;
}
return null;
}
// ---------------------------------------------------------------- filling
/// <summary>
/// Pours a stack in. One brew at a time: a barrel holding two different meads would have to
/// decide which one a mercenary gets, and there is no answer to that which is not arbitrary.
/// </summary>
private bool Fill(Player player, Inventory inventory, ItemDrop.ItemData item, string prefabName)
{
string current = GetBrew();
if (!string.IsNullOrEmpty(current) && current != prefabName && GetDoses() > 0)
{
player.Message(MessageHud.MessageType.Center,
$"There is still {DvergarBotte.BrewDisplayName(current)} in it.");
return false;
}
int room = DvergarBotte.MaxDoses - GetDoses();
if (room <= 0)
{
player.Message(MessageHud.MessageType.Center, "$msg_itsfull");
return false;
}
int poured = Mathf.Min(room, Mathf.Max(1, item.m_stack));
inventory.RemoveItem(item, poured);
m_nview.InvokeRPC("RoV_DvergarBotteFill", prefabName, poured);
player.Message(MessageHud.MessageType.Center,
$"$msg_added {DvergarBotte.BrewDisplayName(prefabName)} x{poured}");
return true;
}
private void RPC_Fill(long sender, string prefabName, int count)
{
if (!m_nview.IsOwner()) return;
if (count < 1) return;
// A barrel that has been drunk dry forgets what it held, so the next brew can be anything.
string current = GetBrew();
if (string.IsNullOrEmpty(current) || GetDoses() <= 0) m_nview.GetZDO().Set(KeyBrew, prefabName);
else if (current != prefabName) return;
SetDoses(GetDoses() + count);
}
// ---------------------------------------------------------------- serving
/// <summary>
/// One round: every mercenary in reach gets a cup, and every cup is a dose. Whoever is out of
/// range or already dead simply is not served - there is no queue and no leftovers.
/// </summary>
private bool Serve(Player player)
{
string brew = GetBrew();
StatusEffect effect = DvergarBotte.BrewEffect(brew);
if (effect == null)
{
player.Message(MessageHud.MessageType.Center, "Whatever is in it does nothing to anyone.");
return false;
}
List<RaisedThrall> drinkers = InRange();
if (drinkers.Count == 0)
{
player.Message(MessageHud.MessageType.Center, "Nobody is at the barrel.");
return false;
}
int doses = GetDoses();
int served = 0;
foreach (RaisedThrall thrall in drinkers)
{
if (served >= doses) break;
if (Pour(thrall, effect)) served++;
}
if (served == 0)
{
player.Message(MessageHud.MessageType.Center, "Not a drop went down.");
return false;
}
m_nview.InvokeRPC("RoV_DvergarBotteSpend", served);
string what = DvergarBotte.BrewDisplayName(brew);
player.Message(MessageHud.MessageType.Center, served < drinkers.Count
? $"{served} drink {what}. The barrel runs dry."
: $"{served} drink {what}.");
return true;
}
/// <summary>
/// Hands one creature the drink. The effect object is passed the same way vanilla passes it
/// when a player swallows a potion - Humanoid.UseItem does exactly this - so whatever SEMan
/// does with the shared asset internally, it is what the game already does to itself.
/// </summary>
private static bool Pour(RaisedThrall thrall, StatusEffect effect)
{
Character character = thrall != null ? thrall.GetComponent<Character>() : null;
if (character == null || character.IsDead()) return false;
// Claimed so that the client pouring is the one simulating the effect. Without this the
// drink would tick on a machine that does not own the creature, which for a heal-over-time
// means it quietly does nothing.
ZNetView nview = character.GetComponent<ZNetView>();
if (nview != null && nview.IsValid()) nview.ClaimOwnership();
character.GetSEMan().AddStatusEffect(effect, true);
return true;
}
private List<RaisedThrall> InRange()
{
List<RaisedThrall> near = new List<RaisedThrall>();
foreach (Character character in Character.GetAllCharacters())
{
if (character == null || character.IsDead()) continue;
RaisedThrall thrall = character.GetComponent<RaisedThrall>();
if (thrall == null) continue;
if (Vector3.SqrMagnitude(character.transform.position - transform.position) >
DvergarBotte.ServeRange * DvergarBotte.ServeRange) continue;
near.Add(thrall);
}
return near;
}
private void RPC_Spend(long sender, int count)
{
if (!m_nview.IsOwner()) return;
SetDoses(GetDoses() - Mathf.Max(0, count));
}
// ---------------------------------------------------------------- state and display
private string GetBrew() =>
m_nview != null && m_nview.IsValid() ? m_nview.GetZDO().GetString(KeyBrew, "") : "";
private int GetDoses() =>
m_nview != null && m_nview.IsValid() ? m_nview.GetZDO().GetInt(KeyDoses, 0) : 0;
private void SetDoses(int value)
{
if (m_nview == null || !m_nview.IsValid()) return;
m_nview.GetZDO().Set(KeyDoses, Mathf.Clamp(value, 0, DvergarBotte.MaxDoses));
}
private string Hover()
{
int doses = GetDoses();
string brew = GetBrew();
string body;
if (doses <= 0 || string.IsNullOrEmpty(brew))
{
body = "empty\n[<color=yellow><b>$KEY_Use</b></color>] Pour a brew in";
}
else
{
int waiting = InRange().Count;
body = $"{DvergarBotte.BrewDisplayName(brew)} {doses}/{DvergarBotte.MaxDoses}" +
$"\n{waiting} at the barrel" +
$"\n[<color=yellow><b>$KEY_Use</b></color>] Pour a round";
}
return Localization.instance.Localize($"{DvergarBotte.PieceDisplayName} ({body})");
}
}
}