True Form now hides the Trol's body and puts the vanilla forest troll's model in its place, on the owner's client and on every other player's. The costume stands as tall as the old True Form did: it follows the Visual scale Trol_PlayerUpdate_Patch already grows and publishes, so the grow-in, the shrink back and the size others see come for free. It takes the Trol skin colour from Trol - Appearance. Weapons are out while it is up. Left click is the troll's punch, right click its ground slam, and with a log in hand they become its two log swings, which wear the log down per hit as a club swing did. Throw Rock plays the troll's throw. The attacks, their triggers and reach are read off the troll's own weapons at runtime, and each hit lands on the troll's OnAttackTrigger event rather than a fixed delay. Damage is a share of the troll's own (Troll Attack Damage, 0.5), scaled by the Clubs skill like a club and hit as Clubs, so the True Form and tier melee bonuses still add on top. Other players see the troll from the existing True Form ZDO flag, with attacks replayed from a new trigger key. New options in Trol - True Form: Troll Model (on/off), Troll Model Size, Troll Attack Damage.
407 lines
19 KiB
C#
407 lines
19 KiB
C#
using System.Collections.Generic;
|
|
using HarmonyLib;
|
|
using Jotunn.Managers;
|
|
using UnityEngine;
|
|
|
|
namespace RacesOfValheim
|
|
{
|
|
/// <summary>
|
|
/// True Form wears Valheim's own forest troll instead of a scaled-up player.
|
|
///
|
|
/// Built the way the Fenrir forms are, not the way the Sverm's Ravager is: the troll's Visual is
|
|
/// instantiated live under the player, CharacterAnimEvent and AnimationEffect included. That
|
|
/// costs a FormFootsteps.Detach, and in return the troll's own clips play their own sounds and,
|
|
/// more to the point here, fire OnAttackTrigger at the exact frame a fist lands. That event
|
|
/// resolves to the PLAYER (the first Character up the hierarchy), and
|
|
/// Trol_TrueFormAttackTrigger_Patch catches it there - so every hit lands on the troll's own
|
|
/// timing rather than on a delay somebody guessed.
|
|
///
|
|
/// SIZE. The costume does not have a size of its own. Every frame it is sized to stand as tall as
|
|
/// the player's hidden Visual would - the same Visual Trol_PlayerUpdate_Patch already grows from
|
|
/// 1.2-1.3 to the True Form scale, on the owner's client and every onlooker's. So the grow-in, the
|
|
/// shrink back and the size other players see all come from code that already worked, and
|
|
/// "Scale" / "Scale (Tier 7+)" keep meaning what they meant: how many player heights tall.
|
|
///
|
|
/// ATTACKS. Read once off the troll's own weapons (Humanoid.m_defaultItems and friends): the
|
|
/// trigger each one plays, its damage, its reach. Nothing is cloned or equipped. The damage is a
|
|
/// share of the troll's (Troll Attack Damage), scaled by the player's Clubs skill exactly the way
|
|
/// a weapon is, and hit as Clubs - so Trol_Character_ApplyDamage_Patch adds the True Form and tier
|
|
/// bonuses on top just as it did for a club in hand.
|
|
/// </summary>
|
|
public static class TrolTrueFormModel
|
|
{
|
|
public const string Creature = "Troll";
|
|
public const string LocalModelName = "TrolTrueFormModel";
|
|
public const string RemoteModelName = "TrolTrueFormRemoteModel";
|
|
|
|
// Published by the owner after every trigger it fires, with a running count so the same
|
|
// punch twice in a row still reads as two - see FenrirAttackSync.
|
|
public const string AttackTriggerKey = "RacesOfValheim_TrolTrueFormAttack";
|
|
private static int attackSeq;
|
|
|
|
private static readonly int TrueFormHash = "SE_TrolTrueForm".GetStableHashCode();
|
|
|
|
public enum AttackKind { Punch, Slam, Throw, LogSwingH, LogSwingV }
|
|
|
|
public class Profile
|
|
{
|
|
public string Source;
|
|
public string Trigger;
|
|
public HitData.DamageTypes Damage;
|
|
public Attack.AttackType Type;
|
|
public float Range;
|
|
public float Height;
|
|
public float Angle;
|
|
public float PushForce;
|
|
public int ToolTier;
|
|
public ItemDrop.ItemData.SharedData Shared;
|
|
}
|
|
|
|
private static readonly Dictionary<AttackKind, Profile> profiles = new Dictionary<AttackKind, Profile>();
|
|
private static bool profilesRead;
|
|
|
|
// Measured once off the prefab: how tall the troll stands at scale 1.
|
|
private static float trollHeight = -1f;
|
|
private static string rightHandPath;
|
|
|
|
private static GameObject localModel;
|
|
private static int attackEvents;
|
|
|
|
public static bool LocalActive => localModel != null;
|
|
|
|
/// <summary>How many OnAttackTrigger events the local troll has fired. Attack routines
|
|
/// remember the count and wait for it to move.</summary>
|
|
public static int AttackEvents => attackEvents;
|
|
|
|
public static void NotifyAttackTrigger() => attackEvents++;
|
|
|
|
// ─── Lifecycle ───────────────────────────────────────────────────────
|
|
|
|
/// <summary>
|
|
/// Called every frame from TrolRace.Update, before its race check, so a race change, a death
|
|
/// or the form running out all take the costume off even though nothing else in TrolRace
|
|
/// looks at the player any more by then.
|
|
/// </summary>
|
|
public static void Tick(Player player)
|
|
{
|
|
if (player == null || player != Player.m_localPlayer) return;
|
|
|
|
bool wanted = TrolConfig.TrueFormUseTrollModel.Value &&
|
|
!player.IsDead() &&
|
|
TrolRace.IsTrol() &&
|
|
player.GetSEMan().HaveStatusEffect(TrueFormHash);
|
|
|
|
if (wanted && localModel == null) SpawnLocal(player);
|
|
else if (!wanted && localModel != null) RemoveLocal(player);
|
|
}
|
|
|
|
private static void SpawnLocal(Player player)
|
|
{
|
|
localModel = Spawn(player, LocalModelName);
|
|
if (localModel == null) return;
|
|
|
|
localModel.AddComponent<TrolTrueFormBehavior>();
|
|
PlayerVisualHider.Hide(player.transform.Find("Visual"), "trol-trueform-local");
|
|
|
|
GameObject smoke = PrefabManager.Cache.GetPrefab<GameObject>("vfx_corpse_destruction_medium");
|
|
if (smoke != null) Object.Instantiate(smoke, player.transform.position + Vector3.up, Quaternion.identity);
|
|
}
|
|
|
|
/// <summary>Takes the costume off and gives the body back. Safe to call when there is none.</summary>
|
|
public static bool RemoveLocal(Player player)
|
|
{
|
|
if (localModel == null) return false;
|
|
|
|
// SetActive first: Destroy waits for the end of the frame, and the behaviour's
|
|
// LateUpdate would hide the body again after the Show below. Same trap
|
|
// SvermRavagerForm.Exit documents.
|
|
localModel.SetActive(false);
|
|
Object.Destroy(localModel);
|
|
localModel = null;
|
|
|
|
if (player != null) PlayerVisualHider.Show(player.transform.Find("Visual"), "trol-trueform-revert");
|
|
return true;
|
|
}
|
|
|
|
/// <summary>
|
|
/// The troll's Visual, under the given player. Shared by the owner's copy and every
|
|
/// onlooker's, so both look alike; only the driving component differs.
|
|
/// </summary>
|
|
public static GameObject Spawn(Player player, string name)
|
|
{
|
|
GameObject prefab = PrefabManager.Cache.GetPrefab<GameObject>(Creature);
|
|
Transform source = prefab != null ? prefab.transform.Find("Visual") : null;
|
|
if (source == null)
|
|
{
|
|
Jotunn.Logger.LogWarning($"[Trol] No '{Creature}' Visual to build True Form from; staying in the old shape.");
|
|
return null;
|
|
}
|
|
|
|
MeasureTroll(prefab);
|
|
|
|
GameObject model = Object.Instantiate(source.gameObject, player.transform);
|
|
model.name = name;
|
|
model.transform.localPosition = Vector3.zero;
|
|
model.transform.localRotation = Quaternion.identity;
|
|
model.transform.localScale = Vector3.one * ScaleFor(player);
|
|
|
|
FormFootsteps.Detach(model, Creature);
|
|
|
|
Animator anim = model.GetComponentInChildren<Animator>(true);
|
|
if (anim != null)
|
|
{
|
|
anim.cullingMode = AnimatorCullingMode.AlwaysAnimate;
|
|
if (anim.GetComponent("AnimationEffect") == null) anim.gameObject.AddComponent<FormAnimEventSound>();
|
|
}
|
|
|
|
Tint(model, SkinColorOf(player));
|
|
return model;
|
|
}
|
|
|
|
/// <summary>
|
|
/// The costume's scale for this player right now: as tall as their Visual stands, in
|
|
/// player heights, times the Troll Model Size setting.
|
|
/// </summary>
|
|
public static float ScaleFor(Player player)
|
|
{
|
|
if (player == null || trollHeight <= 0f) return 1f;
|
|
|
|
GameObject visual = Traverse.Create(player).Field("m_visual").GetValue<GameObject>();
|
|
float visualScale = visual != null ? visual.transform.localScale.y : 1f;
|
|
|
|
CapsuleCollider capsule = player.GetComponent<CapsuleCollider>();
|
|
float playerHeight = capsule != null ? capsule.height : 1.85f;
|
|
|
|
return playerHeight * visualScale / trollHeight * TrolConfig.TrueFormModelSize.Value;
|
|
}
|
|
|
|
private static void MeasureTroll(GameObject prefab)
|
|
{
|
|
if (trollHeight > 0f) return;
|
|
|
|
CapsuleCollider capsule = prefab.GetComponent<CapsuleCollider>();
|
|
trollHeight = capsule != null ? capsule.height * prefab.transform.localScale.y : 0f;
|
|
if (trollHeight <= 0.5f) trollHeight = 4.5f;
|
|
|
|
// Where the troll holds its log: VisEquipment knows, so ask it rather than guess bones.
|
|
VisEquipment vis = prefab.GetComponent<VisEquipment>();
|
|
Transform hand = vis != null ? vis.m_rightHand : null;
|
|
Transform visualRoot = prefab.transform.Find("Visual");
|
|
if (hand != null && visualRoot != null && hand.IsChildOf(visualRoot))
|
|
{
|
|
rightHandPath = PathFrom(visualRoot, hand);
|
|
}
|
|
|
|
Jotunn.Logger.LogInfo($"[Trol] True Form model: '{Creature}' stands {trollHeight:0.00} m at scale 1, " +
|
|
$"right hand '{rightHandPath ?? "not found"}'.");
|
|
}
|
|
|
|
private static string PathFrom(Transform root, Transform child)
|
|
{
|
|
var parts = new List<string>();
|
|
for (Transform t = child; t != null && t != root; t = t.parent) parts.Insert(0, t.name);
|
|
return string.Join("/", parts);
|
|
}
|
|
|
|
// ─── Looks ───────────────────────────────────────────────────────────
|
|
|
|
/// <summary>The colour this Trol picked in Trol - Appearance, as published on their ZDO.</summary>
|
|
public static Color SkinColorOf(Player player)
|
|
{
|
|
ZNetView nview = player != null ? player.GetComponent<ZNetView>() : null;
|
|
if (nview != null && nview.IsValid())
|
|
{
|
|
Vector3 v = nview.GetZDO().GetVec3(TrolSkinColorPatch.SkinColorKey, new Vector3(-1f, -1f, -1f));
|
|
if (v.x >= 0f) return new Color(v.x, v.y, v.z, 1f);
|
|
}
|
|
return player == Player.m_localPlayer ? TrolConfig.SkinColor.Value : TrolConfig.DefaultSkinColor;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Multiplies the troll's own colour by the player's skin colour, brought up to full
|
|
/// brightness first: the troll's texture is already dark, and multiplying it by the swatch
|
|
/// as-is turned it nearly black. The hue is the player's, the shading stays the troll's.
|
|
/// </summary>
|
|
private static void Tint(GameObject model, Color skin)
|
|
{
|
|
float max = Mathf.Max(skin.r, Mathf.Max(skin.g, skin.b));
|
|
if (max <= 0.001f) return;
|
|
Color tint = new Color(skin.r / max, skin.g / max, skin.b / max, 1f);
|
|
|
|
foreach (Renderer r in model.GetComponentsInChildren<Renderer>(true))
|
|
{
|
|
if (r is ParticleSystemRenderer) continue;
|
|
foreach (Material m in r.materials)
|
|
{
|
|
if (m != null && m.HasProperty("_Color")) m.SetColor("_Color", m.GetColor("_Color") * tint);
|
|
}
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Puts a copy of the held Trol log in the troll's right hand, or takes it away. Called every
|
|
/// frame by both drivers with whatever the player has in their right hand.
|
|
/// </summary>
|
|
public static void UpdateHeldLog(GameObject model, GameObject itemPrefab, ref GameObject current, ref string currentName)
|
|
{
|
|
string wanted = itemPrefab != null && itemPrefab.name.StartsWith("TrolWeapon_") ? itemPrefab.name : null;
|
|
if (wanted == currentName) return;
|
|
|
|
if (current != null) Object.Destroy(current);
|
|
current = null;
|
|
currentName = wanted;
|
|
if (wanted == null || rightHandPath == null) return;
|
|
|
|
Transform hand = model.transform.Find(rightHandPath);
|
|
Transform attach = itemPrefab.transform.Find("attach");
|
|
if (hand == null || attach == null) return;
|
|
|
|
current = Object.Instantiate(attach.gameObject, hand);
|
|
current.name = "TrolTrueFormLog";
|
|
current.transform.localPosition = Vector3.zero;
|
|
current.transform.localRotation = Quaternion.identity;
|
|
// Left at the attach's own scale: the hand bone already carries the costume's, so the
|
|
// log grows and shrinks with the troll. Whether it looks right in the fist is a thing
|
|
// only an eye can settle - this is the line to change if it does not.
|
|
current.transform.localScale = Vector3.one;
|
|
}
|
|
|
|
// ─── Attacks ─────────────────────────────────────────────────────────
|
|
|
|
public static Profile Get(AttackKind kind)
|
|
{
|
|
EnsureProfiles();
|
|
profiles.TryGetValue(kind, out Profile p);
|
|
return p;
|
|
}
|
|
|
|
private static void EnsureProfiles()
|
|
{
|
|
if (profilesRead) return;
|
|
GameObject prefab = PrefabManager.Cache.GetPrefab<GameObject>(Creature);
|
|
Humanoid humanoid = prefab != null ? prefab.GetComponent<Humanoid>() : null;
|
|
if (humanoid == null) return;
|
|
profilesRead = true;
|
|
|
|
var weapons = new List<GameObject>();
|
|
if (humanoid.m_defaultItems != null) weapons.AddRange(humanoid.m_defaultItems);
|
|
if (humanoid.m_randomWeapon != null) weapons.AddRange(humanoid.m_randomWeapon);
|
|
if (humanoid.m_randomSets != null)
|
|
{
|
|
foreach (Humanoid.ItemSet set in humanoid.m_randomSets)
|
|
{
|
|
if (set?.m_items != null) weapons.AddRange(set.m_items);
|
|
}
|
|
}
|
|
|
|
foreach (GameObject weapon in weapons)
|
|
{
|
|
ItemDrop drop = weapon != null ? weapon.GetComponent<ItemDrop>() : null;
|
|
ItemDrop.ItemData.SharedData shared = drop?.m_itemData?.m_shared;
|
|
if (shared?.m_attack == null || string.IsNullOrEmpty(shared.m_attack.m_attackAnimation)) continue;
|
|
|
|
AttackKind? kind = Classify(weapon.name.ToLower(), shared);
|
|
if (kind == null || profiles.ContainsKey(kind.Value)) continue;
|
|
|
|
Attack a = shared.m_attack;
|
|
Profile p = new Profile
|
|
{
|
|
Source = weapon.name,
|
|
Trigger = a.m_attackAnimation,
|
|
Damage = shared.m_damages,
|
|
Type = a.m_attackType,
|
|
Range = a.m_attackRange,
|
|
Height = a.m_attackHeight,
|
|
Angle = a.m_attackAngle,
|
|
PushForce = shared.m_attackForce,
|
|
ToolTier = shared.m_toolTier,
|
|
Shared = shared,
|
|
};
|
|
profiles[kind.Value] = p;
|
|
|
|
Jotunn.Logger.LogInfo($"[Trol] True Form {kind.Value} <- '{p.Source}': trigger '{p.Trigger}', {p.Type}, " +
|
|
$"range {p.Range:0.0}, blunt {p.Damage.m_blunt:0} slash {p.Damage.m_slash:0} " +
|
|
$"chop {p.Damage.m_chop:0} pickaxe {p.Damage.m_pickaxe:0}.");
|
|
}
|
|
|
|
if (!profiles.ContainsKey(AttackKind.Punch))
|
|
{
|
|
Jotunn.Logger.LogWarning($"[Trol] '{Creature}' carries no punch; True Form left click will do nothing.");
|
|
}
|
|
}
|
|
|
|
private static AttackKind? Classify(string name, ItemDrop.ItemData.SharedData shared)
|
|
{
|
|
if (name.Contains("throw") || shared.m_attack.m_attackProjectile != null) return AttackKind.Throw;
|
|
if (name.Contains("log"))
|
|
{
|
|
return name.EndsWith("_v") || name.Contains("vertical") ? AttackKind.LogSwingV : AttackKind.LogSwingH;
|
|
}
|
|
if (name.Contains("slam") || shared.m_attack.m_attackType == Attack.AttackType.Area) return AttackKind.Slam;
|
|
if (name.Contains("punch")) return AttackKind.Punch;
|
|
return null;
|
|
}
|
|
|
|
/// <summary>
|
|
/// The owner's side of a remote replay: records the trigger just fired, so
|
|
/// RemoteTrolTrueFormAnimator plays it on every other client's copy.
|
|
/// </summary>
|
|
public static void PublishAttackTrigger(Player player, string trigger)
|
|
{
|
|
ZNetView nview = player != null ? player.GetComponent<ZNetView>() : null;
|
|
if (nview == null || !nview.IsValid()) return;
|
|
|
|
attackSeq++;
|
|
nview.GetZDO().Set(AttackTriggerKey, trigger + "#" + attackSeq);
|
|
}
|
|
|
|
/// <summary>
|
|
/// The damage a troll attack deals for this player right now: the troll's own numbers, times
|
|
/// Troll Attack Damage, times the same random Clubs factor a club would get.
|
|
/// </summary>
|
|
public static HitData.DamageTypes DamageFor(Player player, Profile profile)
|
|
{
|
|
HitData.DamageTypes damage = profile.Damage.Clone();
|
|
float factor = TrolConfig.TrueFormTrollDamageShare.Value * player.GetRandomSkillFactor(Skills.SkillType.Clubs);
|
|
damage.Modify(factor);
|
|
return damage;
|
|
}
|
|
|
|
// ─── Native attack loop, shut while the costume is on ────────────────
|
|
|
|
[HarmonyPatch(typeof(Humanoid), "StartAttack")]
|
|
public static class Trol_TrueFormBlockNativeAttack_Patch
|
|
{
|
|
public static bool Prefix(Humanoid __instance)
|
|
{
|
|
return __instance != Player.m_localPlayer || !LocalActive;
|
|
}
|
|
}
|
|
|
|
/// <summary>Crossbow reload and draw live here; see Fenrir's BlockPlayerAttackInputPatch.</summary>
|
|
[HarmonyPatch(typeof(Player), "PlayerAttackInput")]
|
|
public static class Trol_TrueFormBlockAttackInput_Patch
|
|
{
|
|
public static bool Prefix(Player __instance)
|
|
{
|
|
return __instance != Player.m_localPlayer || !LocalActive;
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// The troll's own clips call OnAttackTrigger at the moment a blow lands, and it arrives on
|
|
/// the player. It is the hit cue for TrolTrueFormBehavior, and it must go no further: let
|
|
/// through, it fires whatever attack the human still has in hand.
|
|
/// </summary>
|
|
[HarmonyPatch(typeof(Humanoid), nameof(Humanoid.OnAttackTrigger))]
|
|
public static class Trol_TrueFormAttackTrigger_Patch
|
|
{
|
|
public static bool Prefix(Humanoid __instance)
|
|
{
|
|
if (__instance != Player.m_localPlayer || !LocalActive) return true;
|
|
NotifyAttackTrigger();
|
|
return false;
|
|
}
|
|
}
|
|
}
|
|
}
|