Fix T62048: crash when turning off curve path animation with Spline IK.
[blender.git] / source / blender / blenkernel / intern / armature_update.c
1 /*
2  * This program is free software; you can redistribute it and/or
3  * modify it under the terms of the GNU General Public License
4  * as published by the Free Software Foundation; either version 2
5  * of the License, or (at your option) any later version.
6  *
7  * This program is distributed in the hope that it will be useful,
8  * but WITHOUT ANY WARRANTY; without even the implied warranty of
9  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
10  * GNU General Public License for more details.
11  *
12  * You should have received a copy of the GNU General Public License
13  * along with this program; if not, write to the Free Software Foundation,
14  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
15  *
16  * The Original Code is Copyright (C) 2015 Blender Foundation.
17  * All rights reserved.
18  *
19  * Defines and code for core node types
20  */
21
22 /** \file
23  * \ingroup bke
24  */
25
26 #include "MEM_guardedalloc.h"
27
28 #include "BLI_utildefines.h"
29 #include "BLI_listbase.h"
30 #include "BLI_math.h"
31
32 #include "DNA_armature_types.h"
33 #include "DNA_constraint_types.h"
34 #include "DNA_object_types.h"
35 #include "DNA_scene_types.h"
36
37 #include "BKE_action.h"
38 #include "BKE_anim.h"
39 #include "BKE_armature.h"
40 #include "BKE_curve.h"
41 #include "BKE_displist.h"
42 #include "BKE_fcurve.h"
43 #include "BKE_object.h"
44 #include "BKE_scene.h"
45
46 #include "BIK_api.h"
47
48
49 #include "DEG_depsgraph.h"
50
51 /* ********************** SPLINE IK SOLVER ******************* */
52
53 /* Temporary evaluation tree data used for Spline IK */
54 typedef struct tSplineIK_Tree {
55         struct tSplineIK_Tree *next, *prev;
56
57         int type;                    /* type of IK that this serves (CONSTRAINT_TYPE_KINEMATIC or ..._SPLINEIK) */
58
59         bool free_points;            /* free the point positions array */
60         short chainlen;              /* number of bones in the chain */
61
62         float *points;               /* parametric positions for the joints along the curve */
63         bPoseChannel **chain;        /* chain of bones to affect using Spline IK (ordered from the tip) */
64
65         bPoseChannel *root;          /* bone that is the root node of the chain */
66
67         bConstraint *con;            /* constraint for this chain */
68         bSplineIKConstraint *ikData; /* constraint settings for this chain */
69 } tSplineIK_Tree;
70
71 /* ----------- */
72
73 /* Tag the bones in the chain formed by the given bone for IK */
74 static void splineik_init_tree_from_pchan(Scene *UNUSED(scene), Object *UNUSED(ob), bPoseChannel *pchan_tip)
75 {
76         bPoseChannel *pchan, *pchanRoot = NULL;
77         bPoseChannel *pchanChain[255];
78         bConstraint *con = NULL;
79         bSplineIKConstraint *ikData = NULL;
80         float boneLengths[255], *jointPoints;
81         float totLength = 0.0f;
82         bool free_joints = 0;
83         int segcount = 0;
84
85         /* find the SplineIK constraint */
86         for (con = pchan_tip->constraints.first; con; con = con->next) {
87                 if (con->type == CONSTRAINT_TYPE_SPLINEIK) {
88                         ikData = con->data;
89
90                         /* target can only be curve */
91                         if ((ikData->tar == NULL) || (ikData->tar->type != OB_CURVE))
92                                 continue;
93                         /* skip if disabled */
94                         if ((con->enforce == 0.0f) || (con->flag & (CONSTRAINT_DISABLE | CONSTRAINT_OFF)))
95                                 continue;
96
97                         /* otherwise, constraint is ok... */
98                         break;
99                 }
100         }
101         if (con == NULL)
102                 return;
103
104         /* make sure that the constraint targets are ok
105          *     - this is a workaround for a depsgraph bug or dependency cycle...
106          */
107         if (ikData->tar) {
108                 CurveCache *cache = ikData->tar->runtime.curve_cache;
109
110                 if (ELEM(NULL, cache, cache->path, cache->path->data)) {
111                         return;
112                 }
113         }
114
115         /* find the root bone and the chain of bones from the root to the tip
116          * NOTE: this assumes that the bones are connected, but that may not be true... */
117         for (pchan = pchan_tip; pchan && (segcount < ikData->chainlen); pchan = pchan->parent, segcount++) {
118                 /* store this segment in the chain */
119                 pchanChain[segcount] = pchan;
120
121                 /* if performing rebinding, calculate the length of the bone */
122                 boneLengths[segcount] = pchan->bone->length;
123                 totLength += boneLengths[segcount];
124         }
125
126         if (segcount == 0)
127                 return;
128         else
129                 pchanRoot = pchanChain[segcount - 1];
130
131         /* perform binding step if required */
132         if ((ikData->flag & CONSTRAINT_SPLINEIK_BOUND) == 0) {
133                 float segmentLen = (1.0f / (float)segcount);
134                 int i;
135
136                 /* setup new empty array for the points list */
137                 if (ikData->points)
138                         MEM_freeN(ikData->points);
139                 ikData->numpoints = ikData->chainlen + 1;
140                 ikData->points = MEM_mallocN(sizeof(float) * ikData->numpoints, "Spline IK Binding");
141
142                 /* bind 'tip' of chain (i.e. first joint = tip of bone with the Spline IK Constraint) */
143                 ikData->points[0] = 1.0f;
144
145                 /* perform binding of the joints to parametric positions along the curve based
146                  * proportion of the total length that each bone occupies
147                  */
148                 for (i = 0; i < segcount; i++) {
149                         /* 'head' joints, traveling towards the root of the chain
150                          * - 2 methods; the one chosen depends on whether we've got usable lengths
151                          */
152                         if ((ikData->flag & CONSTRAINT_SPLINEIK_EVENSPLITS) || (totLength == 0.0f)) {
153                                 /* 1) equi-spaced joints */
154                                 ikData->points[i + 1] = ikData->points[i] - segmentLen;
155                         }
156                         else {
157                                 /* 2) to find this point on the curve, we take a step from the previous joint
158                                  *    a distance given by the proportion that this bone takes
159                                  */
160                                 ikData->points[i + 1] = ikData->points[i] - (boneLengths[i] / totLength);
161                         }
162                 }
163
164                 /* spline has now been bound */
165                 ikData->flag |= CONSTRAINT_SPLINEIK_BOUND;
166         }
167
168         /* disallow negative values (happens with float precision) */
169         CLAMP_MIN(ikData->points[segcount], 0.0f);
170
171         /* apply corrections for sensitivity to scaling on a copy of the bind points,
172          * since it's easier to determine the positions of all the joints beforehand this way
173          */
174         if ((ikData->flag & CONSTRAINT_SPLINEIK_SCALE_LIMITED) && (totLength != 0.0f)) {
175                 float splineLen, maxScale;
176                 int i;
177
178                 /* make a copy of the points array, that we'll store in the tree
179                  *     - although we could just multiply the points on the fly, this approach means that
180                  *       we can introduce per-segment stretchiness later if it is necessary
181                  */
182                 jointPoints = MEM_dupallocN(ikData->points);
183                 free_joints = 1;
184
185                 /* get the current length of the curve */
186                 /* NOTE: this is assumed to be correct even after the curve was resized */
187                 splineLen = ikData->tar->runtime.curve_cache->path->totdist;
188
189                 /* calculate the scale factor to multiply all the path values by so that the
190                  * bone chain retains its current length, such that
191                  *     maxScale * splineLen = totLength
192                  */
193                 maxScale = totLength / splineLen;
194
195                 /* apply scaling correction to all of the temporary points */
196                 /* TODO: this is really not adequate enough on really short chains */
197                 for (i = 0; i < segcount; i++)
198                         jointPoints[i] *= maxScale;
199         }
200         else {
201                 /* just use the existing points array */
202                 jointPoints = ikData->points;
203                 free_joints = 0;
204         }
205
206         /* make a new Spline-IK chain, and store it in the IK chains */
207         /* TODO: we should check if there is already an IK chain on this, since that would take precedence... */
208         {
209                 /* make new tree */
210                 tSplineIK_Tree *tree = MEM_callocN(sizeof(tSplineIK_Tree), "SplineIK Tree");
211                 tree->type = CONSTRAINT_TYPE_SPLINEIK;
212
213                 tree->chainlen = segcount;
214
215                 /* copy over the array of links to bones in the chain (from tip to root) */
216                 tree->chain = MEM_mallocN(sizeof(bPoseChannel *) * segcount, "SplineIK Chain");
217                 memcpy(tree->chain, pchanChain, sizeof(bPoseChannel *) * segcount);
218
219                 /* store reference to joint position array */
220                 tree->points = jointPoints;
221                 tree->free_points = free_joints;
222
223                 /* store references to different parts of the chain */
224                 tree->root = pchanRoot;
225                 tree->con = con;
226                 tree->ikData = ikData;
227
228                 /* AND! link the tree to the root */
229                 BLI_addtail(&pchanRoot->siktree, tree);
230         }
231
232         /* mark root channel having an IK tree */
233         pchanRoot->flag |= POSE_IKSPLINE;
234 }
235
236 /* Tag which bones are members of Spline IK chains */
237 static void splineik_init_tree(Scene *scene, Object *ob, float UNUSED(ctime))
238 {
239         bPoseChannel *pchan;
240
241         /* find the tips of Spline IK chains, which are simply the bones which have been tagged as such */
242         for (pchan = ob->pose->chanbase.first; pchan; pchan = pchan->next) {
243                 if (pchan->constflag & PCHAN_HAS_SPLINEIK)
244                         splineik_init_tree_from_pchan(scene, ob, pchan);
245         }
246 }
247
248 /* ----------- */
249
250 /* Evaluate spline IK for a given bone */
251 static void splineik_evaluate_bone(
252         struct Depsgraph *depsgraph, tSplineIK_Tree *tree, Scene *scene, Object *ob, bPoseChannel *pchan,
253         int index, float ctime)
254 {
255         bSplineIKConstraint *ikData = tree->ikData;
256         float poseHead[3], poseTail[3], poseMat[4][4];
257         float splineVec[3], scaleFac, radius = 1.0f;
258
259         /* firstly, calculate the bone matrix the standard way, since this is needed for roll control */
260         BKE_pose_where_is_bone(depsgraph, scene, ob, pchan, ctime, 1);
261
262         copy_v3_v3(poseHead, pchan->pose_head);
263         copy_v3_v3(poseTail, pchan->pose_tail);
264
265         /* step 1: determine the positions for the endpoints of the bone */
266         {
267                 float vec[4], dir[3], rad;
268                 float tailBlendFac = 1.0f;
269
270                 /* determine if the bone should still be affected by SplineIK */
271                 if (tree->points[index + 1] >= 1.0f) {
272                         /* spline doesn't affect the bone anymore, so done... */
273                         pchan->flag |= POSE_DONE;
274                         return;
275                 }
276                 else if ((tree->points[index] >= 1.0f) && (tree->points[index + 1] < 1.0f)) {
277                         /* blending factor depends on the amount of the bone still left on the chain */
278                         tailBlendFac = (1.0f - tree->points[index + 1]) / (tree->points[index] - tree->points[index + 1]);
279                 }
280
281                 /* tail endpoint */
282                 if (where_on_path(ikData->tar, tree->points[index], vec, dir, NULL, &rad, NULL)) {
283                         /* apply curve's object-mode transforms to the position
284                          * unless the option to allow curve to be positioned elsewhere is activated (i.e. no root)
285                          */
286                         if ((ikData->flag & CONSTRAINT_SPLINEIK_NO_ROOT) == 0)
287                                 mul_m4_v3(ikData->tar->obmat, vec);
288
289                         /* convert the position to pose-space, then store it */
290                         mul_m4_v3(ob->imat, vec);
291                         interp_v3_v3v3(poseTail, pchan->pose_tail, vec, tailBlendFac);
292
293                         /* set the new radius */
294                         radius = rad;
295                 }
296
297                 /* head endpoint */
298                 if (where_on_path(ikData->tar, tree->points[index + 1], vec, dir, NULL, &rad, NULL)) {
299                         /* apply curve's object-mode transforms to the position
300                          * unless the option to allow curve to be positioned elsewhere is activated (i.e. no root)
301                          */
302                         if ((ikData->flag & CONSTRAINT_SPLINEIK_NO_ROOT) == 0)
303                                 mul_m4_v3(ikData->tar->obmat, vec);
304
305                         /* store the position, and convert it to pose space */
306                         mul_m4_v3(ob->imat, vec);
307                         copy_v3_v3(poseHead, vec);
308
309                         /* set the new radius (it should be the average value) */
310                         radius = (radius + rad) / 2;
311                 }
312         }
313
314         /* step 2: determine the implied transform from these endpoints
315          *     - splineVec: the vector direction that the spline applies on the bone
316          *     - scaleFac: the factor that the bone length is scaled by to get the desired amount
317          */
318         sub_v3_v3v3(splineVec, poseTail, poseHead);
319         scaleFac = len_v3(splineVec) / pchan->bone->length;
320
321         /* step 3: compute the shortest rotation needed to map from the bone rotation to the current axis
322          *      - this uses the same method as is used for the Damped Track Constraint (see the code there for details)
323          */
324         {
325                 float dmat[3][3], rmat[3][3], tmat[3][3];
326                 float raxis[3], rangle;
327
328                 /* compute the raw rotation matrix from the bone's current matrix by extracting only the
329                  * orientation-relevant axes, and normalizing them
330                  */
331                 copy_v3_v3(rmat[0], pchan->pose_mat[0]);
332                 copy_v3_v3(rmat[1], pchan->pose_mat[1]);
333                 copy_v3_v3(rmat[2], pchan->pose_mat[2]);
334                 normalize_m3(rmat);
335
336                 /* also, normalize the orientation imposed by the bone, now that we've extracted the scale factor */
337                 normalize_v3(splineVec);
338
339                 /* calculate smallest axis-angle rotation necessary for getting from the
340                  * current orientation of the bone, to the spline-imposed direction
341                  */
342                 cross_v3_v3v3(raxis, rmat[1], splineVec);
343
344                 rangle = dot_v3v3(rmat[1], splineVec);
345                 CLAMP(rangle, -1.0f, 1.0f);
346                 rangle = acosf(rangle);
347
348                 /* multiply the magnitude of the angle by the influence of the constraint to
349                  * control the influence of the SplineIK effect
350                  */
351                 rangle *= tree->con->enforce;
352
353                 /* construct rotation matrix from the axis-angle rotation found above
354                  * - this call takes care to make sure that the axis provided is a unit vector first
355                  */
356                 axis_angle_to_mat3(dmat, raxis, rangle);
357
358                 /* combine these rotations so that the y-axis of the bone is now aligned as the spline dictates,
359                  * while still maintaining roll control from the existing bone animation
360                  */
361                 mul_m3_m3m3(tmat, dmat, rmat); /* m1, m3, m2 */
362                 normalize_m3(tmat); /* attempt to reduce shearing, though I doubt this'll really help too much now... */
363                 copy_m4_m3(poseMat, tmat);
364         }
365
366         /* step 4: set the scaling factors for the axes */
367         {
368                 /* only multiply the y-axis by the scaling factor to get nice volume-preservation */
369                 mul_v3_fl(poseMat[1], scaleFac);
370
371                 /* set the scaling factors of the x and z axes from... */
372                 switch (ikData->xzScaleMode) {
373                         case CONSTRAINT_SPLINEIK_XZS_ORIGINAL:
374                         {
375                                 /* original scales get used */
376                                 float scale;
377
378                                 /* x-axis scale */
379                                 scale = len_v3(pchan->pose_mat[0]);
380                                 mul_v3_fl(poseMat[0], scale);
381                                 /* z-axis scale */
382                                 scale = len_v3(pchan->pose_mat[2]);
383                                 mul_v3_fl(poseMat[2], scale);
384                                 break;
385                         }
386                         case CONSTRAINT_SPLINEIK_XZS_INVERSE:
387                         {
388                                 /* old 'volume preservation' method using the inverse scale */
389                                 float scale;
390
391                                 /* calculate volume preservation factor which is
392                                  * basically the inverse of the y-scaling factor
393                                  */
394                                 if (fabsf(scaleFac) != 0.0f) {
395                                         scale = 1.0f / fabsf(scaleFac);
396
397                                         /* we need to clamp this within sensible values */
398                                         /* NOTE: these should be fine for now, but should get sanitised in future */
399                                         CLAMP(scale, 0.0001f, 100000.0f);
400                                 }
401                                 else
402                                         scale = 1.0f;
403
404                                 /* apply the scaling */
405                                 mul_v3_fl(poseMat[0], scale);
406                                 mul_v3_fl(poseMat[2], scale);
407                                 break;
408                         }
409                         case CONSTRAINT_SPLINEIK_XZS_VOLUMETRIC:
410                         {
411                                 /* improved volume preservation based on the Stretch To constraint */
412                                 float final_scale;
413
414                                 /* as the basis for volume preservation, we use the inverse scale factor... */
415                                 if (fabsf(scaleFac) != 0.0f) {
416                                         /* NOTE: The method here is taken wholesale from the Stretch To constraint */
417                                         float bulge = powf(1.0f / fabsf(scaleFac), ikData->bulge);
418
419                                         if (bulge > 1.0f) {
420                                                 if (ikData->flag & CONSTRAINT_SPLINEIK_USE_BULGE_MAX) {
421                                                         float bulge_max = max_ff(ikData->bulge_max, 1.0f);
422                                                         float hard = min_ff(bulge, bulge_max);
423
424                                                         float range = bulge_max - 1.0f;
425                                                         float scale = (range > 0.0f) ? 1.0f / range : 0.0f;
426                                                         float soft = 1.0f + range * atanf((bulge - 1.0f) * scale) / (float)M_PI_2;
427
428                                                         bulge = interpf(soft, hard, ikData->bulge_smooth);
429                                                 }
430                                         }
431                                         if (bulge < 1.0f) {
432                                                 if (ikData->flag & CONSTRAINT_SPLINEIK_USE_BULGE_MIN) {
433                                                         float bulge_min = CLAMPIS(ikData->bulge_min, 0.0f, 1.0f);
434                                                         float hard = max_ff(bulge, bulge_min);
435
436                                                         float range = 1.0f - bulge_min;
437                                                         float scale = (range > 0.0f) ? 1.0f / range : 0.0f;
438                                                         float soft = 1.0f - range * atanf((1.0f - bulge) * scale) / (float)M_PI_2;
439
440                                                         bulge = interpf(soft, hard, ikData->bulge_smooth);
441                                                 }
442                                         }
443
444                                         /* compute scale factor for xz axes from this value */
445                                         final_scale = sqrtf(bulge);
446                                 }
447                                 else {
448                                         /* no scaling, so scale factor is simple */
449                                         final_scale = 1.0f;
450                                 }
451
452                                 /* apply the scaling (assuming normalised scale) */
453                                 mul_v3_fl(poseMat[0], final_scale);
454                                 mul_v3_fl(poseMat[2], final_scale);
455                                 break;
456                         }
457                 }
458
459                 /* finally, multiply the x and z scaling by the radius of the curve too,
460                  * to allow automatic scales to get tweaked still
461                  */
462                 if ((ikData->flag & CONSTRAINT_SPLINEIK_NO_CURVERAD) == 0) {
463                         mul_v3_fl(poseMat[0], radius);
464                         mul_v3_fl(poseMat[2], radius);
465                 }
466         }
467
468         /* step 5: set the location of the bone in the matrix */
469         if (ikData->flag & CONSTRAINT_SPLINEIK_NO_ROOT) {
470                 /* when the 'no-root' option is affected, the chain can retain
471                  * the shape but be moved elsewhere
472                  */
473                 copy_v3_v3(poseHead, pchan->pose_head);
474         }
475         else if (tree->con->enforce < 1.0f) {
476                 /* when the influence is too low
477                  * - blend the positions for the 'root' bone
478                  * - stick to the parent for any other
479                  */
480                 if (pchan->parent) {
481                         copy_v3_v3(poseHead, pchan->pose_head);
482                 }
483                 else {
484                         /* FIXME: this introduces popping artifacts when we reach 0.0 */
485                         interp_v3_v3v3(poseHead, pchan->pose_head, poseHead, tree->con->enforce);
486                 }
487         }
488         copy_v3_v3(poseMat[3], poseHead);
489
490         /* finally, store the new transform */
491         copy_m4_m4(pchan->pose_mat, poseMat);
492         copy_v3_v3(pchan->pose_head, poseHead);
493
494         /* recalculate tail, as it's now outdated after the head gets adjusted above! */
495         BKE_pose_where_is_bone_tail(pchan);
496
497         /* done! */
498         pchan->flag |= POSE_DONE;
499 }
500
501 /* Evaluate the chain starting from the nominated bone */
502 static void splineik_execute_tree(struct Depsgraph *depsgraph, Scene *scene, Object *ob, bPoseChannel *pchan_root, float ctime)
503 {
504         tSplineIK_Tree *tree;
505
506         /* for each pose-tree, execute it if it is spline, otherwise just free it */
507         while ((tree = pchan_root->siktree.first) != NULL) {
508                 int i;
509
510                 /* walk over each bone in the chain, calculating the effects of spline IK
511                  *     - the chain is traversed in the opposite order to storage order (i.e. parent to children)
512                  *       so that dependencies are correct
513                  */
514                 for (i = tree->chainlen - 1; i >= 0; i--) {
515                         bPoseChannel *pchan = tree->chain[i];
516                         splineik_evaluate_bone(depsgraph, tree, scene, ob, pchan, i, ctime);
517                 }
518
519                 /* free the tree info specific to SplineIK trees now */
520                 if (tree->chain)
521                         MEM_freeN(tree->chain);
522                 if (tree->free_points)
523                         MEM_freeN(tree->points);
524
525                 /* free this tree */
526                 BLI_freelinkN(&pchan_root->siktree, tree);
527         }
528 }
529
530 void BKE_pose_splineik_init_tree(Scene *scene, Object *ob, float ctime)
531 {
532         splineik_init_tree(scene, ob, ctime);
533 }
534
535 void BKE_splineik_execute_tree(
536         struct Depsgraph *depsgraph, Scene *scene,
537         Object *ob, bPoseChannel *pchan_root, float ctime)
538 {
539         splineik_execute_tree(depsgraph, scene, ob, pchan_root, ctime);
540 }
541
542 /* *************** Depsgraph evaluation callbacks ************ */
543
544 static void pose_pchan_index_create(bPose *pose)
545 {
546         const int num_channels = BLI_listbase_count(&pose->chanbase);
547         pose->chan_array = MEM_malloc_arrayN(
548                 num_channels, sizeof(bPoseChannel *), "pose->chan_array");
549         int pchan_index = 0;
550         for (bPoseChannel *pchan = pose->chanbase.first; pchan != NULL; pchan = pchan->next) {
551                 pose->chan_array[pchan_index++] = pchan;
552         }
553 }
554
555 BLI_INLINE bPoseChannel *pose_pchan_get_indexed(Object *ob, int pchan_index)
556 {
557         bPose *pose = ob->pose;
558         BLI_assert(pose != NULL);
559         BLI_assert(pose->chan_array != NULL);
560         BLI_assert(pchan_index >= 0);
561         BLI_assert(pchan_index < MEM_allocN_len(pose->chan_array) / sizeof(bPoseChannel *));
562         return pose->chan_array[pchan_index];
563 }
564
565 void BKE_pose_eval_init(struct Depsgraph *depsgraph,
566                         Scene *UNUSED(scene),
567                         Object *object)
568 {
569         bPose *pose = object->pose;
570         BLI_assert(pose != NULL);
571
572         DEG_debug_print_eval(depsgraph, __func__, object->id.name, object);
573
574         BLI_assert(object->type == OB_ARMATURE);
575
576         /* We demand having proper pose. */
577         BLI_assert(object->pose != NULL);
578         BLI_assert((object->pose->flag & POSE_RECALC) == 0);
579
580         /* imat is needed for solvers. */
581         invert_m4_m4(object->imat, object->obmat);
582
583         /* clear flags */
584         for (bPoseChannel *pchan = pose->chanbase.first; pchan != NULL; pchan = pchan->next) {
585                 pchan->flag &= ~(POSE_DONE | POSE_CHAIN | POSE_IKTREE | POSE_IKSPLINE);
586
587                 /* Free B-Bone shape data cache if it's not a B-Bone. */
588                 if (pchan->bone == NULL || pchan->bone->segments <= 1) {
589                         BKE_pose_channel_free_bbone_cache(pchan);
590                 }
591         }
592
593         pose_pchan_index_create(pose);
594         BKE_armature_cached_bbone_deformation_free_data(object);
595 }
596
597 void BKE_pose_eval_init_ik(struct Depsgraph *depsgraph,
598                            Scene *scene,
599                            Object *object)
600 {
601         DEG_debug_print_eval(depsgraph, __func__, object->id.name, object);
602         BLI_assert(object->type == OB_ARMATURE);
603         const float ctime = BKE_scene_frame_get(scene); /* not accurate... */
604         bArmature *armature = (bArmature *)object->data;
605         if (armature->flag & ARM_RESTPOS) {
606                 return;
607         }
608         /* construct the IK tree (standard IK) */
609         BIK_initialize_tree(depsgraph, scene, object, ctime);
610         /* construct the Spline IK trees
611          * - this is not integrated as an IK plugin, since it should be able
612          *   to function in conjunction with standard IK.  */
613         BKE_pose_splineik_init_tree(scene, object, ctime);
614 }
615
616 void BKE_pose_eval_bone(struct Depsgraph *depsgraph,
617                         Scene *scene,
618                         Object *object,
619                         int pchan_index)
620 {
621         const bArmature *armature = (bArmature *)object->data;
622         if (armature->edbo != NULL) {
623                 return;
624         }
625         bPoseChannel *pchan = pose_pchan_get_indexed(object, pchan_index);
626         DEG_debug_print_eval_subdata(
627                 depsgraph, __func__, object->id.name, object,
628                 "pchan", pchan->name, pchan);
629         BLI_assert(object->type == OB_ARMATURE);
630         if (armature->flag & ARM_RESTPOS) {
631                 Bone *bone = pchan->bone;
632                 if (bone) {
633                         copy_m4_m4(pchan->pose_mat, bone->arm_mat);
634                         copy_v3_v3(pchan->pose_head, bone->arm_head);
635                         copy_v3_v3(pchan->pose_tail, bone->arm_tail);
636                 }
637         }
638         else {
639                 /* TODO(sergey): Currently if there are constraints full transform is
640                  * being evaluated in BKE_pose_constraints_evaluate. */
641                 if (pchan->constraints.first == NULL) {
642                         if (pchan->flag & POSE_IKTREE || pchan->flag & POSE_IKSPLINE) {
643                                 /* pass */
644                         }
645                         else {
646                                 if ((pchan->flag & POSE_DONE) == 0) {
647                                         /* TODO(sergey): Use time source node for time. */
648                                         float ctime = BKE_scene_frame_get(scene); /* not accurate... */
649                                         BKE_pose_where_is_bone(depsgraph, scene, object, pchan, ctime, 1);
650                                 }
651                         }
652                 }
653         }
654 }
655
656 void BKE_pose_constraints_evaluate(struct Depsgraph *depsgraph,
657                                    Scene *scene,
658                                    Object *object,
659                                    int pchan_index)
660 {
661         const bArmature *armature = (bArmature *)object->data;
662         if (armature->edbo != NULL) {
663                 return;
664         }
665         bPoseChannel *pchan = pose_pchan_get_indexed(object, pchan_index);
666         DEG_debug_print_eval_subdata(
667                 depsgraph, __func__, object->id.name, object,
668                 "pchan", pchan->name, pchan);
669         if (armature->flag & ARM_RESTPOS) {
670                 return;
671         }
672         else if (pchan->flag & POSE_IKTREE || pchan->flag & POSE_IKSPLINE) {
673                 /* IK are being solved separately/ */
674         }
675         else {
676                 if ((pchan->flag & POSE_DONE) == 0) {
677                         float ctime = BKE_scene_frame_get(scene); /* not accurate... */
678                         BKE_pose_where_is_bone(depsgraph, scene, object, pchan, ctime, 1);
679                 }
680         }
681 }
682
683 void BKE_pose_bone_done(struct Depsgraph *depsgraph,
684                         struct Object *object,
685                         int pchan_index)
686 {
687         const bArmature *armature = (bArmature *)object->data;
688         if (armature->edbo != NULL) {
689                 return;
690         }
691         bPoseChannel *pchan = pose_pchan_get_indexed(object, pchan_index);
692         float imat[4][4];
693         DEG_debug_print_eval_subdata(
694                 depsgraph, __func__, object->id.name, object,
695                 "pchan", pchan->name, pchan);
696         if (pchan->bone) {
697                 invert_m4_m4(imat, pchan->bone->arm_mat);
698                 mul_m4_m4m4(pchan->chan_mat, pchan->pose_mat, imat);
699         }
700         if (DEG_is_active(depsgraph) && armature->edbo == NULL) {
701                 bPoseChannel *pchan_orig = pchan->orig_pchan;
702                 copy_m4_m4(pchan_orig->pose_mat, pchan->pose_mat);
703                 copy_m4_m4(pchan_orig->chan_mat, pchan->chan_mat);
704                 copy_v3_v3(pchan_orig->pose_head, pchan->pose_mat[3]);
705                 copy_m4_m4(pchan_orig->constinv, pchan->constinv);
706                 BKE_pose_where_is_bone_tail(pchan_orig);
707                 if (pchan->bone == NULL || pchan->bone->segments <= 1) {
708                         BKE_pose_channel_free_bbone_cache(pchan_orig);
709                 }
710         }
711 }
712
713 void BKE_pose_eval_bbone_segments(struct Depsgraph *depsgraph,
714                                   struct Object *object,
715                                   int pchan_index)
716 {
717         const bArmature *armature = (bArmature *)object->data;
718         if (armature->edbo != NULL) {
719                 return;
720         }
721         bPoseChannel *pchan = pose_pchan_get_indexed(object, pchan_index);
722         DEG_debug_print_eval_subdata(
723                 depsgraph, __func__, object->id.name, object,
724                 "pchan", pchan->name, pchan);
725         if (pchan->bone != NULL && pchan->bone->segments > 1) {
726                 BKE_pchan_bbone_segments_cache_compute(pchan);
727                 if (DEG_is_active(depsgraph)) {
728                         BKE_pchan_bbone_segments_cache_copy(pchan->orig_pchan, pchan);
729                 }
730         }
731 }
732
733 void BKE_pose_iktree_evaluate(struct Depsgraph *depsgraph,
734                               Scene *scene,
735                               Object *object,
736                               int rootchan_index)
737 {
738         const bArmature *armature = (bArmature *)object->data;
739         if (armature->edbo != NULL) {
740                 return;
741         }
742         bPoseChannel *rootchan = pose_pchan_get_indexed(object, rootchan_index);
743         DEG_debug_print_eval_subdata(
744                 depsgraph, __func__, object->id.name, object,
745                 "rootchan", rootchan->name, rootchan);
746         BLI_assert(object->type == OB_ARMATURE);
747         const float ctime = BKE_scene_frame_get(scene); /* not accurate... */
748         if (armature->flag & ARM_RESTPOS) {
749                 return;
750         }
751         BIK_execute_tree(depsgraph, scene, object, rootchan, ctime);
752 }
753
754 void BKE_pose_splineik_evaluate(struct Depsgraph *depsgraph,
755                                 Scene *scene,
756                                 Object *object,
757                                 int rootchan_index)
758
759 {
760         const bArmature *armature = (bArmature *)object->data;
761         if (armature->edbo != NULL) {
762                 return;
763         }
764         bPoseChannel *rootchan = pose_pchan_get_indexed(object, rootchan_index);
765         DEG_debug_print_eval_subdata(
766                 depsgraph, __func__, object->id.name, object,
767                 "rootchan", rootchan->name, rootchan);
768         BLI_assert(object->type == OB_ARMATURE);
769         const float ctime = BKE_scene_frame_get(scene); /* not accurate... */
770         if (armature->flag & ARM_RESTPOS) {
771                 return;
772         }
773         BKE_splineik_execute_tree(depsgraph, scene, object, rootchan, ctime);
774 }
775
776 /* Common part for both original and proxy armatrues. */
777 static void pose_eval_done_common(struct Depsgraph *depsgraph, Object *object)
778 {
779         const bArmature *armature = (bArmature *)object->data;
780         if (armature->edbo != NULL) {
781                 return;
782         }
783         bPose *pose = object->pose;
784         UNUSED_VARS_NDEBUG(pose);
785         BLI_assert(pose != NULL);
786         BKE_armature_cached_bbone_deformation_update(object);
787         BKE_object_eval_boundbox(depsgraph, object);
788 }
789 static void pose_eval_cleanup_common(Object *object)
790 {
791         bPose *pose = object->pose;
792         BLI_assert(pose != NULL);
793         BLI_assert(pose->chan_array != NULL || BLI_listbase_is_empty(&pose->chanbase));
794         MEM_SAFE_FREE(pose->chan_array);
795 }
796
797 void BKE_pose_eval_done(struct Depsgraph *depsgraph, Object *object)
798 {
799         bPose *pose = object->pose;
800         BLI_assert(pose != NULL);
801         UNUSED_VARS_NDEBUG(pose);
802         DEG_debug_print_eval(depsgraph, __func__, object->id.name, object);
803         BLI_assert(object->type == OB_ARMATURE);
804         pose_eval_done_common(depsgraph, object);
805 }
806
807 void BKE_pose_eval_cleanup(struct Depsgraph *depsgraph,
808                            Scene *scene,
809                            Object *object)
810 {
811         bPose *pose = object->pose;
812         BLI_assert(pose != NULL);
813         UNUSED_VARS_NDEBUG(pose);
814         const float ctime = BKE_scene_frame_get(scene); /* not accurate... */
815         DEG_debug_print_eval(depsgraph, __func__, object->id.name, object);
816         BLI_assert(object->type == OB_ARMATURE);
817         /* Release the IK tree. */
818         BIK_release_tree(scene, object, ctime);
819         pose_eval_cleanup_common(object);
820 }
821
822 void BKE_pose_eval_proxy_init(struct Depsgraph *depsgraph, Object *object)
823 {
824         BLI_assert(ID_IS_LINKED(object) && object->proxy_from != NULL);
825         DEG_debug_print_eval(depsgraph, __func__, object->id.name, object);
826
827         pose_pchan_index_create(object->pose);
828         BKE_armature_cached_bbone_deformation_free_data(object);
829 }
830
831 void BKE_pose_eval_proxy_done(struct Depsgraph *depsgraph, Object *object)
832 {
833         BLI_assert(ID_IS_LINKED(object) && object->proxy_from != NULL);
834         DEG_debug_print_eval(depsgraph, __func__, object->id.name, object);
835         pose_eval_done_common(depsgraph, object);
836 }
837
838 void BKE_pose_eval_proxy_cleanup(struct Depsgraph *depsgraph, Object *object)
839 {
840         BLI_assert(ID_IS_LINKED(object) && object->proxy_from != NULL);
841         DEG_debug_print_eval(depsgraph, __func__, object->id.name, object);
842         pose_eval_cleanup_common(object);
843 }
844
845 void BKE_pose_eval_proxy_copy_bone(
846         struct Depsgraph *depsgraph,
847         Object *object,
848         int pchan_index)
849 {
850         const bArmature *armature = (bArmature *)object->data;
851         if (armature->edbo != NULL) {
852                 return;
853         }
854         BLI_assert(ID_IS_LINKED(object) && object->proxy_from != NULL);
855         bPoseChannel *pchan = pose_pchan_get_indexed(object, pchan_index);
856         DEG_debug_print_eval_subdata(
857                 depsgraph, __func__, object->id.name, object,
858                 "pchan", pchan->name, pchan);
859         /* TODO(sergey): Use indexec lookup, once it's guaranteed to be kept
860          * around for the time while proxies are evaluating.
861          */
862 #if 0
863         bPoseChannel *pchan_from = pose_pchan_get_indexed(
864                 object->proxy_from, pchan_index);
865 #else
866         bPoseChannel *pchan_from = BKE_pose_channel_find_name(
867                 object->proxy_from->pose, pchan->name);
868 #endif
869         BLI_assert(pchan != NULL);
870         BLI_assert(pchan_from != NULL);
871         BKE_pose_copyesult_pchan_result(pchan, pchan_from);
872         BKE_pchan_bbone_segments_cache_copy(pchan, pchan_from);
873 }