IkConstraint.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  1. /******************************************************************************
  2. * Spine Runtimes License Agreement
  3. * Last updated January 1, 2020. Replaces all prior versions.
  4. *
  5. * Copyright (c) 2013-2020, Esoteric Software LLC
  6. *
  7. * Integration of the Spine Runtimes into software or otherwise creating
  8. * derivative works of the Spine Runtimes is permitted under the terms and
  9. * conditions of Section 2 of the Spine Editor License Agreement:
  10. * http://esotericsoftware.com/spine-editor-license
  11. *
  12. * Otherwise, it is permitted to integrate the Spine Runtimes into software
  13. * or otherwise create derivative works of the Spine Runtimes (collectively,
  14. * "Products"), provided that each user of the Products must obtain their own
  15. * Spine Editor license and redistribution of the Products in any form must
  16. * include this license and copyright notice.
  17. *
  18. * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY
  19. * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  20. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  21. * DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY
  22. * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  23. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES,
  24. * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND
  25. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  26. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  27. * THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  28. *****************************************************************************/
  29. using System;
  30. namespace Spine {
  31. /// <summary>
  32. /// <para>
  33. /// Stores the current pose for an IK constraint. An IK constraint adjusts the rotation of 1 or 2 constrained bones so the tip of
  34. /// the last bone is as close to the target bone as possible.</para>
  35. /// <para>
  36. /// See <a href="http://esotericsoftware.com/spine-ik-constraints">IK constraints</a> in the Spine User Guide.</para>
  37. /// </summary>
  38. public class IkConstraint : IUpdatable {
  39. internal IkConstraintData data;
  40. internal ExposedList<Bone> bones = new ExposedList<Bone>();
  41. internal Bone target;
  42. internal int bendDirection;
  43. internal bool compress, stretch;
  44. internal float mix = 1, softness;
  45. internal bool active;
  46. public IkConstraint (IkConstraintData data, Skeleton skeleton) {
  47. if (data == null) throw new ArgumentNullException("data", "data cannot be null.");
  48. if (skeleton == null) throw new ArgumentNullException("skeleton", "skeleton cannot be null.");
  49. this.data = data;
  50. mix = data.mix;
  51. softness = data.softness;
  52. bendDirection = data.bendDirection;
  53. compress = data.compress;
  54. stretch = data.stretch;
  55. bones = new ExposedList<Bone>(data.bones.Count);
  56. foreach (BoneData boneData in data.bones)
  57. bones.Add(skeleton.FindBone(boneData.name));
  58. target = skeleton.FindBone(data.target.name);
  59. }
  60. /// <summary>Copy constructor.</summary>
  61. public IkConstraint (IkConstraint constraint, Skeleton skeleton) {
  62. if (constraint == null) throw new ArgumentNullException("constraint cannot be null.");
  63. if (skeleton == null) throw new ArgumentNullException("skeleton cannot be null.");
  64. data = constraint.data;
  65. bones = new ExposedList<Bone>(constraint.Bones.Count);
  66. foreach (Bone bone in constraint.Bones)
  67. bones.Add(skeleton.Bones.Items[bone.data.index]);
  68. target = skeleton.Bones.Items[constraint.target.data.index];
  69. mix = constraint.mix;
  70. softness = constraint.softness;
  71. bendDirection = constraint.bendDirection;
  72. compress = constraint.compress;
  73. stretch = constraint.stretch;
  74. }
  75. /// <summary>Applies the constraint to the constrained bones.</summary>
  76. public void Apply () {
  77. Update();
  78. }
  79. public void Update () {
  80. Bone target = this.target;
  81. ExposedList<Bone> bones = this.bones;
  82. switch (bones.Count) {
  83. case 1:
  84. Apply(bones.Items[0], target.worldX, target.worldY, compress, stretch, data.uniform, mix);
  85. break;
  86. case 2:
  87. Apply(bones.Items[0], bones.Items[1], target.worldX, target.worldY, bendDirection, stretch, softness, mix);
  88. break;
  89. }
  90. }
  91. /// <summary>The bones that will be modified by this IK constraint.</summary>
  92. public ExposedList<Bone> Bones {
  93. get { return bones; }
  94. }
  95. /// <summary>The bone that is the IK target.</summary>
  96. public Bone Target {
  97. get { return target; }
  98. set { target = value; }
  99. }
  100. /// <summary>A percentage (0-1) that controls the mix between the constrained and unconstrained rotations.</summary>
  101. public float Mix {
  102. get { return mix; }
  103. set { mix = value; }
  104. }
  105. ///<summary>For two bone IK, the distance from the maximum reach of the bones that rotation will slow.</summary>
  106. public float Softness {
  107. get { return softness; }
  108. set { softness = value; }
  109. }
  110. /// <summary>Controls the bend direction of the IK bones, either 1 or -1.</summary>
  111. public int BendDirection {
  112. get { return bendDirection; }
  113. set { bendDirection = value; }
  114. }
  115. /// <summary>
  116. /// When true and only a single bone is being constrained, if the target is too close, the bone is scaled to reach it.</summary>
  117. public bool Compress {
  118. get { return compress; }
  119. set { compress = value; }
  120. }
  121. /// <summary>
  122. /// When true, if the target is out of range, the parent bone is scaled to reach it. If more than one bone is being constrained
  123. /// and the parent bone has local nonuniform scale, stretch is not applied.</summary>
  124. public bool Stretch {
  125. get { return stretch; }
  126. set { stretch = value; }
  127. }
  128. public bool Active {
  129. get { return active; }
  130. }
  131. /// <summary>The IK constraint's setup pose data.</summary>
  132. public IkConstraintData Data {
  133. get { return data; }
  134. }
  135. override public string ToString () {
  136. return data.name;
  137. }
  138. /// <summary>Applies 1 bone IK. The target is specified in the world coordinate system.</summary>
  139. static public void Apply (Bone bone, float targetX, float targetY, bool compress, bool stretch, bool uniform,
  140. float alpha) {
  141. if (!bone.appliedValid) bone.UpdateAppliedTransform();
  142. Bone p = bone.parent;
  143. float pa = p.a, pb = p.b, pc = p.c, pd = p.d;
  144. float rotationIK = -bone.ashearX - bone.arotation;
  145. float tx = 0, ty = 0;
  146. switch(bone.data.transformMode) {
  147. case TransformMode.OnlyTranslation:
  148. tx = targetX - bone.worldX;
  149. ty = targetY - bone.worldY;
  150. break;
  151. case TransformMode.NoRotationOrReflection: {
  152. float s = Math.Abs(pa * pd - pb * pc) / (pa * pa + pc * pc);
  153. float sa = pa / bone.skeleton.ScaleX;
  154. float sc = pc / bone.skeleton.ScaleY;
  155. pb = -sc * s * bone.skeleton.ScaleX;
  156. pd = sa * s * bone.skeleton.ScaleY;
  157. rotationIK += (float)Math.Atan2(pc, pa) * MathUtils.RadDeg;
  158. goto default; // Fall through.
  159. }
  160. default: {
  161. float x = targetX - p.worldX, y = targetY - p.worldY;
  162. float d = pa * pd - pb * pc;
  163. tx = (x * pd - y * pb) / d - bone.ax;
  164. ty = (y * pa - x * pc) / d - bone.ay;
  165. break;
  166. }
  167. }
  168. rotationIK += (float)Math.Atan2(ty, tx) * MathUtils.RadDeg;
  169. if (bone.ascaleX < 0) rotationIK += 180;
  170. if (rotationIK > 180)
  171. rotationIK -= 360;
  172. else if (rotationIK < -180) //
  173. rotationIK += 360;
  174. float sx = bone.ascaleX, sy = bone.ascaleY;
  175. if (compress || stretch) {
  176. switch (bone.data.transformMode) {
  177. case TransformMode.NoScale:
  178. tx = targetX - bone.worldX;
  179. ty = targetY - bone.worldY;
  180. break;
  181. case TransformMode.NoScaleOrReflection:
  182. tx = targetX - bone.worldX;
  183. ty = targetY - bone.worldY;
  184. break;
  185. }
  186. float b = bone.data.length * sx, dd = (float)Math.Sqrt(tx * tx + ty * ty);
  187. if ((compress && dd < b) || (stretch && dd > b) && b > 0.0001f) {
  188. float s = (dd / b - 1) * alpha + 1;
  189. sx *= s;
  190. if (uniform) sy *= s;
  191. }
  192. }
  193. bone.UpdateWorldTransform(bone.ax, bone.ay, bone.arotation + rotationIK * alpha, sx, sy, bone.ashearX, bone.ashearY);
  194. }
  195. /// <summary>Applies 2 bone IK. The target is specified in the world coordinate system.</summary>
  196. /// <param name="child">A direct descendant of the parent bone.</param>
  197. static public void Apply (Bone parent, Bone child, float targetX, float targetY, int bendDir, bool stretch, float softness,
  198. float alpha) {
  199. if (alpha == 0) {
  200. child.UpdateWorldTransform();
  201. return;
  202. }
  203. if (!parent.appliedValid) parent.UpdateAppliedTransform();
  204. if (!child.appliedValid) child.UpdateAppliedTransform();
  205. float px = parent.ax, py = parent.ay, psx = parent.ascaleX, sx = psx, psy = parent.ascaleY, csx = child.ascaleX;
  206. int os1, os2, s2;
  207. if (psx < 0) {
  208. psx = -psx;
  209. os1 = 180;
  210. s2 = -1;
  211. } else {
  212. os1 = 0;
  213. s2 = 1;
  214. }
  215. if (psy < 0) {
  216. psy = -psy;
  217. s2 = -s2;
  218. }
  219. if (csx < 0) {
  220. csx = -csx;
  221. os2 = 180;
  222. } else
  223. os2 = 0;
  224. float cx = child.ax, cy, cwx, cwy, a = parent.a, b = parent.b, c = parent.c, d = parent.d;
  225. bool u = Math.Abs(psx - psy) <= 0.0001f;
  226. if (!u) {
  227. cy = 0;
  228. cwx = a * cx + parent.worldX;
  229. cwy = c * cx + parent.worldY;
  230. } else {
  231. cy = child.ay;
  232. cwx = a * cx + b * cy + parent.worldX;
  233. cwy = c * cx + d * cy + parent.worldY;
  234. }
  235. Bone pp = parent.parent;
  236. a = pp.a;
  237. b = pp.b;
  238. c = pp.c;
  239. d = pp.d;
  240. float id = 1 / (a * d - b * c), x = cwx - pp.worldX, y = cwy - pp.worldY;
  241. float dx = (x * d - y * b) * id - px, dy = (y * a - x * c) * id - py;
  242. float l1 = (float)Math.Sqrt(dx * dx + dy * dy), l2 = child.data.length * csx, a1, a2;
  243. if (l1 < 0.0001f) {
  244. Apply(parent, targetX, targetY, false, stretch, false, alpha);
  245. child.UpdateWorldTransform(cx, cy, 0, child.ascaleX, child.ascaleY, child.ashearX, child.ashearY);
  246. return;
  247. }
  248. x = targetX - pp.worldX;
  249. y = targetY - pp.worldY;
  250. float tx = (x * d - y * b) * id - px, ty = (y * a - x * c) * id - py;
  251. float dd = tx * tx + ty * ty;
  252. if (softness != 0) {
  253. softness *= psx * (csx + 1) / 2;
  254. float td = (float)Math.Sqrt(dd), sd = td - l1 - l2 * psx + softness;
  255. if (sd > 0) {
  256. float p = Math.Min(1, sd / (softness * 2)) - 1;
  257. p = (sd - softness * (1 - p * p)) / td;
  258. tx -= p * tx;
  259. ty -= p * ty;
  260. dd = tx * tx + ty * ty;
  261. }
  262. }
  263. if (u) {
  264. l2 *= psx;
  265. float cos = (dd - l1 * l1 - l2 * l2) / (2 * l1 * l2);
  266. if (cos < -1)
  267. cos = -1;
  268. else if (cos > 1) {
  269. cos = 1;
  270. if (stretch) sx *= ((float)Math.Sqrt(dd) / (l1 + l2) - 1) * alpha + 1;
  271. }
  272. a2 = (float)Math.Acos(cos) * bendDir;
  273. a = l1 + l2 * cos;
  274. b = l2 * (float)Math.Sin(a2);
  275. a1 = (float)Math.Atan2(ty * a - tx * b, tx * a + ty * b);
  276. } else {
  277. a = psx * l2;
  278. b = psy * l2;
  279. float aa = a * a, bb = b * b, ta = (float)Math.Atan2(ty, tx);
  280. c = bb * l1 * l1 + aa * dd - aa * bb;
  281. float c1 = -2 * bb * l1, c2 = bb - aa;
  282. d = c1 * c1 - 4 * c2 * c;
  283. if (d >= 0) {
  284. float q = (float)Math.Sqrt(d);
  285. if (c1 < 0) q = -q;
  286. q = -(c1 + q) / 2;
  287. float r0 = q / c2, r1 = c / q;
  288. float r = Math.Abs(r0) < Math.Abs(r1) ? r0 : r1;
  289. if (r * r <= dd) {
  290. y = (float)Math.Sqrt(dd - r * r) * bendDir;
  291. a1 = ta - (float)Math.Atan2(y, r);
  292. a2 = (float)Math.Atan2(y / psy, (r - l1) / psx);
  293. goto break_outer; // break outer;
  294. }
  295. }
  296. float minAngle = MathUtils.PI, minX = l1 - a, minDist = minX * minX, minY = 0;
  297. float maxAngle = 0, maxX = l1 + a, maxDist = maxX * maxX, maxY = 0;
  298. c = -a * l1 / (aa - bb);
  299. if (c >= -1 && c <= 1) {
  300. c = (float)Math.Acos(c);
  301. x = a * (float)Math.Cos(c) + l1;
  302. y = b * (float)Math.Sin(c);
  303. d = x * x + y * y;
  304. if (d < minDist) {
  305. minAngle = c;
  306. minDist = d;
  307. minX = x;
  308. minY = y;
  309. }
  310. if (d > maxDist) {
  311. maxAngle = c;
  312. maxDist = d;
  313. maxX = x;
  314. maxY = y;
  315. }
  316. }
  317. if (dd <= (minDist + maxDist) / 2) {
  318. a1 = ta - (float)Math.Atan2(minY * bendDir, minX);
  319. a2 = minAngle * bendDir;
  320. } else {
  321. a1 = ta - (float)Math.Atan2(maxY * bendDir, maxX);
  322. a2 = maxAngle * bendDir;
  323. }
  324. }
  325. break_outer:
  326. float os = (float)Math.Atan2(cy, cx) * s2;
  327. float rotation = parent.arotation;
  328. a1 = (a1 - os) * MathUtils.RadDeg + os1 - rotation;
  329. if (a1 > 180)
  330. a1 -= 360;
  331. else if (a1 < -180) a1 += 360;
  332. parent.UpdateWorldTransform(px, py, rotation + a1 * alpha, sx, parent.ascaleY, 0, 0);
  333. rotation = child.arotation;
  334. a2 = ((a2 + os) * MathUtils.RadDeg - child.ashearX) * s2 + os2 - rotation;
  335. if (a2 > 180)
  336. a2 -= 360;
  337. else if (a2 < -180) a2 += 360;
  338. child.UpdateWorldTransform(cx, cy, rotation + a2 * alpha, child.ascaleX, child.ascaleY, child.ashearX, child.ashearY);
  339. }
  340. }
  341. }