RacesOfValheim/JotunnModStub/PlayerVisualHider.cs
kanym 5dff5e1b84 fix(forms): hair comes back after a form with Valkyr
Valkyr sets its hair's forceRenderingOff on every visual update. The hider
read that flag as "not hidden yet", recorded the hair a second time with
enabled already false, and the revert left it off. Track hidden renderers
in a set instead of trusting the flag.
2026-10-18 00:09:14 +02:00

184 lines
7.7 KiB
C#

using System.Collections.Generic;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// Hides and restores a player's "Visual" child without ever deactivating it.
///
/// The player's Animator sits on that same GameObject, and Unity rebinds an Animator whenever it
/// is re-enabled: the controller restarts from its entry state, which for the player is the same
/// get-up clip that plays when you spawn into a world. Deactivating the Visual to hide the human
/// body during a monster form is therefore why reverting looked exactly like respawning.
///
/// Hiding is done with Renderer.forceRenderingOff on top of Renderer.enabled. Nothing in the game
/// touches forceRenderingOff on a character (only EnvZone uses it, on its own props), so the body
/// stays invisible even if some other code re-enables the renderers behind our back.
/// </summary>
public class PlayerVisualHider : MonoBehaviour
{
// Tracing for the hide/show paths. Off by default; flip to true if a transformed body
// ever shows up again and the log should name which path did it.
public static bool Diagnostics = false;
// VisEquipment rebuilds item visuals whenever gear changes and they come back visible, so
// the hidden set has to be re-swept rather than applied once.
private const float RescanInterval = 0.25f;
private const float LogInterval = 2f;
private struct HiddenRenderer
{
public Renderer Renderer;
public bool WasEnabled;
}
private readonly List<HiddenRenderer> m_hidden = new List<HiddenRenderer>();
// What we hid, kept apart from forceRenderingOff. Other mods write that flag too: Valkyr
// sets its hair's forceRenderingOff on every visual update, so the flag alone made the
// rescan record the hair a second time, already disabled, and the revert left it off.
private readonly HashSet<Renderer> m_tracked = new HashSet<Renderer>();
private float m_nextRescan;
private float m_nextLog;
private string m_context = "";
/// <param name="keepScale">Leave the Visual's scale alone. For a body that is meant to be
/// sized while hidden: the Trol's True Form troll stands as tall as the Visual does, and
/// resetting it here every frame fought Trol_PlayerUpdate_Patch growing it back - the troll
/// pulsed several times a second and never reached full size.</param>
public static void Hide(Transform playerVisual, string context, bool keepScale = false)
{
if (playerVisual == null) return;
// Undo the two older ways this body could have been hidden, so a form entered right
// after one of those code paths still starts from a sane state.
if (!playerVisual.gameObject.activeSelf) playerVisual.gameObject.SetActive(true);
if (!keepScale && playerVisual.localScale != Vector3.one) playerVisual.localScale = Vector3.one;
// Belt and braces: if anything else ever does deactivate the Visual, at least keep the
// animator from snapping back to its spawn state.
Animator anim = playerVisual.GetComponent<Animator>();
if (anim != null) anim.keepAnimatorStateOnDisable = true;
PlayerVisualHider hider = playerVisual.GetComponent<PlayerVisualHider>();
if (hider == null) hider = playerVisual.gameObject.AddComponent<PlayerVisualHider>();
bool alreadyHiding = hider.enabled;
hider.m_context = context;
hider.enabled = true;
int added = hider.HideRenderers();
if (Diagnostics && (!alreadyHiding || added > 0))
{
Jotunn.Logger.LogInfo(
$"[VisualHider] hide '{context}' newlyHidden={added} tracked={hider.m_hidden.Count} " +
$"visualActive={playerVisual.gameObject.activeInHierarchy}");
}
}
public static void Show(Transform playerVisual, string context, bool keepScale = false)
{
if (playerVisual == null) return;
if (!playerVisual.gameObject.activeSelf) playerVisual.gameObject.SetActive(true);
if (!keepScale && playerVisual.localScale != Vector3.one) playerVisual.localScale = Vector3.one;
PlayerVisualHider hider = playerVisual.GetComponent<PlayerVisualHider>();
if (hider == null || !hider.enabled) return;
int restored = hider.RestoreRenderers();
if (Diagnostics)
{
Jotunn.Logger.LogInfo(
$"[VisualHider] show '{context}' restored={restored} (hidden by '{hider.m_context}')");
}
}
public static bool IsHidden(Transform playerVisual)
{
if (playerVisual == null) return false;
PlayerVisualHider hider = playerVisual.GetComponent<PlayerVisualHider>();
return hider != null && hider.enabled;
}
/// <summary>Hides every renderer not already hidden by us. Returns how many were added.</summary>
private int HideRenderers()
{
int added = 0;
// Equipment is parented to the body's bones, so this covers weapons, armour, hair and
// the cape along with the body mesh itself.
foreach (Renderer r in GetComponentsInChildren<Renderer>(true))
{
if (r == null) continue;
if (m_tracked.Contains(r))
{
// Already ours: re-assert in case another mod cleared the flag.
r.forceRenderingOff = true;
continue;
}
// Hidden by someone else (Valkyr hides the vanilla body and hair this way): leave
// it to them, or the revert would show it.
if (r.forceRenderingOff) continue;
m_tracked.Add(r);
m_hidden.Add(new HiddenRenderer { Renderer = r, WasEnabled = r.enabled });
r.enabled = false;
r.forceRenderingOff = true;
added++;
}
m_nextRescan = Time.time + RescanInterval;
return added;
}
private int RestoreRenderers()
{
int restored = 0;
foreach (HiddenRenderer h in m_hidden)
{
if (h.Renderer == null) continue;
h.Renderer.forceRenderingOff = false;
h.Renderer.enabled = h.WasEnabled;
restored++;
}
m_hidden.Clear();
m_tracked.Clear();
enabled = false;
return restored;
}
private void LateUpdate()
{
if (Time.time < m_nextRescan) return;
int added = HideRenderers();
if (!Diagnostics || Time.time < m_nextLog) return;
// If anything re-enables a renderer we own, forceRenderingOff still keeps it invisible -
// but we want to know who, so report it rather than silently papering over it.
int reEnabled = 0;
string firstName = "";
foreach (HiddenRenderer h in m_hidden)
{
if (h.Renderer == null || !h.Renderer.enabled) continue;
if (reEnabled == 0) firstName = h.Renderer.name;
reEnabled++;
}
if (added == 0 && reEnabled == 0) return;
m_nextLog = Time.time + LogInterval;
Jotunn.Logger.LogInfo(
$"[VisualHider] sweep '{m_context}' newlyHidden={added} reEnabledBehindUs={reEnabled} " +
$"first='{firstName}' tracked={m_hidden.Count}");
}
}
}