1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054 |
- using System;
- using System.Collections;
- using System.Collections.Generic;
- using System.Text;
- using UnityEngine;
- using UnityEngine.Playables;
- using Object = UnityEngine.Object;
- namespace Animancer
- {
-
-
-
- public abstract class AnimancerNode : Key, IUpdatable, IEnumerable<AnimancerState>, IEnumerator, IPlayableWrapper
- {
-
- #region Playable
-
-
-
-
-
-
-
-
- protected internal Playable _Playable;
-
- Playable IPlayableWrapper.Playable => _Playable;
-
-
-
- public bool IsValid => _Playable.IsValid();
-
- #if UNITY_EDITOR
-
- internal bool _IsInspectorExpanded;
- #endif
-
-
-
- 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);
- }
-
- protected abstract void CreatePlayable(out Playable playable);
-
-
- public void DestroyPlayable()
- {
- if (_Playable.IsValid())
- Root._Graph.DestroyPlayable(_Playable);
- }
-
-
- public virtual void RecreatePlayable()
- {
- DestroyPlayable();
- CreatePlayable();
- }
-
- public void RecreatePlayableRecursive()
- {
- RecreatePlayable();
- for (int i = ChildCount - 1; i >= 0; i--)
- GetChild(i)?.RecreatePlayableRecursive();
- }
-
- #endregion
-
- #region Graph
-
-
- public AnimancerPlayable Root { get; internal set; }
-
-
- public abstract AnimancerLayer Layer { get; }
-
- public abstract IPlayableWrapper Parent { get; }
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- public int Index { get; internal set; } = int.MinValue;
-
-
- protected AnimancerNode()
- {
- #if UNITY_ASSERTIONS
- if (TraceConstructor)
- _ConstructorStackTrace = new System.Diagnostics.StackTrace(true);
- #endif
- }
-
- #if UNITY_ASSERTIONS
-
-
-
-
-
-
- public static bool TraceConstructor { get; set; }
-
-
-
-
- private System.Diagnostics.StackTrace _ConstructorStackTrace;
-
-
- ~AnimancerNode()
- {
- if (Root != null ||
- OptionalWarning.UnusedNode.IsDisabled())
- return;
- var name = DebugName;
- if (string.IsNullOrEmpty(name))
- {
-
- 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 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 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 Node: " + this +
- "\n Parent: " + parent);
- #endif
- _IsWeightDirty = true;
- if (_Weight != 0 || parent.KeepChildrenConnected)
- {
- ConnectToGraph();
- }
- else
- {
- Root.RequirePreUpdate(this);
- }
- }
-
-
- protected void RequireUpdate()
- {
- Root?.RequirePreUpdate(this);
- }
-
-
- void IUpdatable.Update()
- {
- if (_Playable.IsValid())
- {
- Update(out var needsMoreUpdates);
- if (needsMoreUpdates)
- return;
- }
- Root.CancelPreUpdate(this);
- }
-
-
-
-
-
-
-
- protected internal virtual void Update(out bool needsMoreUpdates)
- {
- UpdateFade(out needsMoreUpdates);
- ApplyWeight();
- }
-
-
-
-
-
-
-
-
- protected internal abstract bool IsPlayingAndNotEnding();
- bool IEnumerator.MoveNext() => IsPlayingAndNotEnding();
- object IEnumerator.Current => null;
- void IEnumerator.Reset() { }
-
- #endregion
-
- #region Children
-
-
-
-
- public virtual int ChildCount => 0;
-
-
- AnimancerNode IPlayableWrapper.GetChild(int index) => GetChild(index);
-
-
-
-
- public virtual AnimancerState GetChild(int index)
- => throw new NotSupportedException(this + " can't have children.");
-
-
- protected internal virtual void OnAddChild(AnimancerState state)
- {
- state.ClearParent();
- throw new NotSupportedException(this + " can't have children.");
- }
-
-
- protected internal virtual void OnRemoveChild(AnimancerState state)
- {
- state.ClearParent();
- throw new NotSupportedException(this + " can't have children.");
- }
-
-
-
- protected void OnAddChild(IList<AnimancerState> states, AnimancerState state)
- {
- var index = state.Index;
- if (states[index] != null)
- {
- state.ClearParent();
- 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);
- }
-
-
-
-
- public virtual bool KeepChildrenConnected => false;
-
-
-
- internal void ConnectAllChildrenToGraph()
- {
- if (!Parent.Playable.GetInput(Index).IsValid())
- ConnectToGraph();
- for (int i = ChildCount - 1; i >= 0; i--)
- GetChild(i)?.ConnectAllChildrenToGraph();
- }
-
-
-
-
- internal void DisconnectWeightlessChildrenFromGraph()
- {
- if (Weight == 0)
- DisconnectFromGraph();
- for (int i = ChildCount - 1; i >= 0; i--)
- GetChild(i)?.DisconnectWeightlessChildrenFromGraph();
- }
-
-
-
-
- public virtual FastEnumerator<AnimancerState> GetEnumerator() => default;
- IEnumerator<AnimancerState> IEnumerable<AnimancerState>.GetEnumerator() => GetEnumerator();
- IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
-
- #endregion
-
- #region Weight
-
-
- private float _Weight;
-
- private bool _IsWeightDirty = true;
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- public float Weight
- {
- get => _Weight;
- set
- {
- SetWeight(value);
- TargetWeight = value;
- FadeSpeed = 0;
- }
- }
-
-
-
-
-
-
-
-
-
- public void SetWeight(float value)
- {
- if (_Weight == value)
- return;
- #if UNITY_ASSERTIONS
- if (!(value >= 0) || value == float.PositiveInfinity)
- throw new ArgumentOutOfRangeException(nameof(value), value, $"{nameof(Weight)} must be a finite positive value");
- #endif
- _Weight = value;
- SetWeightDirty();
- }
-
- protected internal void SetWeightDirty()
- {
- _IsWeightDirty = true;
- RequireUpdate();
- }
-
-
-
-
- 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);
- }
-
-
-
-
-
- public float EffectiveWeight
- {
- get
- {
- var weight = Weight;
- var parent = Parent;
- while (parent != null)
- {
- weight *= parent.Weight;
- parent = parent.Parent;
- }
- return weight;
- }
- }
-
- #endregion
-
- #region Fading
-
-
-
-
-
- public float TargetWeight { get; set; }
-
-
- public float FadeSpeed { get; set; }
-
-
-
-
-
-
-
-
-
-
-
- public void StartFade(float targetWeight)
- => StartFade(targetWeight, AnimancerPlayable.DefaultFadeDuration);
-
-
-
-
-
-
-
-
-
-
-
-
-
- public void StartFade(float targetWeight, float fadeDuration)
- {
- TargetWeight = targetWeight;
- if (targetWeight == Weight)
- {
- if (targetWeight == 0)
- {
- Stop();
- }
- else
- {
- FadeSpeed = 0;
- OnStartFade();
- }
- return;
- }
-
- if (fadeDuration <= 0)
- {
- FadeSpeed = float.PositiveInfinity;
- }
- else
- {
- FadeSpeed = Math.Abs(Weight - targetWeight) / fadeDuration;
- }
- OnStartFade();
- RequireUpdate();
- }
-
-
- protected internal abstract void OnStartFade();
-
-
-
-
-
- public virtual void Stop()
- {
- Weight = 0;
- }
-
-
-
-
-
- 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 Inverse Kinematics
-
-
-
-
-
- public static bool ApplyParentAnimatorIK { get; set; } = true;
-
-
-
-
- public static bool ApplyParentFootIK { get; set; } = true;
-
-
-
-
-
-
-
-
- public virtual void CopyIKFlags(AnimancerNode node)
- {
- if (Root == null)
- return;
- if (ApplyParentAnimatorIK)
- {
- ApplyAnimatorIK = node.ApplyAnimatorIK;
- if (ApplyParentFootIK)
- ApplyFootIK = node.ApplyFootIK;
- }
- else if (ApplyParentFootIK)
- {
- ApplyFootIK = node.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 Speed
-
- private float _Speed = 1;
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- public float Speed
- {
- get => _Speed;
- set
- {
- #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
-
-
-
-
- protected virtual string UnsupportedSpeedMessage => null;
- #endif
-
-
-
-
-
- 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;
- }
- }
-
-
-
-
- public float EffectiveSpeed
- {
- get => Speed * ParentEffectiveSpeed;
- set => Speed = value / ParentEffectiveSpeed;
- }
-
- #endregion
-
- #region Descriptions
-
- #if UNITY_ASSERTIONS
-
-
- public string DebugName { get; private set; }
- #endif
-
- public override string ToString()
- {
- #if UNITY_ASSERTIONS
- if (!string.IsNullOrEmpty(DebugName))
- return DebugName;
- #endif
- return base.ToString();
- }
-
-
-
- [System.Diagnostics.Conditional(Strings.Assertions)]
- public void SetDebugName(string name)
- {
- #if UNITY_ASSERTIONS
- DebugName = name;
- #endif
- }
-
-
- public string GetDescription(string separator = "\n")
- {
- var text = ObjectPool.AcquireStringBuilder();
- AppendDescription(text, separator);
- return text.ReleaseToString();
- }
-
-
- 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("] ");
- child.AppendDescription(text, indentedSeparator);
- }
- }
- }
-
-
- 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);
- }
-
-
-
-
-
- public static void AppendIKDetails(StringBuilder text, string separator, IPlayableWrapper node)
- {
- 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
-
- }
- }
|