// Animancer // https://kybernetik.com.au/animancer // Copyright 2018-2023 Kybernetik // using System; using System.Collections; using System.Collections.Generic; using System.Text; using UnityEngine; using UnityEngine.Playables; using Object = UnityEngine.Object; namespace Animancer { /// Base class for wrapper objects in an . /// https://kybernetik.com.au/animancer/api/Animancer/AnimancerNode /// public abstract class AnimancerNode : Key, IUpdatable, IEnumerable, IEnumerator, IPlayableWrapper, ICopyable { /************************************************************************************************************************/ #region Playable /************************************************************************************************************************/ /// /// The internal object this node manages in the . /// /// Must be set by . Failure to do so will throw the following exception /// throughout the system when using this node: ": The playable passed as an /// argument is invalid. To create a valid playable, please use the appropriate Create method". /// protected internal Playable _Playable; /// The internal managed by this node. public Playable Playable => _Playable; /// Is the usable (properly initialized and not destroyed)? public bool IsValid => _Playable.IsValid(); /************************************************************************************************************************/ #if UNITY_EDITOR /// [Editor-Only, Internal] Indicates whether the Inspector details for this node are expanded. internal bool _IsInspectorExpanded; #endif /************************************************************************************************************************/ /// Creates and assigns the managed by this node. /// This method also applies the if it was set beforehand. public virtual void CreatePlayable() { #if UNITY_ASSERTIONS if (Root == null) throw new InvalidOperationException($"{nameof(AnimancerNode)}.{nameof(Root)}" + $" is null when attempting to create its {nameof(Playable)}: {this}" + $"\nThe {nameof(Root)} is generally set when you first play a state," + " so you probably just need to play it before trying to access it."); if (_Playable.IsValid()) Debug.LogWarning($"{nameof(AnimancerNode)}.{nameof(CreatePlayable)}" + $" was called before destroying the previous {nameof(Playable)}: {this}", Root?.Component as Object); #endif CreatePlayable(out _Playable); #if UNITY_ASSERTIONS if (!_Playable.IsValid()) throw new InvalidOperationException( $"{nameof(AnimancerNode)}.{nameof(CreatePlayable)} did not create a valid {nameof(Playable)}:" + this); #endif if (_Speed != 1) _Playable.SetSpeed(_Speed); var parent = Parent; if (parent != null) ApplyConnectedState(parent); } /// Creates and assigns the managed by this node. protected abstract void CreatePlayable(out Playable playable); /************************************************************************************************************************/ /// Destroys the . public void DestroyPlayable() { if (_Playable.IsValid()) Root._Graph.DestroyPlayable(_Playable); } /************************************************************************************************************************/ /// Calls and . public virtual void RecreatePlayable() { DestroyPlayable(); CreatePlayable(); } /// Calls on this node and all its children recursively. public void RecreatePlayableRecursive() { RecreatePlayable(); for (int i = ChildCount - 1; i >= 0; i--) GetChild(i)?.RecreatePlayableRecursive(); } /************************************************************************************************************************/ /// void ICopyable.CopyFrom(AnimancerNode copyFrom) { _Weight = copyFrom._Weight; _IsWeightDirty = true; TargetWeight = copyFrom.TargetWeight; FadeSpeed = copyFrom.FadeSpeed; Speed = copyFrom.Speed; CopyIKFlags(copyFrom); #if UNITY_ASSERTIONS SetDebugName(copyFrom.DebugName); #endif } /************************************************************************************************************************/ #endregion /************************************************************************************************************************/ #region Graph /************************************************************************************************************************/ private AnimancerPlayable _Root; /// The at the root of the graph. public AnimancerPlayable Root { get => _Root; internal set { _Root = value; #if UNITY_ASSERTIONS GC.SuppressFinalize(this); #endif } } /************************************************************************************************************************/ /// The root which this node is connected to. public abstract AnimancerLayer Layer { get; } /// The object which receives the output of this node. public abstract IPlayableWrapper Parent { get; } /************************************************************************************************************************/ /// The index of the port this node is connected to on the parent's . /// /// A negative value indicates that it is not assigned to a port. /// /// Indices are generally assigned starting from 0, ascending in the order they are connected to their layer. /// They will not usually change unless the changes or another state on the same layer is /// destroyed so the last state is swapped into its place to avoid shuffling everything down to cover the gap. /// /// The setter is internal so user defined states cannot set it incorrectly. Ideally, /// should be able to set the port in its constructor and /// should also be able to set it, but classes that further inherit from /// there should not be able to change it without properly calling that method. /// public int Index { get; internal set; } = int.MinValue; /************************************************************************************************************************/ /// Creates a new . protected AnimancerNode() { #if UNITY_ASSERTIONS if (TraceConstructor) _ConstructorStackTrace = new System.Diagnostics.StackTrace(true); #endif } /************************************************************************************************************************/ #if UNITY_ASSERTIONS /************************************************************************************************************************/ /// [Assert-Only] /// Should a be captured in the constructor of all new nodes so /// can include it in the warning if that node ends up being unused? /// /// This has a notable performance cost so it should only be used when trying to identify a problem. public static bool TraceConstructor { get; set; } /************************************************************************************************************************/ /// [Assert-Only] /// The stack trace of the constructor (or null if was false). /// private System.Diagnostics.StackTrace _ConstructorStackTrace; /// [Assert-Only] /// Returns the stack trace of the constructor (or null if was false). /// public static System.Diagnostics.StackTrace GetConstructorStackTrace(AnimancerNode node) => node._ConstructorStackTrace; /************************************************************************************************************************/ /// [Assert-Only] Checks . ~AnimancerNode() { if (Root != null || OptionalWarning.UnusedNode.IsDisabled()) return; var name = DebugName; if (string.IsNullOrEmpty(name)) { // ToString will likely throw an exception since finalizers are not run on the main thread. try { name = ToString(); } catch { name = GetType().FullName; } } var message = $"The {nameof(Root)} {nameof(AnimancerPlayable)} of '{name}'" + $" is null during finalization (garbage collection)." + $" This probably means that it was never used for anything and should not have been created."; if (_ConstructorStackTrace != null) message += "\n\nThis node was created at:\n" + _ConstructorStackTrace; else message += $"\n\nEnable {nameof(AnimancerNode)}.{nameof(TraceConstructor)} on startup to allow" + $" this warning to include the {nameof(System.Diagnostics.StackTrace)} of when the node was constructed."; OptionalWarning.UnusedNode.Log(message); } /************************************************************************************************************************/ #endif /************************************************************************************************************************/ /// [Internal] Connects the to the . internal void ConnectToGraph() { var parent = Parent; if (parent == null) return; #if UNITY_ASSERTIONS if (Index < 0) throw new InvalidOperationException( $"Invalid {nameof(AnimancerNode)}.{nameof(Index)}" + " when attempting to connect to its parent:" + "\n• Node: " + this + "\n• Parent: " + parent); Validate.AssertPlayable(this); #endif var parentPlayable = parent.Playable; Root._Graph.Connect(_Playable, 0, parentPlayable, Index); parentPlayable.SetInputWeight(Index, _Weight); _IsWeightDirty = false; } /// [Internal] Disconnects the from the . internal void DisconnectFromGraph() { var parent = Parent; if (parent == null) return; var parentPlayable = parent.Playable; if (parentPlayable.GetInput(Index).IsValid()) Root._Graph.Disconnect(parentPlayable, Index); } /************************************************************************************************************************/ private void ApplyConnectedState(IPlayableWrapper parent) { #if UNITY_ASSERTIONS if (Index < 0) throw new InvalidOperationException( $"Invalid {nameof(AnimancerNode)}.{nameof(Index)}" + $" when attempting to connect to its parent:" + $"\n• {nameof(Index)}: {Index}" + $"\n• Node: {this}" + $"\n• Parent: {this}"); #endif _IsWeightDirty = true; if (_Weight != 0 || parent.KeepChildrenConnected) { ConnectToGraph(); } else { Root.RequirePreUpdate(this); } } /************************************************************************************************************************/ /// Calls if the is not null. protected void RequireUpdate() { Root?.RequirePreUpdate(this); } /************************************************************************************************************************/ /// void IUpdatable.Update() { if (_Playable.IsValid()) { Update(out var needsMoreUpdates); if (needsMoreUpdates) return; } Root.CancelPreUpdate(this); } /// /// Updates the for fading, applies it to this state's port on the parent mixer, and plays /// or pauses the if its state is dirty. /// /// If the 's is set to false, this method will /// also connect/disconnect this node from the in the playable graph. /// protected internal virtual void Update(out bool needsMoreUpdates) { UpdateFade(out needsMoreUpdates); ApplyWeight(); } /************************************************************************************************************************/ // IEnumerator for yielding in a coroutine to wait until animations have stopped. /************************************************************************************************************************/ /// Is this node playing and not yet at its end? /// /// This method is called by so this object can be used as a custom yield /// instruction to wait until it finishes. /// public abstract bool IsPlayingAndNotEnding(); bool IEnumerator.MoveNext() => IsPlayingAndNotEnding(); object IEnumerator.Current => null; void IEnumerator.Reset() { } /************************************************************************************************************************/ #endregion /************************************************************************************************************************/ #region Children /************************************************************************************************************************/ /// [] /// The number of states using this node as their . /// public virtual int ChildCount => 0; /// Returns the state connected to the specified `index` as a child of this node. /// This node can't have children. AnimancerNode IPlayableWrapper.GetChild(int index) => GetChild(index); /// [] /// Returns the state connected to the specified `index` as a child of this node. /// /// This node can't have children. public virtual AnimancerState GetChild(int index) => throw new NotSupportedException(this + " can't have children."); /// Called when a child is connected with this node as its . /// This node can't have children. protected internal virtual void OnAddChild(AnimancerState state) { state.SetParentInternal(null); throw new NotSupportedException(this + " can't have children."); } /// Called when a child's is changed from this node. /// This node can't have children. protected internal virtual void OnRemoveChild(AnimancerState state) { state.SetParentInternal(null); throw new NotSupportedException(this + " can't have children."); } /************************************************************************************************************************/ /// Connects the `state` to this node at its . /// The was already occupied. protected void OnAddChild(IList states, AnimancerState state) { var index = state.Index; if (states[index] != null) { state.SetParentInternal(null); throw new InvalidOperationException( $"Tried to add a state to an already occupied port on {this}:" + $"\n• {nameof(Index)}: {index}" + $"\n• Old State: {states[index]} " + $"\n• New State: {state}"); } #if UNITY_ASSERTIONS if (state.Root != Root) Debug.LogError( $"{nameof(AnimancerNode)}.{nameof(Root)} mismatch:" + $"\n• {nameof(state)}: {state}" + $"\n• {nameof(state)}.{nameof(state.Root)}: {state.Root}" + $"\n• {nameof(Parent)}.{nameof(Root)}: {Root}", Root?.Component as Object); #endif states[index] = state; if (Root != null) state.ApplyConnectedState(this); } /************************************************************************************************************************/ /// /// Indicates whether child playables should stay connected to this mixer at all times (default false). /// public virtual bool KeepChildrenConnected => false; /// /// Ensures that all children of this node are connected to the . /// internal void ConnectAllChildrenToGraph() { if (!Parent.Playable.GetInput(Index).IsValid()) ConnectToGraph(); for (int i = ChildCount - 1; i >= 0; i--) GetChild(i)?.ConnectAllChildrenToGraph(); } /// /// Ensures that all children of this node which have zero weight are disconnected from the /// . /// internal void DisconnectWeightlessChildrenFromGraph() { if (Weight == 0) DisconnectFromGraph(); for (int i = ChildCount - 1; i >= 0; i--) GetChild(i)?.DisconnectWeightlessChildrenFromGraph(); } /************************************************************************************************************************/ // IEnumerable for 'foreach' statements. /************************************************************************************************************************/ /// Gets an enumerator for all of this node's child states. public virtual FastEnumerator GetEnumerator() => default; IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); /************************************************************************************************************************/ #endregion /************************************************************************************************************************/ #region Weight /************************************************************************************************************************/ /// The current blend weight of this node. Accessed via . private float _Weight; /// Indicates whether the weight has changed and should be applied to the parent mixer. private bool _IsWeightDirty = true; /************************************************************************************************************************/ /// The current blend weight of this node which determines how much it affects the final output. /// /// 0 has no effect while 1 applies the full effect and values inbetween apply a proportional effect. /// /// Setting this property cancels any fade currently in progress. If you don't wish to do that, you can use /// instead. /// /// Animancer Lite only allows this value to be set to 0 or 1 in runtime builds. /// /// /// /// Calling immediately sets the weight of all states to 0 /// and the new state to 1. Note that this is separate from other values like /// so a state can be paused at any point and still show its pose on the /// character or it could be still playing at 0 weight if you want it to still trigger events (though states /// are normally stopped when they reach 0 weight so you would need to explicitly set it to playing again). /// /// Calling does not immediately change /// the weights, but instead calls on every state to set their /// and . Then every update each state's weight will move /// towards that target value at that speed. /// public float Weight { get => _Weight; set { SetWeight(value); TargetWeight = value; FadeSpeed = 0; } } /// /// Sets the current blend weight of this node which determines how much it affects the final output. /// 0 has no effect while 1 applies the full effect of this node. /// /// This method allows any fade currently in progress to continue. If you don't wish to do that, you can set /// the property instead. /// /// Animancer Lite only allows this value to be set to 0 or 1 in runtime builds. /// public void SetWeight(float value) { if (_Weight == value) return; #if UNITY_ASSERTIONS if (!(value >= 0) || value == float.PositiveInfinity)// Reversed comparison includes NaN. throw new ArgumentOutOfRangeException(nameof(value), value, $"{nameof(Weight)} must be a finite positive value"); #endif _Weight = value; SetWeightDirty(); } /// Flags this node as having a changed that needs to be applied next update. protected internal void SetWeightDirty() { _IsWeightDirty = true; RequireUpdate(); } /************************************************************************************************************************/ /// /// Applies the to the connection between this node and its . /// public void ApplyWeight() { if (!_IsWeightDirty) return; _IsWeightDirty = false; var parent = Parent; if (parent == null) return; Playable parentPlayable; if (!parent.KeepChildrenConnected) { if (_Weight == 0) { DisconnectFromGraph(); return; } parentPlayable = parent.Playable; if (!parentPlayable.GetInput(Index).IsValid()) ConnectToGraph(); } else parentPlayable = parent.Playable; parentPlayable.SetInputWeight(Index, _Weight); } /************************************************************************************************************************/ /// /// The of this state multiplied by the of each of its parents down /// the hierarchy to determine how much this state affects the final output. /// public float EffectiveWeight { get { var weight = Weight; var parent = Parent; while (parent != null) { weight *= parent.Weight; parent = parent.Parent; } return weight; } } /************************************************************************************************************************/ #endregion /************************************************************************************************************************/ #region Fading /************************************************************************************************************************/ /// /// The desired which this node is fading towards according to the /// . /// public float TargetWeight { get; set; } /// The speed at which this node is fading towards the . /// This value isn't affected by this node's , but is affected by its parents. public float FadeSpeed { get; set; } /************************************************************************************************************************/ /// /// Calls and starts fading the over the course /// of the (in seconds). /// /// /// If the `targetWeight` is 0 then will be called when the fade is complete. /// /// If the is already equal to the `targetWeight` then the fade will end /// immediately. /// public void StartFade(float targetWeight) => StartFade(targetWeight, AnimancerPlayable.DefaultFadeDuration); /// /// Calls and starts fading the over the course /// of the `fadeDuration` (in seconds). /// /// /// If the `targetWeight` is 0 then will be called when the fade is complete. /// /// If the is already equal to the `targetWeight` then the fade will end /// immediately. /// /// Animancer Lite only allows a `targetWeight` of 0 or 1 and the default `fadeDuration` (0.25 seconds) in /// runtime builds. /// public void StartFade(float targetWeight, float fadeDuration) { TargetWeight = targetWeight; if (targetWeight == Weight) { if (targetWeight == 0) { Stop(); } else { FadeSpeed = 0; OnStartFade(); } return; } // Duration 0 = Instant. if (fadeDuration <= 0) { FadeSpeed = float.PositiveInfinity; } else// Otherwise determine how fast we need to go to cover the distance in the specified time. { FadeSpeed = Math.Abs(Weight - targetWeight) / fadeDuration; } OnStartFade(); RequireUpdate(); } /************************************************************************************************************************/ /// Called by . protected internal abstract void OnStartFade(); /************************************************************************************************************************/ /// /// Stops the animation and makes it inactive immediately so it no longer affects the output. /// Sets = 0 by default. /// public virtual void Stop() { Weight = 0; } /************************************************************************************************************************/ /// /// Moves the towards the according to the /// . /// private void UpdateFade(out bool needsMoreUpdates) { var fadeSpeed = FadeSpeed; if (fadeSpeed == 0) { needsMoreUpdates = false; return; } _IsWeightDirty = true; fadeSpeed *= ParentEffectiveSpeed * AnimancerPlayable.DeltaTime; if (fadeSpeed < 0) fadeSpeed = -fadeSpeed; var target = TargetWeight; var current = _Weight; var delta = target - current; if (delta > 0) { if (delta > fadeSpeed) { _Weight = current + fadeSpeed; needsMoreUpdates = true; return; } } else { if (-delta > fadeSpeed) { _Weight = current - fadeSpeed; needsMoreUpdates = true; return; } } _Weight = target; needsMoreUpdates = false; if (target == 0) { Stop(); } else { FadeSpeed = 0; } } /************************************************************************************************************************/ #endregion /************************************************************************************************************************/ #region Speed /************************************************************************************************************************/ private float _Speed = 1; /// [Pro-Only] How fast the is advancing every frame (default 1). /// /// /// A negative value will play the animation backwards. /// /// To pause an animation, consider setting to false instead of setting /// this value to 0. /// /// Animancer Lite does not allow this value to be changed in runtime builds. /// /// /// /// void PlayAnimation(AnimancerComponent animancer, AnimationClip clip) /// { /// var state = animancer.Play(clip); /// /// state.Speed = 1;// Normal speed. /// state.Speed = 2;// Double speed. /// state.Speed = 0.5f;// Half speed. /// state.Speed = -1;// Normal speed playing backwards. /// } /// /// /// The value is not finite. public float Speed { get => _Speed; set { if (_Speed == value) return; #if UNITY_ASSERTIONS if (!value.IsFinite()) throw new ArgumentOutOfRangeException(nameof(value), value, $"{nameof(Speed)} {Strings.MustBeFinite}"); OptionalWarning.UnsupportedSpeed.Log(UnsupportedSpeedMessage, Root?.Component); #endif _Speed = value; if (_Playable.IsValid()) _Playable.SetSpeed(value); } } #if UNITY_ASSERTIONS /// [Assert-Only] /// Returns null if the property will work properly on this type of node, or a message /// explaining why it won't work. /// protected virtual string UnsupportedSpeedMessage => null; #endif /************************************************************************************************************************/ /// /// The multiplied of each of this node's parents down the hierarchy, excluding the root /// . /// private float ParentEffectiveSpeed { get { var parent = Parent; if (parent == null) return 1; var speed = parent.Speed; while ((parent = parent.Parent) != null) { speed *= parent.Speed; } return speed; } } /// /// The of this node multiplied by the of each of its parents to /// determine the actual speed it's playing at. /// public float EffectiveSpeed { get => Speed * ParentEffectiveSpeed; set => Speed = value / ParentEffectiveSpeed; } /************************************************************************************************************************/ #endregion /************************************************************************************************************************/ #region Inverse Kinematics /************************************************************************************************************************/ /// /// Should setting the also set this node's to match it? /// Default is true. /// public static bool ApplyParentAnimatorIK { get; set; } = true; /// /// Should setting the also set this node's to match it? /// Default is true. /// public static bool ApplyParentFootIK { get; set; } = true; /************************************************************************************************************************/ /// /// Copies the IK settings from the : /// /// If is true, copy . /// If is true, copy . /// /// public virtual void CopyIKFlags(AnimancerNode copyFrom) { if (Root == null) return; if (ApplyParentAnimatorIK) ApplyAnimatorIK = copyFrom.ApplyAnimatorIK; if (ApplyParentFootIK) ApplyFootIK = copyFrom.ApplyFootIK; } /************************************************************************************************************************/ /// public virtual bool ApplyAnimatorIK { get { for (int i = ChildCount - 1; i >= 0; i--) { var state = GetChild(i); if (state == null) continue; if (state.ApplyAnimatorIK) return true; } return false; } set { for (int i = ChildCount - 1; i >= 0; i--) { var state = GetChild(i); if (state == null) continue; state.ApplyAnimatorIK = value; } } } /************************************************************************************************************************/ /// public virtual bool ApplyFootIK { get { for (int i = ChildCount - 1; i >= 0; i--) { var state = GetChild(i); if (state == null) continue; if (state.ApplyFootIK) return true; } return false; } set { for (int i = ChildCount - 1; i >= 0; i--) { var state = GetChild(i); if (state == null) continue; state.ApplyFootIK = value; } } } /************************************************************************************************************************/ #endregion /************************************************************************************************************************/ #region Descriptions /************************************************************************************************************************/ #if UNITY_ASSERTIONS /// [Assert-Only] The Inspector display name of this node. /// Set using . public string DebugName { get; private set; } #endif /// The Inspector display name of this node. public override string ToString() { #if UNITY_ASSERTIONS if (!string.IsNullOrEmpty(DebugName)) return DebugName; #endif return base.ToString(); } /// [Assert-Conditional] /// Sets the Inspector display name of this node. returns the name. /// [System.Diagnostics.Conditional(Strings.Assertions)] public void SetDebugName(string name) { #if UNITY_ASSERTIONS DebugName = name; #endif } /************************************************************************************************************************/ /// Returns a detailed descrption of the current details of this node. public string GetDescription(string separator = "\n") { var text = ObjectPool.AcquireStringBuilder(); AppendDescription(text, separator); return text.ReleaseToString(); } /************************************************************************************************************************/ /// Appends a detailed descrption of the current details of this node. public void AppendDescription(StringBuilder text, string separator = "\n") { text.Append(ToString()); AppendDetails(text, separator); if (ChildCount > 0) { text.Append(separator).Append($"{nameof(ChildCount)}: ").Append(ChildCount); var indentedSeparator = separator + Strings.Indent; var i = 0; foreach (var child in this) { text.Append(separator).Append('[').Append(i++).Append("] "); if (child != null) child.AppendDescription(text, indentedSeparator); else text.Append("null"); } } } /************************************************************************************************************************/ /// Called by to append the details of this node. protected virtual void AppendDetails(StringBuilder text, string separator) { text.Append(separator).Append("Playable: "); if (_Playable.IsValid()) text.Append(_Playable.GetPlayableType()); else text.Append("Invalid"); text.Append(separator).Append($"{nameof(Index)}: ").Append(Index); var realSpeed = _Playable.IsValid() ? _Playable.GetSpeed() : _Speed; if (realSpeed == _Speed) { text.Append(separator).Append($"{nameof(Speed)}: ").Append(_Speed); } else { text.Append(separator).Append($"{nameof(Speed)} (Real): ").Append(_Speed) .Append(" (").Append(realSpeed).Append(')'); } text.Append(separator).Append($"{nameof(Weight)}: ").Append(Weight); if (Weight != TargetWeight) { text.Append(separator).Append($"{nameof(TargetWeight)}: ").Append(TargetWeight); text.Append(separator).Append($"{nameof(FadeSpeed)}: ").Append(FadeSpeed); } AppendIKDetails(text, separator, this); } /************************************************************************************************************************/ /// /// Appends the details of and /// . /// public static void AppendIKDetails(StringBuilder text, string separator, IPlayableWrapper node) { if (!node.Playable.IsValid()) return; text.Append(separator).Append("InverseKinematics: "); if (node.ApplyAnimatorIK) { text.Append("OnAnimatorIK"); if (node.ApplyFootIK) text.Append(", FootIK"); } else if (node.ApplyFootIK) { text.Append("FootIK"); } else { text.Append("None"); } } /************************************************************************************************************************/ #endregion /************************************************************************************************************************/ } }