IkConstraint.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386
  1. /******************************************************************************
  2. * Spine Runtimes License Agreement
  3. * Last updated July 28, 2023. Replaces all prior versions.
  4. *
  5. * Copyright (c) 2013-2023, 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 or
  13. * 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 THE
  27. * SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  28. *****************************************************************************/
  29. using System;
  30. namespace Spine {
  31. using Physics = Skeleton.Physics;
  32. /// <summary>
  33. /// <para>
  34. /// Stores the current pose for an IK constraint. An IK constraint adjusts the rotation of 1 or 2 constrained bones so the tip of
  35. /// the last bone is as close to the target bone as possible.</para>
  36. /// <para>
  37. /// See <a href="http://esotericsoftware.com/spine-ik-constraints">IK constraints</a> in the Spine User Guide.</para>
  38. /// </summary>
  39. public class IkConstraint : IUpdatable {
  40. internal readonly IkConstraintData data;
  41. internal readonly ExposedList<Bone> bones = new ExposedList<Bone>();
  42. internal Bone target;
  43. internal int bendDirection;
  44. internal bool compress, stretch;
  45. internal float mix = 1, softness;
  46. internal bool active;
  47. public IkConstraint (IkConstraintData data, Skeleton skeleton) {
  48. if (data == null) throw new ArgumentNullException("data", "data cannot be null.");
  49. this.data = data;
  50. bones = new ExposedList<Bone>(data.bones.Count);
  51. foreach (BoneData boneData in data.bones)
  52. bones.Add(skeleton.bones.Items[boneData.index]);
  53. target = skeleton.bones.Items[data.target.index];
  54. mix = data.mix;
  55. softness = data.softness;
  56. bendDirection = data.bendDirection;
  57. compress = data.compress;
  58. stretch = data.stretch;
  59. }
  60. /// <summary>Copy constructor.</summary>
  61. public IkConstraint (IkConstraint constraint, Skeleton skeleton)
  62. : this(constraint.data, skeleton) {
  63. mix = constraint.mix;
  64. softness = constraint.softness;
  65. bendDirection = constraint.bendDirection;
  66. compress = constraint.compress;
  67. stretch = constraint.stretch;
  68. }
  69. public void SetToSetupPose () {
  70. IkConstraintData data = this.data;
  71. mix = data.mix;
  72. softness = data.softness;
  73. bendDirection = data.bendDirection;
  74. compress = data.compress;
  75. stretch = data.stretch;
  76. }
  77. public void Update (Physics physics) {
  78. if (mix == 0) return;
  79. Bone target = this.target;
  80. Bone[] bones = this.bones.Items;
  81. switch (this.bones.Count) {
  82. case 1:
  83. Apply(bones[0], target.worldX, target.worldY, compress, stretch, data.uniform, mix);
  84. break;
  85. case 2:
  86. Apply(bones[0], bones[1], target.worldX, target.worldY, bendDirection, stretch, data.uniform, softness, mix);
  87. break;
  88. }
  89. }
  90. /// <summary>The bones that will be modified by this IK constraint.</summary>
  91. public ExposedList<Bone> Bones {
  92. get { return bones; }
  93. }
  94. /// <summary>The bone that is the IK target.</summary>
  95. public Bone Target {
  96. get { return target; }
  97. set { target = value; }
  98. }
  99. /// <summary>A percentage (0-1) that controls the mix between the constrained and unconstrained rotation.
  100. /// <para>
  101. /// For two bone IK: if the parent bone has local nonuniform scale, the child bone's local Y translation is set to 0.
  102. /// </para></summary>
  103. public float Mix {
  104. get { return mix; }
  105. set { mix = value; }
  106. }
  107. /// <summary>For two bone IK, the target bone's distance from the maximum reach of the bones where rotation begins to slow. The bones
  108. /// will not straighten completely until the target is this far out of range.</summary>
  109. public float Softness {
  110. get { return softness; }
  111. set { softness = value; }
  112. }
  113. /// <summary>For two bone IK, controls the bend direction of the IK bones, either 1 or -1.</summary>
  114. public int BendDirection {
  115. get { return bendDirection; }
  116. set { bendDirection = value; }
  117. }
  118. /// <summary>For one bone IK, when true and the target is too close, the bone is scaled to reach it.</summary>
  119. public bool Compress {
  120. get { return compress; }
  121. set { compress = value; }
  122. }
  123. /// <summary>When true and the target is out of range, the parent bone is scaled to reach it.
  124. /// <para>
  125. /// For two bone IK: 1) the child bone's local Y translation is set to 0,
  126. /// 2) stretch is not applied if <see cref="Softness"/> is > 0,
  127. /// and 3) if the parent bone has local nonuniform scale, stretch is not applied.
  128. /// </para></summary>
  129. public bool Stretch {
  130. get { return stretch; }
  131. set { stretch = value; }
  132. }
  133. public bool Active {
  134. get { return active; }
  135. }
  136. /// <summary>The IK constraint's setup pose data.</summary>
  137. public IkConstraintData Data {
  138. get { return data; }
  139. }
  140. override public string ToString () {
  141. return data.name;
  142. }
  143. /// <summary>Applies 1 bone IK. The target is specified in the world coordinate system.</summary>
  144. static public void Apply (Bone bone, float targetX, float targetY, bool compress, bool stretch, bool uniform,
  145. float alpha) {
  146. if (bone == null) throw new ArgumentNullException("bone", "bone cannot be null.");
  147. Bone p = bone.parent;
  148. float pa = p.a, pb = p.b, pc = p.c, pd = p.d;
  149. float rotationIK = -bone.ashearX - bone.arotation;
  150. float tx = 0, ty = 0;
  151. switch (bone.inherit) {
  152. case Inherit.OnlyTranslation:
  153. tx = (targetX - bone.worldX) * Math.Sign(bone.skeleton.ScaleX);
  154. ty = (targetY - bone.worldY) * Math.Sign(bone.skeleton.ScaleY);
  155. break;
  156. case Inherit.NoRotationOrReflection: {
  157. float s = Math.Abs(pa * pd - pb * pc) / Math.Max(0.0001f, pa * pa + pc * pc);
  158. float sa = pa / bone.skeleton.scaleX;
  159. float sc = pc / bone.skeleton.ScaleY;
  160. pb = -sc * s * bone.skeleton.scaleX;
  161. pd = sa * s * bone.skeleton.ScaleY;
  162. rotationIK += MathUtils.Atan2Deg(sc, sa);
  163. goto default; // Fall through.
  164. }
  165. default: {
  166. float x = targetX - p.worldX, y = targetY - p.worldY;
  167. float d = pa * pd - pb * pc;
  168. if (Math.Abs(d) <= 0.0001f) {
  169. tx = 0;
  170. ty = 0;
  171. } else {
  172. tx = (x * pd - y * pb) / d - bone.ax;
  173. ty = (y * pa - x * pc) / d - bone.ay;
  174. }
  175. break;
  176. }
  177. }
  178. rotationIK += MathUtils.Atan2Deg(ty, tx);
  179. if (bone.ascaleX < 0) rotationIK += 180;
  180. if (rotationIK > 180)
  181. rotationIK -= 360;
  182. else if (rotationIK < -180) //
  183. rotationIK += 360;
  184. float sx = bone.ascaleX, sy = bone.ascaleY;
  185. if (compress || stretch) {
  186. switch (bone.inherit) {
  187. case Inherit.NoScale:
  188. case Inherit.NoScaleOrReflection:
  189. tx = targetX - bone.worldX;
  190. ty = targetY - bone.worldY;
  191. break;
  192. }
  193. float b = bone.data.length * sx;
  194. if (b > 0.0001f) {
  195. float dd = tx * tx + ty * ty;
  196. if ((compress && dd < b * b) || (stretch && dd > b * b)) {
  197. float s = ((float)Math.Sqrt(dd) / b - 1) * alpha + 1;
  198. sx *= s;
  199. if (uniform) sy *= s;
  200. }
  201. }
  202. }
  203. bone.UpdateWorldTransform(bone.ax, bone.ay, bone.arotation + rotationIK * alpha, sx, sy, bone.ashearX, bone.ashearY);
  204. }
  205. /// <summary>Applies 2 bone IK. The target is specified in the world coordinate system.</summary>
  206. /// <param name="child">A direct descendant of the parent bone.</param>
  207. static public void Apply (Bone parent, Bone child, float targetX, float targetY, int bendDir, bool stretch, bool uniform,
  208. float softness, float alpha) {
  209. if (parent == null) throw new ArgumentNullException("parent", "parent cannot be null.");
  210. if (child == null) throw new ArgumentNullException("child", "child cannot be null.");
  211. if (parent.inherit != Inherit.Normal || child.inherit != Inherit.Normal) return;
  212. float px = parent.ax, py = parent.ay, psx = parent.ascaleX, psy = parent.ascaleY, sx = psx, sy = psy, csx = child.ascaleX;
  213. int os1, os2, s2;
  214. if (psx < 0) {
  215. psx = -psx;
  216. os1 = 180;
  217. s2 = -1;
  218. } else {
  219. os1 = 0;
  220. s2 = 1;
  221. }
  222. if (psy < 0) {
  223. psy = -psy;
  224. s2 = -s2;
  225. }
  226. if (csx < 0) {
  227. csx = -csx;
  228. os2 = 180;
  229. } else
  230. os2 = 0;
  231. float cx = child.ax, cy, cwx, cwy, a = parent.a, b = parent.b, c = parent.c, d = parent.d;
  232. bool u = Math.Abs(psx - psy) <= 0.0001f;
  233. if (!u || stretch) {
  234. cy = 0;
  235. cwx = a * cx + parent.worldX;
  236. cwy = c * cx + parent.worldY;
  237. } else {
  238. cy = child.ay;
  239. cwx = a * cx + b * cy + parent.worldX;
  240. cwy = c * cx + d * cy + parent.worldY;
  241. }
  242. Bone pp = parent.parent;
  243. a = pp.a;
  244. b = pp.b;
  245. c = pp.c;
  246. d = pp.d;
  247. float id = a * d - b * c, x = cwx - pp.worldX, y = cwy - pp.worldY;
  248. id = Math.Abs(id) <= 0.0001f ? 0 : 1 / id;
  249. float dx = (x * d - y * b) * id - px, dy = (y * a - x * c) * id - py;
  250. float l1 = (float)Math.Sqrt(dx * dx + dy * dy), l2 = child.data.length * csx, a1, a2;
  251. if (l1 < 0.0001f) {
  252. Apply(parent, targetX, targetY, false, stretch, false, alpha);
  253. child.UpdateWorldTransform(cx, cy, 0, child.ascaleX, child.ascaleY, child.ashearX, child.ashearY);
  254. return;
  255. }
  256. x = targetX - pp.worldX;
  257. y = targetY - pp.worldY;
  258. float tx = (x * d - y * b) * id - px, ty = (y * a - x * c) * id - py;
  259. float dd = tx * tx + ty * ty;
  260. if (softness != 0) {
  261. softness *= psx * (csx + 1) * 0.5f;
  262. float td = (float)Math.Sqrt(dd), sd = td - l1 - l2 * psx + softness;
  263. if (sd > 0) {
  264. float p = Math.Min(1, sd / (softness * 2)) - 1;
  265. p = (sd - softness * (1 - p * p)) / td;
  266. tx -= p * tx;
  267. ty -= p * ty;
  268. dd = tx * tx + ty * ty;
  269. }
  270. }
  271. if (u) {
  272. l2 *= psx;
  273. float cos = (dd - l1 * l1 - l2 * l2) / (2 * l1 * l2);
  274. if (cos < -1) {
  275. cos = -1;
  276. a2 = MathUtils.PI * bendDir;
  277. } else if (cos > 1) {
  278. cos = 1;
  279. a2 = 0;
  280. if (stretch) {
  281. a = ((float)Math.Sqrt(dd) / (l1 + l2) - 1) * alpha + 1;
  282. sx *= a;
  283. if (uniform) sy *= a;
  284. }
  285. } else
  286. a2 = (float)Math.Acos(cos) * bendDir;
  287. a = l1 + l2 * cos;
  288. b = l2 * (float)Math.Sin(a2);
  289. a1 = (float)Math.Atan2(ty * a - tx * b, tx * a + ty * b);
  290. } else {
  291. a = psx * l2;
  292. b = psy * l2;
  293. float aa = a * a, bb = b * b, ta = (float)Math.Atan2(ty, tx);
  294. c = bb * l1 * l1 + aa * dd - aa * bb;
  295. float c1 = -2 * bb * l1, c2 = bb - aa;
  296. d = c1 * c1 - 4 * c2 * c;
  297. if (d >= 0) {
  298. float q = (float)Math.Sqrt(d);
  299. if (c1 < 0) q = -q;
  300. q = -(c1 + q) * 0.5f;
  301. float r0 = q / c2, r1 = c / q;
  302. float r = Math.Abs(r0) < Math.Abs(r1) ? r0 : r1;
  303. r0 = dd - r * r;
  304. if (r0 >= 0) {
  305. y = (float)Math.Sqrt(r0) * bendDir;
  306. a1 = ta - (float)Math.Atan2(y, r);
  307. a2 = (float)Math.Atan2(y / psy, (r - l1) / psx);
  308. goto break_outer; // break outer;
  309. }
  310. }
  311. float minAngle = MathUtils.PI, minX = l1 - a, minDist = minX * minX, minY = 0;
  312. float maxAngle = 0, maxX = l1 + a, maxDist = maxX * maxX, maxY = 0;
  313. c = -a * l1 / (aa - bb);
  314. if (c >= -1 && c <= 1) {
  315. c = (float)Math.Acos(c);
  316. x = a * (float)Math.Cos(c) + l1;
  317. y = b * (float)Math.Sin(c);
  318. d = x * x + y * y;
  319. if (d < minDist) {
  320. minAngle = c;
  321. minDist = d;
  322. minX = x;
  323. minY = y;
  324. }
  325. if (d > maxDist) {
  326. maxAngle = c;
  327. maxDist = d;
  328. maxX = x;
  329. maxY = y;
  330. }
  331. }
  332. if (dd <= (minDist + maxDist) * 0.5f) {
  333. a1 = ta - (float)Math.Atan2(minY * bendDir, minX);
  334. a2 = minAngle * bendDir;
  335. } else {
  336. a1 = ta - (float)Math.Atan2(maxY * bendDir, maxX);
  337. a2 = maxAngle * bendDir;
  338. }
  339. }
  340. break_outer:
  341. float os = (float)Math.Atan2(cy, cx) * s2;
  342. float rotation = parent.arotation;
  343. a1 = (a1 - os) * MathUtils.RadDeg + os1 - rotation;
  344. if (a1 > 180)
  345. a1 -= 360;
  346. else if (a1 < -180)
  347. a1 += 360;
  348. parent.UpdateWorldTransform(px, py, rotation + a1 * alpha, sx, sy, 0, 0);
  349. rotation = child.arotation;
  350. a2 = ((a2 + os) * MathUtils.RadDeg - child.ashearX) * s2 + os2 - rotation;
  351. if (a2 > 180)
  352. a2 -= 360;
  353. else if (a2 < -180)
  354. a2 += 360;
  355. child.UpdateWorldTransform(cx, cy, rotation + a2 * alpha, child.ascaleX, child.ascaleY, child.ashearX, child.ashearY);
  356. }
  357. }
  358. }