DirectionalMixerState.cs 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236
  1. // Animancer // https://kybernetik.com.au/animancer // Copyright 2018-2024 Kybernetik //
  2. using System;
  3. using UnityEngine;
  4. namespace Animancer
  5. {
  6. /// <summary>[Pro-Only]
  7. /// An <see cref="AnimancerState"/> which blends an array of other states together based on a two dimensional
  8. /// parameter and thresholds using Polar Gradient Band Interpolation.
  9. /// </summary>
  10. /// <remarks>
  11. /// This mixer type is similar to the 2D Freeform Directional Blend Type in Mecanim Blend Trees.
  12. /// <para></para>
  13. /// <strong>Documentation:</strong>
  14. /// <see href="https://kybernetik.com.au/animancer/docs/manual/blending/mixers">
  15. /// Mixers</see>
  16. /// </remarks>
  17. /// https://kybernetik.com.au/animancer/api/Animancer/DirectionalMixerState
  18. ///
  19. public class DirectionalMixerState : Vector2MixerState,
  20. ICopyable<DirectionalMixerState>
  21. {
  22. /************************************************************************************************************************/
  23. /// <summary>Precalculated magnitudes of all thresholds to speed up the recalculation of weights.</summary>
  24. private float[] _ThresholdMagnitudes;
  25. /// <summary>Precalculated values to speed up the recalculation of weights.</summary>
  26. private Vector2[][] _BlendFactors;
  27. /// <summary>Indicates whether the <see cref="_BlendFactors"/> need to be recalculated.</summary>
  28. private bool _BlendFactorsAreDirty = true;
  29. /// <summary>The multiplier that controls how much an angle (in radians) is worth compared to normalized distance.</summary>
  30. private const float AngleFactor = 2;
  31. /************************************************************************************************************************/
  32. /// <summary>
  33. /// Called whenever the thresholds are changed. Indicates that the internal blend factors need to be
  34. /// recalculated and triggers weight recalculation.
  35. /// </summary>
  36. public override void OnThresholdsChanged()
  37. {
  38. _BlendFactorsAreDirty = true;
  39. base.OnThresholdsChanged();
  40. }
  41. /************************************************************************************************************************/
  42. /// <inheritdoc/>
  43. protected override void ForceRecalculateWeights()
  44. {
  45. var childCount = ChildCount;
  46. if (childCount == 0)
  47. {
  48. return;
  49. }
  50. else if (childCount == 1)
  51. {
  52. var state = ChildStates[0];
  53. Playable.SetChildWeight(state, 1);
  54. return;
  55. }
  56. CalculateBlendFactors(childCount);
  57. var parameterMagnitude = Parameter.magnitude;
  58. float totalWeight = 0;
  59. var weights = GetTemporaryFloatArray(childCount);
  60. for (int i = 0; i < childCount; i++)
  61. {
  62. var state = ChildStates[i];
  63. var blendFactors = _BlendFactors[i];
  64. var thresholdI = GetThreshold(i);
  65. var magnitudeI = _ThresholdMagnitudes[i];
  66. // Convert the threshold to polar coordinates (distance, angle)
  67. // and interpolate the weight based on those.
  68. var differenceIToParameter = parameterMagnitude - magnitudeI;
  69. var angleIToParameter = SignedAngle(thresholdI, Parameter) * AngleFactor;
  70. float weight = 1;
  71. for (int j = 0; j < childCount; j++)
  72. {
  73. if (j == i)
  74. continue;
  75. var magnitudeJ = _ThresholdMagnitudes[j];
  76. var averageMagnitude = (magnitudeJ + magnitudeI) * 0.5f;
  77. var polarIToParameter = new Vector2(
  78. differenceIToParameter / averageMagnitude,
  79. angleIToParameter);
  80. var newWeight = 1 - Vector2.Dot(polarIToParameter, blendFactors[j]);
  81. if (weight > newWeight)
  82. weight = newWeight;
  83. }
  84. if (weight < 0.01f)
  85. weight = 0;
  86. weights[i] = weight;
  87. totalWeight += weight;
  88. }
  89. NormalizeAndApplyWeights(totalWeight, weights);
  90. }
  91. /************************************************************************************************************************/
  92. private void CalculateBlendFactors(int childCount)
  93. {
  94. if (!_BlendFactorsAreDirty)
  95. return;
  96. _BlendFactorsAreDirty = false;
  97. // Resize the precalculated values.
  98. if (_BlendFactors == null || _BlendFactors.Length != childCount)
  99. {
  100. _ThresholdMagnitudes = new float[childCount];
  101. _BlendFactors = new Vector2[childCount][];
  102. for (int i = 0; i < childCount; i++)
  103. _BlendFactors[i] = new Vector2[childCount];
  104. }
  105. // Calculate the magnitude of each threshold.
  106. for (int i = 0; i < childCount; i++)
  107. {
  108. _ThresholdMagnitudes[i] = GetThreshold(i).magnitude;
  109. }
  110. // Calculate the blend factors between each combination of thresholds.
  111. for (int i = 0; i < childCount; i++)
  112. {
  113. var blendFactors = _BlendFactors[i];
  114. var thresholdI = GetThreshold(i);
  115. var magnitudeI = _ThresholdMagnitudes[i];
  116. var j = 0;// i + 1;
  117. for (; j < childCount; j++)
  118. {
  119. if (i == j)
  120. continue;
  121. var thresholdJ = GetThreshold(j);
  122. var magnitudeJ = _ThresholdMagnitudes[j];
  123. #if UNITY_ASSERTIONS
  124. if (thresholdI == thresholdJ)
  125. {
  126. MarkAsUsed(this);
  127. throw new ArgumentException(
  128. $"Mixer has multiple identical thresholds.\n{this.GetDescription()}");
  129. }
  130. #endif
  131. var averageMagnitude = (magnitudeI + magnitudeJ) * 0.5f;
  132. // Convert the thresholds to polar coordinates (distance, angle) and interpolate the weight based on those.
  133. var differenceIToJ = magnitudeJ - magnitudeI;
  134. var angleIToJ = SignedAngle(thresholdI, thresholdJ);
  135. var polarIToJ = new Vector2(
  136. differenceIToJ / averageMagnitude,
  137. angleIToJ * AngleFactor);
  138. polarIToJ /= polarIToJ.sqrMagnitude;
  139. // Each factor is used in [i][j] with it's opposite in [j][i].
  140. blendFactors[j] = polarIToJ;
  141. _BlendFactors[j][i] = -polarIToJ;
  142. }
  143. }
  144. }
  145. /************************************************************************************************************************/
  146. private static float SignedAngle(Vector2 a, Vector2 b)
  147. {
  148. // If either vector is exactly at the origin, the angle is 0.
  149. if ((a.x == 0 && a.y == 0) || (b.x == 0 && b.y == 0))
  150. {
  151. // Due to floating point error the formula below usually gives 0 but sometimes Pi,
  152. // which screws up our other calculations so we need it to always be 0 properly.
  153. return 0;
  154. }
  155. return Mathf.Atan2(
  156. a.x * b.y - a.y * b.x,
  157. a.x * b.x + a.y * b.y);
  158. }
  159. /************************************************************************************************************************/
  160. /// <inheritdoc/>
  161. public override AnimancerState Clone(CloneContext context)
  162. {
  163. var clone = new DirectionalMixerState();
  164. clone.CopyFrom(this, context);
  165. return clone;
  166. }
  167. /************************************************************************************************************************/
  168. /// <inheritdoc/>
  169. public sealed override void CopyFrom(Vector2MixerState copyFrom, CloneContext context)
  170. => this.CopyFromBase(copyFrom, context);
  171. /// <inheritdoc/>
  172. public virtual void CopyFrom(DirectionalMixerState copyFrom, CloneContext context)
  173. {
  174. _ThresholdMagnitudes = copyFrom._ThresholdMagnitudes;
  175. _BlendFactorsAreDirty = copyFrom._BlendFactorsAreDirty;
  176. if (!_BlendFactorsAreDirty)
  177. _BlendFactors = copyFrom._BlendFactors;
  178. base.CopyFrom(copyFrom, context);
  179. }
  180. /************************************************************************************************************************/
  181. }
  182. }