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.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  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 and initialize the Solver.
  66. /// </summary>
  67. protected virtual void OnValidate()
  68. {
  69. m_Weight = Mathf.Clamp01(m_Weight);
  70. if (!isValid)
  71. Initialize();
  72. }
  73. bool Validate()
  74. {
  75. for (var i = 0; i < GetChainCount(); ++i)
  76. {
  77. var chain = GetChain(i);
  78. if (!chain.isValid)
  79. return false;
  80. }
  81. return DoValidate();
  82. }
  83. bool HasTargets()
  84. {
  85. for (var i = 0; i < GetChainCount(); ++i)
  86. {
  87. var chain = GetChain(i);
  88. if (chain.target == null)
  89. return false;
  90. }
  91. return true;
  92. }
  93. /// <summary>
  94. /// Initializes the solver.
  95. /// </summary>
  96. public void Initialize()
  97. {
  98. DoInitialize();
  99. for (var i = 0; i < GetChainCount(); ++i)
  100. {
  101. var chain = GetChain(i);
  102. chain.Initialize();
  103. }
  104. }
  105. void Prepare()
  106. {
  107. var rootTransform = GetPlaneRootTransform();
  108. if (rootTransform != null)
  109. {
  110. m_Plane.normal = rootTransform.forward;
  111. m_Plane.distance = -Vector3.Dot(m_Plane.normal, rootTransform.position);
  112. }
  113. for (var i = 0; i < GetChainCount(); ++i)
  114. {
  115. var chain = GetChain(i);
  116. var constrainTargetRotation = constrainRotation && chain.target != null;
  117. if (m_SolveFromDefaultPose)
  118. chain.RestoreDefaultPose(constrainTargetRotation);
  119. }
  120. DoPrepare();
  121. }
  122. void PrepareEffectorPositions()
  123. {
  124. m_TargetPositions.Clear();
  125. for (var i = 0; i < GetChainCount(); ++i)
  126. {
  127. var chain = GetChain(i);
  128. if (chain.target)
  129. m_TargetPositions.Add(chain.target.position);
  130. }
  131. }
  132. /// <summary>
  133. /// Perform the Solver IK update.
  134. /// </summary>
  135. /// <param name="globalWeight">Weight for position solving.</param>
  136. public void UpdateIK(float globalWeight)
  137. {
  138. if (allChainsHaveTargets)
  139. {
  140. PrepareEffectorPositions();
  141. UpdateIK(m_TargetPositions, globalWeight);
  142. }
  143. }
  144. /// <summary>
  145. /// Perform the Solver IK update with specified target positions.
  146. /// </summary>
  147. /// <param name="targetPositions">Target positions.</param>
  148. /// <param name="globalWeight">Weight for position solving.</param>
  149. public void UpdateIK(List<Vector3> targetPositions, float globalWeight)
  150. {
  151. if (targetPositions.Count != chainCount)
  152. return;
  153. var finalWeight = globalWeight * weight;
  154. var weightValueChanged = Math.Abs(finalWeight - m_LastFinalWeight) > 0.0001f;
  155. m_LastFinalWeight = finalWeight;
  156. if (finalWeight == 0f && !weightValueChanged)
  157. return;
  158. if (!isValid)
  159. return;
  160. if (finalWeight < 1f)
  161. StoreLocalRotations();
  162. Prepare();
  163. DoUpdateIK(targetPositions);
  164. if (constrainRotation)
  165. {
  166. for (var i = 0; i < GetChainCount(); ++i)
  167. {
  168. var chain = GetChain(i);
  169. if (chain.target)
  170. chain.effector.rotation = chain.target.rotation;
  171. }
  172. }
  173. if (finalWeight < 1f)
  174. BlendFkToIk(finalWeight);
  175. }
  176. void StoreLocalRotations()
  177. {
  178. for (var i = 0; i < GetChainCount(); ++i)
  179. {
  180. var chain = GetChain(i);
  181. chain.StoreLocalRotations();
  182. }
  183. }
  184. void BlendFkToIk(float finalWeight)
  185. {
  186. for (var i = 0; i < GetChainCount(); ++i)
  187. {
  188. var chain = GetChain(i);
  189. var constrainTargetRotation = constrainRotation && chain.target != null;
  190. chain.BlendFkToIk(finalWeight, constrainTargetRotation);
  191. }
  192. }
  193. /// <summary>
  194. /// Override to return the IKChain2D at the given index.
  195. /// </summary>
  196. /// <param name="index">Index of the IKChain2D.</param>
  197. /// <returns></returns>
  198. public abstract IKChain2D GetChain(int index);
  199. /// <summary>
  200. /// Override to return the number of chains in the Solver.
  201. /// </summary>
  202. /// <returns>Number of chains in the solver.</returns>
  203. protected abstract int GetChainCount();
  204. /// <summary>
  205. /// Override to perform Solver IK update.
  206. /// </summary>
  207. /// <param name="targetPositions">Target position for the chain.</param>
  208. protected abstract void DoUpdateIK(List<Vector3> targetPositions);
  209. /// <summary>
  210. /// Override to perform custom validation.
  211. /// </summary>
  212. /// <returns>Returns true if the Solver is in a valid state. False otherwise.</returns>
  213. protected virtual bool DoValidate() => true;
  214. /// <summary>
  215. /// Override to initialize the solver.
  216. /// </summary>
  217. protected virtual void DoInitialize() { }
  218. /// <summary>
  219. /// Override to prepare the solver for update.
  220. /// </summary>
  221. protected virtual void DoPrepare() { }
  222. /// <summary>
  223. /// Override to return the root transform of the Solver. The default implementation returns the root transform of the first chain.
  224. /// </summary>
  225. /// <returns>Transform representing the root.</returns>
  226. protected virtual Transform GetPlaneRootTransform()
  227. {
  228. return chainCount > 0 ? GetChain(0).rootTransform : null;
  229. }
  230. /// <summary>
  231. /// Convert a world position coordinate to the solver's plane space.
  232. /// </summary>
  233. /// <param name="worldPosition">Vector3 representing world position</param>
  234. /// <returns>Converted position in solver's plane</returns>
  235. protected Vector3 GetPointOnSolverPlane(Vector3 worldPosition)
  236. {
  237. return GetPlaneRootTransform().InverseTransformPoint(m_Plane.ClosestPointOnPlane(worldPosition));
  238. }
  239. /// <summary>
  240. /// Convert a position from solver's plane to world coordinates.
  241. /// </summary>
  242. /// <param name="planePoint">Vector3 representing a position in the Solver's plane.</param>
  243. /// <returns>Converted position to world coordinates.</returns>
  244. protected Vector3 GetWorldPositionFromSolverPlanePoint(Vector2 planePoint)
  245. {
  246. return GetPlaneRootTransform().TransformPoint(planePoint);
  247. }
  248. /// <summary>
  249. /// Empty method. Implemented for the IPreviewable interface.
  250. /// </summary>
  251. public void OnPreviewUpdate() { }
  252. }
  253. }