DirectionalMixerState.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  1. // Animancer // https://kybernetik.com.au/animancer // Copyright 2022 Kybernetik //
  2. using System;
  3. using System.Text;
  4. using UnityEngine;
  5. namespace Animancer
  6. {
  7. /// <summary>[Pro-Only]
  8. /// An <see cref="AnimancerState"/> which blends an array of other states together based on a two dimensional
  9. /// parameter and thresholds using Polar Gradient Band Interpolation.
  10. /// </summary>
  11. /// <remarks>
  12. /// This mixer type is similar to the 2D Freeform Directional Blend Type in Mecanim Blend Trees.
  13. /// <para></para>
  14. /// Documentation: <see href="https://kybernetik.com.au/animancer/docs/manual/blending/mixers">Mixers</see>
  15. /// </remarks>
  16. /// https://kybernetik.com.au/animancer/api/Animancer/DirectionalMixerState
  17. ///
  18. public class DirectionalMixerState : MixerState<Vector2>
  19. {
  20. /************************************************************************************************************************/
  21. /// <summary><see cref="MixerState{TParameter}.Parameter"/>.x.</summary>
  22. public float ParameterX
  23. {
  24. get => Parameter.x;
  25. set => Parameter = new Vector2(value, Parameter.y);
  26. }
  27. /// <summary><see cref="MixerState{TParameter}.Parameter"/>.y.</summary>
  28. public float ParameterY
  29. {
  30. get => Parameter.y;
  31. set => Parameter = new Vector2(Parameter.x, value);
  32. }
  33. /************************************************************************************************************************/
  34. /// <inheritdoc/>
  35. public override string GetParameterError(Vector2 value)
  36. => value.IsFinite() ? null : $"value.x and value.y {Strings.MustBeFinite}";
  37. /************************************************************************************************************************/
  38. /// <summary>Precalculated magnitudes of all thresholds to speed up the recalculation of weights.</summary>
  39. private float[] _ThresholdMagnitudes;
  40. /// <summary>Precalculated values to speed up the recalculation of weights.</summary>
  41. private Vector2[][] _BlendFactors;
  42. /// <summary>Indicates whether the <see cref="_BlendFactors"/> need to be recalculated.</summary>
  43. private bool _BlendFactorsDirty = true;
  44. /// <summary>The multiplier that controls how much an angle (in radians) is worth compared to normalized distance.</summary>
  45. private const float AngleFactor = 2;
  46. /************************************************************************************************************************/
  47. /// <summary>
  48. /// Called whenever the thresholds are changed. Indicates that the internal blend factors need to be
  49. /// recalculated and calls <see cref="ForceRecalculateWeights"/>.
  50. /// </summary>
  51. public override void OnThresholdsChanged()
  52. {
  53. _BlendFactorsDirty = true;
  54. base.OnThresholdsChanged();
  55. }
  56. /************************************************************************************************************************/
  57. /// <summary>
  58. /// Recalculates the weights of all <see cref="MixerState.ChildStates"/> based on the current value of the
  59. /// <see cref="MixerState{TParameter}.Parameter"/> and the thresholds.
  60. /// </summary>
  61. protected override void ForceRecalculateWeights()
  62. {
  63. WeightsAreDirty = false;
  64. var childCount = ChildCount;
  65. if (childCount == 0)
  66. {
  67. return;
  68. }
  69. else if (childCount == 1)
  70. {
  71. var state = GetChild(0);
  72. state.Weight = 1;
  73. return;
  74. }
  75. CalculateBlendFactors(childCount);
  76. var parameterMagnitude = Parameter.magnitude;
  77. float totalWeight = 0;
  78. for (int i = 0; i < childCount; i++)
  79. {
  80. var state = GetChild(i);
  81. if (state == null)
  82. continue;
  83. var blendFactors = _BlendFactors[i];
  84. var thresholdI = GetThreshold(i);
  85. var magnitudeI = _ThresholdMagnitudes[i];
  86. // Convert the threshold to polar coordinates (distance, angle) and interpolate the weight based on those.
  87. var differenceIToParameter = parameterMagnitude - magnitudeI;
  88. var angleIToParameter = SignedAngle(thresholdI, Parameter) * AngleFactor;
  89. float weight = 1;
  90. for (int j = 0; j < childCount; j++)
  91. {
  92. if (j == i || GetChild(j) == null)
  93. continue;
  94. var magnitudeJ = _ThresholdMagnitudes[j];
  95. var averageMagnitude = (magnitudeJ + magnitudeI) * 0.5f;
  96. var polarIToParameter = new Vector2(
  97. differenceIToParameter / averageMagnitude,
  98. angleIToParameter);
  99. var newWeight = 1 - Vector2.Dot(polarIToParameter, blendFactors[j]);
  100. if (weight > newWeight)
  101. weight = newWeight;
  102. }
  103. if (weight < 0.01f)
  104. weight = 0;
  105. state.Weight = weight;
  106. totalWeight += weight;
  107. }
  108. NormalizeWeights(totalWeight);
  109. }
  110. /************************************************************************************************************************/
  111. private void CalculateBlendFactors(int childCount)
  112. {
  113. if (!_BlendFactorsDirty)
  114. return;
  115. _BlendFactorsDirty = false;
  116. // Resize the precalculated values.
  117. if (_BlendFactors == null || _BlendFactors.Length != childCount)
  118. {
  119. _ThresholdMagnitudes = new float[childCount];
  120. _BlendFactors = new Vector2[childCount][];
  121. for (int i = 0; i < childCount; i++)
  122. _BlendFactors[i] = new Vector2[childCount];
  123. }
  124. // Calculate the magnitude of each threshold.
  125. for (int i = 0; i < childCount; i++)
  126. {
  127. _ThresholdMagnitudes[i] = GetThreshold(i).magnitude;
  128. }
  129. // Calculate the blend factors between each combination of thresholds.
  130. for (int i = 0; i < childCount; i++)
  131. {
  132. var blendFactors = _BlendFactors[i];
  133. var thresholdI = GetThreshold(i);
  134. var magnitudeI = _ThresholdMagnitudes[i];
  135. var j = 0;// i + 1;
  136. for (; j < childCount; j++)
  137. {
  138. if (i == j)
  139. continue;
  140. var thresholdJ = GetThreshold(j);
  141. var magnitudeJ = _ThresholdMagnitudes[j];
  142. var averageMagnitude = (magnitudeI + magnitudeJ) * 0.5f;
  143. // Convert the thresholds to polar coordinates (distance, angle) and interpolate the weight based on those.
  144. var differenceIToJ = magnitudeJ - magnitudeI;
  145. var angleIToJ = SignedAngle(thresholdI, thresholdJ);
  146. var polarIToJ = new Vector2(
  147. differenceIToJ / averageMagnitude,
  148. angleIToJ * AngleFactor);
  149. polarIToJ *= 1f / polarIToJ.sqrMagnitude;
  150. // Each factor is used in [i][j] with it's opposite in [j][i].
  151. blendFactors[j] = polarIToJ;
  152. _BlendFactors[j][i] = -polarIToJ;
  153. }
  154. }
  155. }
  156. /************************************************************************************************************************/
  157. private static float SignedAngle(Vector2 a, Vector2 b)
  158. {
  159. // If either vector is exactly at the origin, the angle is 0.
  160. if ((a.x == 0 && a.y == 0) || (b.x == 0 && b.y == 0))
  161. {
  162. // Due to floating point error the formula below usually gives 0 but sometimes Pi,
  163. // which screws up our other calculations so we need it to always be 0 properly.
  164. return 0;
  165. }
  166. return Mathf.Atan2(
  167. a.x * b.y - a.y * b.x,
  168. a.x * b.x + a.y * b.y);
  169. }
  170. /************************************************************************************************************************/
  171. /// <inheritdoc/>
  172. public override void AppendParameter(StringBuilder text, Vector2 parameter)
  173. {
  174. text.Append('(')
  175. .Append(parameter.x)
  176. .Append(", ")
  177. .Append(parameter.y)
  178. .Append(')');
  179. }
  180. /************************************************************************************************************************/
  181. #region Inspector
  182. /************************************************************************************************************************/
  183. /// <inheritdoc/>
  184. protected override int ParameterCount => 2;
  185. /// <inheritdoc/>
  186. protected override string GetParameterName(int index)
  187. {
  188. switch (index)
  189. {
  190. case 0: return "Parameter X";
  191. case 1: return "Parameter Y";
  192. default: throw new ArgumentOutOfRangeException(nameof(index));
  193. }
  194. }
  195. /// <inheritdoc/>
  196. protected override AnimatorControllerParameterType GetParameterType(int index) => AnimatorControllerParameterType.Float;
  197. /// <inheritdoc/>
  198. protected override object GetParameterValue(int index)
  199. {
  200. switch (index)
  201. {
  202. case 0: return ParameterX;
  203. case 1: return ParameterY;
  204. default: throw new ArgumentOutOfRangeException(nameof(index));
  205. }
  206. }
  207. /// <inheritdoc/>
  208. protected override void SetParameterValue(int index, object value)
  209. {
  210. switch (index)
  211. {
  212. case 0: ParameterX = (float)value; break;
  213. case 1: ParameterY = (float)value; break;
  214. default: throw new ArgumentOutOfRangeException(nameof(index));
  215. }
  216. }
  217. /************************************************************************************************************************/
  218. #endregion
  219. /************************************************************************************************************************/
  220. }
  221. }