Nessuna descrizione
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

Solver2D.cs 9.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  1. using System;
  2. using System.Collections.Generic;
  3. using UnityEngine.Scripting.APIUpdating;
  4. using UnityEngine.Serialization;
  5. using UnityEngine.U2D.Common;
  6. namespace UnityEngine.U2D.IK
  7. {
  8. /// <summary>
  9. /// Abstract class for implementing a 2D IK Solver.
  10. /// </summary>
  11. [MovedFrom("UnityEngine.Experimental.U2D.IK")]
  12. public abstract class Solver2D : MonoBehaviour, IPreviewable
  13. {
  14. [SerializeField]
  15. bool m_ConstrainRotation = true;
  16. [FormerlySerializedAs("m_RestoreDefaultPose")]
  17. [SerializeField]
  18. bool m_SolveFromDefaultPose = true;
  19. [SerializeField]
  20. [Range(0f, 1f)]
  21. float m_Weight = 1f;
  22. Plane m_Plane;
  23. List<Vector3> m_TargetPositions = new List<Vector3>();
  24. /// <summary>
  25. /// Used to evaluate if Solver2D needs to be updated.
  26. /// </summary>
  27. float m_LastFinalWeight;
  28. /// <summary>
  29. /// Returns the number of IKChain2D in the solver.
  30. /// </summary>
  31. public int chainCount => GetChainCount();
  32. /// <summary>
  33. /// Gets and sets the rotation constrain property.
  34. /// </summary>
  35. public bool constrainRotation
  36. {
  37. get => m_ConstrainRotation;
  38. set => m_ConstrainRotation = value;
  39. }
  40. /// <summary>
  41. /// Get and set restoring default pose before the update.
  42. /// </summary>
  43. public bool solveFromDefaultPose
  44. {
  45. get => m_SolveFromDefaultPose;
  46. set => m_SolveFromDefaultPose = value;
  47. }
  48. /// <summary>
  49. /// Returns true if the Solver2D is in a valid state.
  50. /// </summary>
  51. public bool isValid => Validate();
  52. /// <summary>
  53. /// Returns true if all chains in the Solver have a target.
  54. /// </summary>
  55. public bool allChainsHaveTargets => HasTargets();
  56. /// <summary>
  57. /// Get and Set Solver weights.
  58. /// </summary>
  59. public float weight
  60. {
  61. get => m_Weight;
  62. set => m_Weight = Mathf.Clamp01(value);
  63. }
  64. /// <summary>
  65. /// Validate new values set from the Inspector.
  66. /// </summary>
  67. protected virtual void OnValidate()
  68. {
  69. m_Weight = Mathf.Clamp01(m_Weight);
  70. }
  71. bool Validate()
  72. {
  73. for (var i = 0; i < GetChainCount(); ++i)
  74. {
  75. var chain = GetChain(i);
  76. if (!chain.isValid)
  77. return false;
  78. }
  79. return DoValidate();
  80. }
  81. bool HasTargets()
  82. {
  83. for (var i = 0; i < GetChainCount(); ++i)
  84. {
  85. var chain = GetChain(i);
  86. if (chain.target == null)
  87. return false;
  88. }
  89. return true;
  90. }
  91. /// <summary>
  92. /// Initializes the solver.
  93. /// </summary>
  94. public void Initialize()
  95. {
  96. DoInitialize();
  97. for (var i = 0; i < GetChainCount(); ++i)
  98. {
  99. var chain = GetChain(i);
  100. chain.Initialize();
  101. }
  102. }
  103. void Prepare()
  104. {
  105. var rootTransform = GetPlaneRootTransform();
  106. if (rootTransform != null)
  107. {
  108. m_Plane.normal = rootTransform.forward;
  109. m_Plane.distance = -Vector3.Dot(m_Plane.normal, rootTransform.position);
  110. }
  111. for (var i = 0; i < GetChainCount(); ++i)
  112. {
  113. var chain = GetChain(i);
  114. var constrainTargetRotation = constrainRotation && chain.target != null;
  115. if (m_SolveFromDefaultPose)
  116. chain.RestoreDefaultPose(constrainTargetRotation);
  117. }
  118. DoPrepare();
  119. }
  120. void PrepareEffectorPositions()
  121. {
  122. m_TargetPositions.Clear();
  123. for (var i = 0; i < GetChainCount(); ++i)
  124. {
  125. var chain = GetChain(i);
  126. if (chain.target)
  127. m_TargetPositions.Add(chain.target.position);
  128. }
  129. }
  130. /// <summary>
  131. /// Perform the Solver IK update.
  132. /// </summary>
  133. /// <param name="globalWeight">Weight for position solving.</param>
  134. public void UpdateIK(float globalWeight)
  135. {
  136. if (allChainsHaveTargets)
  137. {
  138. PrepareEffectorPositions();
  139. UpdateIK(m_TargetPositions, globalWeight);
  140. }
  141. }
  142. /// <summary>
  143. /// Perform the Solver IK update with specified target positions.
  144. /// </summary>
  145. /// <param name="targetPositions">Target positions.</param>
  146. /// <param name="globalWeight">Weight for position solving.</param>
  147. public void UpdateIK(List<Vector3> targetPositions, float globalWeight)
  148. {
  149. if (targetPositions.Count != chainCount)
  150. return;
  151. var finalWeight = globalWeight * weight;
  152. var weightValueChanged = Math.Abs(finalWeight - m_LastFinalWeight) > 0.0001f;
  153. m_LastFinalWeight = finalWeight;
  154. if (finalWeight == 0f && !weightValueChanged)
  155. return;
  156. if (!isValid)
  157. return;
  158. if (finalWeight < 1f)
  159. StoreLocalRotations();
  160. Prepare();
  161. DoUpdateIK(targetPositions);
  162. if (constrainRotation)
  163. {
  164. for (var i = 0; i < GetChainCount(); ++i)
  165. {
  166. var chain = GetChain(i);
  167. if (chain.target)
  168. chain.effector.rotation = chain.target.rotation;
  169. }
  170. }
  171. if (finalWeight < 1f)
  172. BlendFkToIk(finalWeight);
  173. }
  174. void StoreLocalRotations()
  175. {
  176. for (var i = 0; i < GetChainCount(); ++i)
  177. {
  178. var chain = GetChain(i);
  179. chain.StoreLocalRotations();
  180. }
  181. }
  182. void BlendFkToIk(float finalWeight)
  183. {
  184. for (var i = 0; i < GetChainCount(); ++i)
  185. {
  186. var chain = GetChain(i);
  187. var constrainTargetRotation = constrainRotation && chain.target != null;
  188. chain.BlendFkToIk(finalWeight, constrainTargetRotation);
  189. }
  190. }
  191. /// <summary>
  192. /// Override to return the IKChain2D at the given index.
  193. /// </summary>
  194. /// <param name="index">Index of the IKChain2D.</param>
  195. /// <returns></returns>
  196. public abstract IKChain2D GetChain(int index);
  197. /// <summary>
  198. /// Override to return the number of chains in the Solver.
  199. /// </summary>
  200. /// <returns>Number of chains in the solver.</returns>
  201. protected abstract int GetChainCount();
  202. /// <summary>
  203. /// Override to perform Solver IK update.
  204. /// </summary>
  205. /// <param name="targetPositions">Target position for the chain.</param>
  206. protected abstract void DoUpdateIK(List<Vector3> targetPositions);
  207. /// <summary>
  208. /// Override to perform custom validation.
  209. /// </summary>
  210. /// <returns>Returns true if the Solver is in a valid state. False otherwise.</returns>
  211. protected virtual bool DoValidate() => true;
  212. /// <summary>
  213. /// Override to initialize the solver.
  214. /// </summary>
  215. protected virtual void DoInitialize() { }
  216. /// <summary>
  217. /// Override to prepare the solver for update.
  218. /// </summary>
  219. protected virtual void DoPrepare() { }
  220. /// <summary>
  221. /// Override to return the root transform of the Solver. The default implementation returns the root transform of the first chain.
  222. /// </summary>
  223. /// <returns>Transform representing the root.</returns>
  224. protected virtual Transform GetPlaneRootTransform()
  225. {
  226. return chainCount > 0 ? GetChain(0).rootTransform : null;
  227. }
  228. /// <summary>
  229. /// Convert a world position coordinate to the solver's plane space.
  230. /// </summary>
  231. /// <param name="worldPosition">Vector3 representing world position</param>
  232. /// <returns>Converted position in solver's plane</returns>
  233. protected Vector3 GetPointOnSolverPlane(Vector3 worldPosition)
  234. {
  235. return GetPlaneRootTransform().InverseTransformPoint(m_Plane.ClosestPointOnPlane(worldPosition));
  236. }
  237. /// <summary>
  238. /// Convert a position from solver's plane to world coordinates.
  239. /// </summary>
  240. /// <param name="planePoint">Vector3 representing a position in the Solver's plane.</param>
  241. /// <returns>Converted position to world coordinates.</returns>
  242. protected Vector3 GetWorldPositionFromSolverPlanePoint(Vector2 planePoint)
  243. {
  244. return GetPlaneRootTransform().TransformPoint(planePoint);
  245. }
  246. /// <summary>
  247. /// Empty method. Implemented for the IPreviewable interface.
  248. /// </summary>
  249. public void OnPreviewUpdate() { }
  250. }
  251. }