RacesOfValheim/JotunnModStub/RaceCaveBuilding.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

212 lines
9.3 KiB
C#

using System.Collections.Generic;
using HarmonyLib;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// "A troll cave is a house, if you are the right sort of thing."
///
/// Skadi and Trol may build inside ANY troll cave in the world.
///
/// THE ACTUAL RESTRICTION, found only after the game was asked instead of guessed at: a troll
/// cave counts as a DUNGEON, and Valheim refuses any piece whose Piece.m_allowedInDungeons is
/// false while the player is in one - "Can't build in a dungeon". That is a per-PIECE flag, not a
/// per-location one.
///
/// Two earlier versions of this file cleared Location.m_noBuild instead. That is a real
/// restriction and it is still cleared below, but it was never the one refusing these
/// placements, which is why lifting it changed nothing twice in a row. The lesson is in the log
/// line this class now prints: Player.m_placementStatus names the exact reason, and reading it
/// would have answered the question on the first report rather than the third.
///
/// The flag is flipped only while an eligible player is actually standing in a troll cave, and
/// put back when they leave, so this does not quietly become "build anywhere in any crypt". It
/// touches only the pieces on the build tables the player is carrying, and placement checks are
/// client-side, so nobody else's game is affected.
/// </summary>
public class RaceCaveBuilding : MonoBehaviour
{
/// <summary>Matches both troll cave locations this build has: TrollCave and TrollCave02.</summary>
private const string CaveNameFragment = "TrollCave";
/// <summary>Slack on the location's own radius, since the inside of a cave is not a neat sphere.</summary>
private const float RadiusSlack = 12f;
private const float CheckInterval = 0.25f;
private float nextCheck;
private bool allowing;
private readonly List<Piece> flipped = new List<Piece>();
private string lastReport;
private string lastHow = "not checked yet";
private void Update()
{
if (Time.time < nextCheck) return;
nextCheck = Time.time + CheckInterval;
Player player = Player.m_localPlayer;
if (player == null) return;
if (!SkadiRace.IsLocalSkadi() && !TrolRace.IsTrol())
{
Restore();
return;
}
bool inCave = IsInTrollCave(player, out string how);
lastHow = how;
if (inCave && !allowing) Allow(player);
else if (!inCave && allowing) Restore();
ReportWhyIfRefused(player);
}
/// <summary>
/// Two ways of asking, because the two cases are genuinely different.
///
/// FIRST, Location.GetLocation(point, checkDungeons: true). That flag exists for exactly this
/// question - "which location owns this point, counting dungeon interiors" - and it is the
/// only one of the two that can answer it when the interior is not where the mouth is. The
/// previous version of this file dropped it in favour of a distance sweep, and that is why
/// the log said "in troll cave=False" while the player was standing in one: a distance test
/// against the mouth cannot find a player who is inside.
///
/// SECOND, the sweep, kept as the case the first one is weakest at: standing at the mouth,
/// outside, where there is no interior to own the point.
/// </summary>
private static bool IsInTrollCave(Player player, out string how)
{
Vector3 position = player.transform.position;
Location owning = Location.GetLocation(position, true);
if (owning != null && IsTrollCave(owning))
{
LiftOutrightBan(owning);
how = $"GetLocation -> {owning.gameObject.name}";
return true;
}
foreach (Location location in Object.FindObjectsByType<Location>(FindObjectsSortMode.None))
{
if (location == null || !IsTrollCave(location)) continue;
if (Vector3.Distance(position, location.transform.position) > location.GetMaxRadius() + RadiusSlack) continue;
LiftOutrightBan(location);
how = $"nearby -> {location.gameObject.name}";
return true;
}
how = owning != null ? $"owned by '{owning.gameObject.name}', not a cave" : "no location owns this point";
return false;
}
private static bool IsTrollCave(Location location)
{
return location.gameObject.name.IndexOf(CaveNameFragment, System.StringComparison.OrdinalIgnoreCase) >= 0;
}
/// <summary>
/// Cheap and harmless while we are here: a location may also forbid building outright, and
/// that ban would beat everything else. It is NOT what refuses a piece in a troll cave - that
/// was two wrong guesses ago - but a cave that did set it would be unbuildable for a second,
/// separate reason.
/// </summary>
private static void LiftOutrightBan(Location location)
{
if (!location.m_noBuild) return;
location.m_noBuild = false;
Jotunn.Logger.LogInfo($"[Races] '{location.gameObject.name}' also forbade building outright; cleared that too.");
}
/// <summary>
/// Marks every piece on the build tables the player is carrying as dungeon-legal, remembering
/// which ones were not so they can be put back exactly as they were.
/// </summary>
private void Allow(Player player)
{
Inventory inventory = player.GetInventory();
if (inventory == null) return;
foreach (ItemDrop.ItemData item in inventory.GetAllItems())
{
PieceTable table = item?.m_shared?.m_buildPieces;
if (table == null || table.m_pieces == null) continue;
foreach (GameObject entry in table.m_pieces)
{
Piece piece = entry != null ? entry.GetComponent<Piece>() : null;
if (piece == null || piece.m_allowedInDungeons) continue;
piece.m_allowedInDungeons = true;
flipped.Add(piece);
}
}
allowing = true;
Jotunn.Logger.LogInfo($"[Races] In a troll cave: {flipped.Count} pieces temporarily allowed in dungeons.");
player.Message(MessageHud.MessageType.Center, "This cave will hold what you build in it.");
}
/// <summary>
/// Puts the flags back. Without this the permission would follow the player into every crypt
/// and sunken chamber in the world, which is not what was asked for.
/// </summary>
private void Restore()
{
if (!allowing) return;
foreach (Piece piece in flipped)
{
if (piece != null) piece.m_allowedInDungeons = false;
}
Jotunn.Logger.LogInfo($"[Races] Left the troll cave: {flipped.Count} pieces set back to dungeon-forbidden.");
flipped.Clear();
allowing = false;
}
private void OnDestroy()
{
Restore();
}
/// <summary>
/// Says, in the log, exactly why the game is refusing a placement right now. m_placementStatus
/// is private and Player cannot be inspected offline at all, so it is read with Traverse and
/// printed by name - the enum's own ToString does the translating, so this cannot fall out of
/// step with the game's own list of reasons. Only speaks when the answer changes.
/// </summary>
private void ReportWhyIfRefused(Player player)
{
object status = Traverse.Create(player).Field("m_placementStatus").GetValue();
if (status == null) return;
string statusName = status.ToString();
if (statusName == "Valid") { lastReport = null; return; }
string report = statusName + "|" + lastHow;
if (report == lastReport) return;
lastReport = report;
// The player's own position and the distance to the nearest troll cave MOUTH are here for
// one reason: if a refusal ever survives with "in troll cave=False", these two numbers say
// whether the interior sits near its mouth or has been relocated somewhere else entirely -
// which is the difference between a tolerance to widen and a wrong idea about the world.
Vector3 position = player.transform.position;
string nearest = "<none in this world>";
if (ZoneSystem.instance != null
&& ZoneSystem.instance.FindClosestLocation("TrollCave02", position, out ZoneSystem.LocationInstance closest))
{
nearest = $"{Vector3.Distance(position, closest.m_position):0} m away at {closest.m_position}";
}
Jotunn.Logger.LogInfo($"[Races] Placement refused: {statusName} " +
$"(in troll cave={allowing}, pieces flipped={flipped.Count}). " +
$"Detection said: {lastHow}. Player at {position}; nearest TrollCave02 mouth {nearest}.");
}
}
}