Right click blocks in True Form with a raised-arms guard, rooted in place. Block + jump rolls at half distance with the troll's jump animation at double speed. The slam moves to middle click (secondary attack on a pad). trolpose is a debug command for trying guard and roll states live.
717 lines
34 KiB
C#
717 lines
34 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";
|
|
|
|
// The owner's Legacy True Form choice, so every other client draws this Trol the way its
|
|
// owner picked rather than the way the onlooker's own setting says.
|
|
public const string LegacyKey = "RacesOfValheim_TrolTrueFormLegacy";
|
|
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;
|
|
|
|
// The weapon's own model, as VisEquipment would hang it in the troll's hand. Only the
|
|
// log swings have one worth showing.
|
|
public GameObject Attach;
|
|
}
|
|
|
|
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 readonly HashSet<string> logged = new HashSet<string>();
|
|
|
|
private static GameObject localModel;
|
|
private static int attackEvents;
|
|
|
|
public static bool LocalActive => localModel != null;
|
|
|
|
public static Animator LocalAnimator => localModel != null ? localModel.GetComponentInChildren<Animator>() : null;
|
|
|
|
/// <summary>True while the local troll is in the middle of a swing, a slam or a throw.
|
|
/// Trol_TrueFormHoldStill_Patch holds the player still for exactly that long.</summary>
|
|
public static bool LocalAttacking { get; set; }
|
|
|
|
/// <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 legacy = TrolConfig.TrueFormLegacy.Value;
|
|
ZNetView nview = player.GetComponent<ZNetView>();
|
|
if (nview != null && nview.IsValid() && nview.GetZDO().GetBool(LegacyKey, false) != legacy)
|
|
{
|
|
nview.GetZDO().Set(LegacyKey, legacy);
|
|
}
|
|
|
|
bool wanted = !legacy &&
|
|
!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", keepScale: true);
|
|
|
|
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;
|
|
LocalAttacking = false;
|
|
|
|
if (player != null) PlayerVisualHider.Show(player.transform.Find("Visual"), "trol-trueform-revert", keepScale: true);
|
|
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;
|
|
}
|
|
|
|
// The vanilla forest troll's own colour, as near as a single swatch gets: the same value the
|
|
// Skin Color description recommends for "the look of Valheim's own trolls".
|
|
private static readonly Color VanillaTrollColor = new Color(0x7F / 255f, 0xA8 / 255f, 0xC9 / 255f, 1f);
|
|
|
|
/// <summary>
|
|
/// Shifts the troll's colour toward the player's skin colour, the way Valheim recolours a
|
|
/// starred creature: LevelEffects writes _Hue, _Saturation and _Value on the creature
|
|
/// shader. The first version multiplied _Color, which this shader does not read, so the
|
|
/// troll stayed vanilla blue. The shift is the distance from the vanilla troll's colour to
|
|
/// the chosen one, so the default Trol skin gives a troll close to its own colour and the
|
|
/// texture's shading survives whatever hue is picked.
|
|
/// </summary>
|
|
private static void Tint(GameObject model, Color skin)
|
|
{
|
|
Color.RGBToHSV(VanillaTrollColor, out float baseH, out float baseS, out float baseV);
|
|
Color.RGBToHSV(skin, out float h, out float s, out float v);
|
|
|
|
float hue = Mathf.Repeat(h - baseH + 0.5f, 1f) - 0.5f;
|
|
float saturation = Mathf.Clamp(s - baseS, -1f, 1f);
|
|
// Value is halved: the swatch reads darker on the skin than it looks in the picker (the
|
|
// Skin Color description says as much), and a full shift took the troll to near black.
|
|
float value = Mathf.Clamp((v - baseV) * 0.5f, -1f, 1f);
|
|
|
|
int tinted = 0;
|
|
foreach (Renderer r in model.GetComponentsInChildren<Renderer>(true))
|
|
{
|
|
if (r is ParticleSystemRenderer) continue;
|
|
foreach (Material m in r.materials)
|
|
{
|
|
if (m == null || !m.HasProperty("_Hue")) continue;
|
|
m.SetFloat("_Hue", hue);
|
|
if (m.HasProperty("_Saturation")) m.SetFloat("_Saturation", saturation);
|
|
if (m.HasProperty("_Value")) m.SetFloat("_Value", value);
|
|
tinted++;
|
|
}
|
|
}
|
|
|
|
if (logged.Add("tint/" + model.name))
|
|
{
|
|
Jotunn.Logger.LogInfo($"[Trol] True Form tint: hue {hue:+0.00;-0.00}, saturation {saturation:+0.00;-0.00}, " +
|
|
$"value {value:+0.00;-0.00} on {tinted} material(s).");
|
|
}
|
|
}
|
|
|
|
/// <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);
|
|
if (hand == null) return;
|
|
|
|
// The troll's OWN log, not the Trol's. The Trol's was built for a person's hand - turned
|
|
// 90 degrees, pushed 1.5 m along it, scaled to 0.4 - and in the troll's fist that came
|
|
// out huge and pointing the wrong way. The troll's log weapon carries a model made for
|
|
// exactly this bone, and hanging it the way VisEquipment.AttachItem does (zero offset,
|
|
// no rotation, its own scale) puts it where vanilla puts it.
|
|
Profile log = Get(AttackKind.LogSwingH) ?? Get(AttackKind.LogSwingV);
|
|
GameObject source = log?.Attach;
|
|
if (source == null) return;
|
|
|
|
// An item's "attach" child is stored INACTIVE in its prefab; VisEquipment.AttachItem
|
|
// switches it on after the Instantiate. Copied as it was, the log hung in the fist
|
|
// switched off - invisible, and it looked as if the Trol held nothing.
|
|
current = Object.Instantiate(source);
|
|
current.SetActive(true);
|
|
current.name = "TrolTrueFormLog";
|
|
foreach (Collider c in current.GetComponentsInChildren<Collider>(true)) Object.Destroy(c);
|
|
|
|
// Hung the way AttachItem hangs it: on the joint at zero, then the item's equipoffset.
|
|
current.transform.SetParent(hand, false);
|
|
current.transform.localPosition = Vector3.zero;
|
|
current.transform.localRotation = Quaternion.identity;
|
|
Transform offset = source.transform.parent != null ? source.transform.parent.Find("equipoffset") : null;
|
|
if (offset != null)
|
|
{
|
|
current.transform.localPosition += offset.position;
|
|
current.transform.localRotation *= offset.rotation;
|
|
}
|
|
|
|
// AttachItem keeps the attach at its own WORLD size, and a vanilla troll stands at scale 1.
|
|
// This one is worn smaller or bigger, so the log takes the costume's share on top. Once
|
|
// set, the hand carries it through the grow and shrink like any child.
|
|
float handScale = hand.lossyScale.x;
|
|
float costume = model.transform.localScale.x;
|
|
current.transform.localScale = handScale > 0.0001f
|
|
? source.transform.localScale * (costume / handScale)
|
|
: source.transform.localScale;
|
|
|
|
if (logged.Add("log/" + source.name))
|
|
{
|
|
Jotunn.Logger.LogInfo($"[Trol] True Form log '{log.Source}' in hand: hand scale {handScale:0.###}, " +
|
|
$"costume {costume:0.###}, offset {(offset != null ? "yes" : "no")}.");
|
|
}
|
|
}
|
|
|
|
// ─── 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,
|
|
Attach = weapon.transform.Find("attach")?.gameObject,
|
|
};
|
|
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);
|
|
}
|
|
|
|
// ─── Guard and roll poses ────────────────────────────────────────────
|
|
|
|
// The troll has no block or roll of its own, so the guard is one frame of another state held
|
|
// still. State names are read off troll_animator with scripts/dump_controller.py: Movement,
|
|
// attack, jump, punch, throw, swing log V, swing log H, Stagger, Summon, Sleeping, Wakeup,
|
|
// In Water. Both are settable live with the trolpose command until the right frame is found.
|
|
public const string MovementState = "Movement";
|
|
// Picked in game with trolpose: the troll half risen out of its Wakeup, arms up.
|
|
public static string GuardState = "Wakeup";
|
|
public static float GuardTime = 0.13f;
|
|
|
|
/// <summary>The state played whole when the player rolls; null plays nothing and the troll
|
|
/// slides along with the roll.</summary>
|
|
public static string DodgeState = "jump";
|
|
|
|
/// <summary>How fast the roll state plays: the troll's jump runs longer than a roll, so at 1
|
|
/// the troll was still leaping after the roll had ended.</summary>
|
|
public static float DodgeSpeed = 2f;
|
|
|
|
// The local troll's Animator while its roll state plays, null otherwise.
|
|
// Trol_TrueFormDodgeSpeed_Patch keeps its speed up through every FixedUpdate.
|
|
private static Animator dodgeAnimator;
|
|
private static float dodgeStarted;
|
|
|
|
/// <summary>Set while the owner's troll holds its guard, to "state|time", so every other
|
|
/// client's copy holds the same frame. Empty when it is not guarding.</summary>
|
|
public const string GuardKey = "RacesOfValheim_TrolTrueFormGuard";
|
|
|
|
public static bool HasState(Animator anim, string state)
|
|
{
|
|
return anim != null && !string.IsNullOrEmpty(state) && anim.HasState(0, Animator.StringToHash("Base Layer." + state));
|
|
}
|
|
|
|
public static void PlayDodge(Animator anim)
|
|
{
|
|
if (!HasState(anim, DodgeState)) return;
|
|
anim.speed = DodgeSpeed;
|
|
anim.CrossFadeInFixedTime("Base Layer." + DodgeState, 0.1f, 0, 0f);
|
|
dodgeAnimator = anim;
|
|
dodgeStarted = Time.time;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Called every frame: keeps the roll state at DodgeSpeed while it plays, and puts the speed
|
|
/// back once the troll has left it. The first moments are skipped, because the cross-fade
|
|
/// into the state only starts on the Animator's next update.
|
|
/// </summary>
|
|
public static void TickDodge()
|
|
{
|
|
if (dodgeAnimator == null) return;
|
|
|
|
int hash = Animator.StringToHash("Base Layer." + DodgeState);
|
|
bool inState = dodgeAnimator.GetCurrentAnimatorStateInfo(0).fullPathHash == hash ||
|
|
(dodgeAnimator.IsInTransition(0) && dodgeAnimator.GetNextAnimatorStateInfo(0).fullPathHash == hash);
|
|
|
|
if (inState || Time.time - dodgeStarted < 0.15f) dodgeAnimator.speed = DodgeSpeed;
|
|
else EndDodge();
|
|
}
|
|
|
|
public static void EndDodge()
|
|
{
|
|
if (dodgeAnimator != null) dodgeAnimator.speed = 1f;
|
|
dodgeAnimator = null;
|
|
}
|
|
|
|
/// <summary>The troll's CharacterAnimEvent sets its Animator back to speed 1 in every
|
|
/// FixedUpdate; this sets the roll's speed again right after.</summary>
|
|
[HarmonyPatch(typeof(CharacterAnimEvent), nameof(CharacterAnimEvent.CustomFixedUpdate))]
|
|
public static class Trol_TrueFormDodgeSpeed_Patch
|
|
{
|
|
public static void Postfix(CharacterAnimEvent __instance)
|
|
{
|
|
if (dodgeAnimator != null && __instance.gameObject == dodgeAnimator.gameObject) dodgeAnimator.speed = DodgeSpeed;
|
|
}
|
|
}
|
|
|
|
public static void PublishGuard(Player player, bool on)
|
|
{
|
|
ZNetView nview = player != null ? player.GetComponent<ZNetView>() : null;
|
|
if (nview == null || !nview.IsValid()) return;
|
|
|
|
string value = on ? GuardState + "|" + GuardTime.ToString(System.Globalization.CultureInfo.InvariantCulture) : "";
|
|
if (nview.GetZDO().GetString(GuardKey, "") != value) nview.GetZDO().Set(GuardKey, value);
|
|
}
|
|
|
|
/// <summary>The pose another client's troll should hold, read back off the owner's ZDO.</summary>
|
|
public static bool ReadGuard(ZDO zdo, out string state, out float time)
|
|
{
|
|
state = null;
|
|
time = 0f;
|
|
string value = zdo.GetString(GuardKey, "");
|
|
int bar = value.LastIndexOf('|');
|
|
if (bar <= 0) return false;
|
|
|
|
state = value.Substring(0, bar);
|
|
return float.TryParse(value.Substring(bar + 1), System.Globalization.NumberStyles.Float,
|
|
System.Globalization.CultureInfo.InvariantCulture, out time);
|
|
}
|
|
|
|
/// <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 ────────────────
|
|
|
|
/// <summary>
|
|
/// Holds the troll still through its own attack clips, the way vanilla roots a creature in
|
|
/// mid-swing. SkeletonRiseControlsPatch's arrangement: the move direction is the first
|
|
/// argument of SetControls, bound by position.
|
|
/// </summary>
|
|
[HarmonyPatch(typeof(Player), "SetControls")]
|
|
public static class Trol_TrueFormHoldStill_Patch
|
|
{
|
|
public static void Prefix(Player __instance, ref Vector3 __0, ref bool jump, ref bool crouch, ref bool dodge)
|
|
{
|
|
if (__instance != Player.m_localPlayer || !LocalActive || !LocalAttacking) return;
|
|
|
|
__0 = Vector3.zero;
|
|
jump = false;
|
|
crouch = false;
|
|
dodge = false;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Rooted while guarding, so the held pose cannot slide across the ground. Cleared after
|
|
/// SetControls, not before: the block-and-jump roll takes its direction from the move
|
|
/// input inside SetControls, and an input zeroed first sent every roll backwards.
|
|
/// </summary>
|
|
public static void Postfix(Player __instance)
|
|
{
|
|
if (__instance != Player.m_localPlayer || !LocalActive || LocalAttacking) return;
|
|
if (__instance.IsBlocking() && !__instance.InDodge()) MoveDir(__instance) = Vector3.zero;
|
|
}
|
|
|
|
private static readonly AccessTools.FieldRef<Character, Vector3> MoveDir =
|
|
AccessTools.FieldRefAccess<Character, Vector3>("m_moveDir");
|
|
}
|
|
|
|
// Share of a normal roll's distance the troll covers. The roll moves by root motion, and
|
|
// under True Form two animators feed it: the hidden human's dodge and the troll's jump.
|
|
private const float RollDistance = 0.5f;
|
|
|
|
/// <summary>A shorter roll for the troll: every bit of root motion that reaches the player
|
|
/// during a True Form roll is scaled, whichever of the two clips it came from.</summary>
|
|
[HarmonyPatch(typeof(Character), nameof(Character.AddRootMotion))]
|
|
public static class Trol_TrueFormRollDistance_Patch
|
|
{
|
|
public static void Prefix(Character __instance, ref Vector3 vel)
|
|
{
|
|
if (__instance == Player.m_localPlayer && LocalActive && __instance.InDodge()) vel *= RollDistance;
|
|
}
|
|
}
|
|
|
|
[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;
|
|
}
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Holds one troll at one frame of a state, for the True Form guard. It blends in the way it
|
|
/// blends out: a cross-fade into the frame first, then the frame pinned once the fade is over.
|
|
/// Pinned again every frame it holds: the troll's own CharacterAnimEvent puts the Animator back
|
|
/// to speed 1 in every FixedUpdate, so a speed of 0 set once would not stay.
|
|
/// </summary>
|
|
internal class TrolGuardPose
|
|
{
|
|
private const float Fade = 0.2f;
|
|
|
|
// Each state's length, learned the first time it is held: the fade starts that far ahead of
|
|
// the frame, so the state lands on it when the fade ends instead of running past it.
|
|
private static readonly Dictionary<int, float> lengths = new Dictionary<int, float>();
|
|
|
|
private int state;
|
|
private float target;
|
|
private float fadeStarted;
|
|
private bool fading;
|
|
private float pinned;
|
|
|
|
public void Hold(Animator anim, string name, float time)
|
|
{
|
|
if (!TrolTrueFormModel.HasState(anim, name)) return;
|
|
int hash = Animator.StringToHash("Base Layer." + name);
|
|
time = Mathf.Clamp01(time);
|
|
|
|
if (hash != state || time != target)
|
|
{
|
|
state = hash;
|
|
target = time;
|
|
StartFade(anim);
|
|
}
|
|
|
|
if (fading)
|
|
{
|
|
anim.speed = 1f;
|
|
if (Time.time - fadeStarted < Fade || anim.IsInTransition(0)) return;
|
|
|
|
AnimatorStateInfo info = anim.GetCurrentAnimatorStateInfo(0);
|
|
if (info.fullPathHash == state && info.length > 0f)
|
|
{
|
|
lengths[state] = info.length;
|
|
pinned = info.normalizedTime < 1f ? info.normalizedTime : target;
|
|
}
|
|
else
|
|
{
|
|
pinned = target;
|
|
}
|
|
fading = false;
|
|
}
|
|
|
|
anim.Play(state, 0, pinned);
|
|
anim.speed = 0f;
|
|
}
|
|
|
|
private void StartFade(Animator anim)
|
|
{
|
|
// CrossFade takes its duration as a share of the state being left, so turn the seconds
|
|
// into that share.
|
|
float from = anim.GetCurrentAnimatorStateInfo(0).length;
|
|
float lead = lengths.TryGetValue(state, out float length) && length > 0f ? Fade / length : 0f;
|
|
|
|
anim.speed = 1f;
|
|
anim.CrossFade(state, from > 0f ? Fade / from : Fade, 0, Mathf.Max(0f, target - lead));
|
|
fadeStarted = Time.time;
|
|
fading = true;
|
|
}
|
|
|
|
public void Release(Animator anim)
|
|
{
|
|
state = 0;
|
|
fading = false;
|
|
if (anim == null) return;
|
|
|
|
anim.speed = 1f;
|
|
if (TrolTrueFormModel.HasState(anim, TrolTrueFormModel.MovementState))
|
|
{
|
|
anim.CrossFadeInFixedTime("Base Layer." + TrolTrueFormModel.MovementState, Fade, 0);
|
|
}
|
|
}
|
|
}
|
|
}
|