5a2407ca56bbbb14d2e8ca407b9d1a51312457f9
[blender.git] / source / blender / blenkernel / intern / action.c
1 /*
2  * ***** BEGIN GPL LICENSE BLOCK *****
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  *
18  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
19  * All rights reserved.
20  *
21  * Contributor(s): Full recode, Ton Roosendaal, Crete 2005
22  *                               Full recode, Joshua Leung, 2009
23  *
24  * ***** END GPL LICENSE BLOCK *****
25  */
26
27 /** \file blender/blenkernel/intern/action.c
28  *  \ingroup bke
29  */
30
31
32 #include <string.h>
33 #include <math.h>
34 #include <stdlib.h>
35 #include <stddef.h>     
36
37 #include "MEM_guardedalloc.h"
38
39 #include "DNA_anim_types.h"
40 #include "DNA_armature_types.h"
41 #include "DNA_constraint_types.h"
42 #include "DNA_scene_types.h"
43 #include "DNA_object_types.h"
44
45 #include "BLI_blenlib.h"
46 #include "BLI_bpath.h"
47 #include "BLI_math.h"
48 #include "BLI_utildefines.h"
49 #include "BLI_ghash.h"
50
51 #include "BKE_animsys.h"
52 #include "BKE_action.h"
53 #include "BKE_anim.h"
54 #include "BKE_constraint.h"
55 #include "BKE_global.h"
56 #include "BKE_fcurve.h"
57 #include "BKE_library.h"
58 #include "BKE_main.h"
59 #include "BKE_object.h"
60
61 #include "BKE_idprop.h"
62
63 #include "BIK_api.h"
64
65 #include "RNA_access.h"
66
67 /* *********************** NOTE ON POSE AND ACTION **********************
68  *
69  * - Pose is the local (object level) component of armature. The current
70  *   object pose is saved in files, and (will be) is presorted for dependency
71  * - Actions have fewer (or other) channels, and write data to a Pose
72  * - Currently ob->pose data is controlled in where_is_pose only. The (recalc)
73  *   event system takes care of calling that
74  * - The NLA system (here too) uses Poses as interpolation format for Actions
75  * - Therefore we assume poses to be static, and duplicates of poses have channels in
76  *   same order, for quick interpolation reasons
77  *
78  * ****************************** (ton) ************************************ */
79
80 /* ***************** Library data level operations on action ************** */
81
82 bAction *add_empty_action(const char name[])
83 {
84         bAction *act;
85         
86         act= alloc_libblock(&G.main->action, ID_AC, name);
87         
88         return act;
89 }       
90
91 /* .................................. */
92
93 /* temp data for make_local_action */
94 typedef struct tMakeLocalActionContext {
95         bAction *act;       /* original action */
96         bAction *act_new;   /* new action */
97         
98         int is_lib;         /* some action users were libraries */
99         int is_local;       /* some action users were not libraries */
100 } tMakeLocalActionContext;
101
102 /* helper function for make_local_action() - local/lib init step */
103 static void make_localact_init_cb(ID *id, AnimData *adt, void *mlac_ptr)
104 {
105         tMakeLocalActionContext *mlac = (tMakeLocalActionContext *)mlac_ptr;
106         
107         if (adt->action == mlac->act) {
108                 if (id->lib) mlac->is_lib= TRUE;
109                 else mlac->is_local= TRUE;
110         }
111 }
112
113 /* helper function for make_local_action() - change references */
114 static void make_localact_apply_cb(ID *id, AnimData *adt, void *mlac_ptr)
115 {
116         tMakeLocalActionContext *mlac = (tMakeLocalActionContext *)mlac_ptr;
117         
118         if (adt->action == mlac->act) {
119                 if (id->lib == NULL) {
120                         adt->action = mlac->act_new;
121                         
122                         id_us_plus(&mlac->act_new->id);
123                         id_us_min(&mlac->act->id);
124                 }
125         }
126 }
127
128 // does copy_fcurve...
129 void make_local_action(bAction *act)
130 {
131         tMakeLocalActionContext mlac = {act, NULL, FALSE, FALSE};
132         Main *bmain= G.main;
133         
134         if (act->id.lib==NULL) 
135                 return;
136         
137         // XXX: double-check this; it used to be just single-user check, but that was when fake-users were still default
138         if ((act->id.flag & LIB_FAKEUSER) && (act->id.us<=1)) {
139                 id_clear_lib_data(bmain, &act->id);
140                 return;
141         }
142         
143         BKE_animdata_main_cb(bmain, make_localact_init_cb, &mlac);
144         
145         if (mlac.is_local && mlac.is_lib==FALSE) {
146                 id_clear_lib_data(bmain, &act->id);
147         }
148         else if (mlac.is_local && mlac.is_lib) {
149                 mlac.act_new= copy_action(act);
150                 mlac.act_new->id.us= 0;
151
152                 BKE_id_lib_local_paths(bmain, act->id.lib, &mlac.act_new->id);
153
154                 BKE_animdata_main_cb(bmain, make_localact_apply_cb, &mlac);
155         }
156 }
157
158 /* .................................. */
159
160 void free_action(bAction *act)
161 {
162         /* sanity check */
163         if (act == NULL)
164                 return;
165         
166         /* Free F-Curves */
167         free_fcurves(&act->curves);
168         
169         /* Free groups */
170         if (act->groups.first)
171                 BLI_freelistN(&act->groups);
172                 
173         /* Free pose-references (aka local markers) */
174         if (act->markers.first)
175                 BLI_freelistN(&act->markers);
176 }
177
178 /* .................................. */
179
180 bAction *copy_action (bAction *src)
181 {
182         bAction *dst = NULL;
183         bActionGroup *dgrp, *sgrp;
184         FCurve *dfcu, *sfcu;
185         
186         if (src == NULL) 
187                 return NULL;
188         dst= copy_libblock(&src->id);
189         
190         /* duplicate the lists of groups and markers */
191         BLI_duplicatelist(&dst->groups, &src->groups);
192         BLI_duplicatelist(&dst->markers, &src->markers);
193         
194         /* copy F-Curves, fixing up the links as we go */
195         dst->curves.first= dst->curves.last= NULL;
196         
197         for (sfcu= src->curves.first; sfcu; sfcu= sfcu->next) {
198                 /* duplicate F-Curve */
199                 dfcu= copy_fcurve(sfcu);
200                 BLI_addtail(&dst->curves, dfcu);
201                 
202                 /* fix group links (kindof bad list-in-list search, but this is the most reliable way) */
203                 for (dgrp=dst->groups.first, sgrp=src->groups.first; dgrp && sgrp; dgrp=dgrp->next, sgrp=sgrp->next) {
204                         if (sfcu->grp == sgrp) {
205                                 dfcu->grp= dgrp;
206                                 
207                                 if (dgrp->channels.first == sfcu)
208                                         dgrp->channels.first= dfcu;
209                                 if (dgrp->channels.last == sfcu)
210                                         dgrp->channels.last= dfcu;
211                                         
212                                 break;
213                         }
214                 }
215         }
216         
217         return dst;
218 }
219
220 /* *************** Action Groups *************** */
221
222 /* Get the active action-group for an Action */
223 bActionGroup *get_active_actiongroup (bAction *act)
224 {
225         bActionGroup *agrp= NULL;
226         
227         if (act && act->groups.first) { 
228                 for (agrp= act->groups.first; agrp; agrp= agrp->next) {
229                         if (agrp->flag & AGRP_ACTIVE)
230                                 break;
231                 }
232         }
233         
234         return agrp;
235 }
236
237 /* Make the given Action-Group the active one */
238 void set_active_action_group(bAction *act, bActionGroup *agrp, short select)
239 {
240         bActionGroup *grp;
241         
242         /* sanity checks */
243         if (act == NULL)
244                 return;
245         
246         /* Deactive all others */
247         for (grp= act->groups.first; grp; grp= grp->next) {
248                 if ((grp==agrp) && (select))
249                         grp->flag |= AGRP_ACTIVE;
250                 else    
251                         grp->flag &= ~AGRP_ACTIVE;
252         }
253 }
254
255 /* Add a new action group with the given name to the action */
256 bActionGroup *action_groups_add_new (bAction *act, const char name[])
257 {
258         bActionGroup *agrp;
259         
260         /* sanity check: must have action and name */
261         if (ELEM(NULL, act, name))
262                 return NULL;
263         
264         /* allocate a new one */
265         agrp = MEM_callocN(sizeof(bActionGroup), "bActionGroup");
266         
267         /* make it selected, with default name */
268         agrp->flag = AGRP_SELECTED;
269         BLI_strncpy(agrp->name, name[0] ? name : "Group", sizeof(agrp->name));
270         
271         /* add to action, and validate */
272         BLI_addtail(&act->groups, agrp);
273         BLI_uniquename(&act->groups, agrp, "Group", '.', offsetof(bActionGroup, name), sizeof(agrp->name));     
274         
275         /* return the new group */
276         return agrp;
277 }
278
279 /* Add given channel into (active) group 
280  *      - assumes that channel is not linked to anything anymore
281  *      - always adds at the end of the group 
282  */
283 void action_groups_add_channel(bAction *act, bActionGroup *agrp, FCurve *fcurve)
284 {       
285         /* sanity checks */
286         if (ELEM3(NULL, act, agrp, fcurve))
287                 return;
288         
289         /* if no channels anywhere, just add to two lists at the same time */
290         if (act->curves.first == NULL) {
291                 fcurve->next = fcurve->prev = NULL;
292                 
293                 agrp->channels.first = agrp->channels.last = fcurve;
294                 act->curves.first = act->curves.last = fcurve;
295         }
296         
297         /* if the group already has channels, the F-Curve can simply be added to the list 
298          * (i.e. as the last channel in the group)
299          */
300         else if (agrp->channels.first) {
301                 /* if the group's last F-Curve is the action's last F-Curve too, 
302                  * then set the F-Curve as the last for the action first so that
303                  * the lists will be in sync after linking
304                  */
305                 if (agrp->channels.last == act->curves.last)
306                         act->curves.last= fcurve;
307                         
308                 /* link in the given F-Curve after the last F-Curve in the group,
309                  * which means that it should be able to fit in with the rest of the
310                  * list seamlessly
311                  */
312                 BLI_insertlinkafter(&agrp->channels, agrp->channels.last, fcurve);
313         }
314         
315         /* otherwise, need to find the nearest F-Curve in group before/after current to link with */
316         else {
317                 bActionGroup *grp;
318                 
319                 /* firstly, link this F-Curve to the group */
320                 agrp->channels.first = agrp->channels.last = fcurve;
321                 
322                 /* step through the groups preceding this one, finding the F-Curve there to attach this one after */
323                 for (grp= agrp->prev; grp; grp= grp->prev) {
324                         /* if this group has F-Curves, we want weave the given one in right after the last channel there,
325                          * but via the Action's list not this group's list
326                          *      - this is so that the F-Curve is in the right place in the Action,
327                          *        but won't be included in the previous group
328                          */
329                         if (grp->channels.last) {
330                                 /* once we've added, break here since we don't need to search any further... */
331                                 BLI_insertlinkafter(&act->curves, grp->channels.last, fcurve);
332                                 break;
333                         }
334                 }
335                 
336                 /* if grp is NULL, that means we fell through, and this F-Curve should be added as the new first
337                  * since group is (effectively) the first group. Thus, the existing first F-Curve becomes the 
338                  * second in the chain, etc. etc.
339                  */
340                 if (grp == NULL)
341                         BLI_insertlinkbefore(&act->curves, act->curves.first, fcurve);
342         }
343         
344         /* set the F-Curve's new group */
345         fcurve->grp= agrp;
346 }       
347
348 /* Remove the given channel from all groups */
349 void action_groups_remove_channel(bAction *act, FCurve *fcu)
350 {
351         /* sanity checks */
352         if (ELEM(NULL, act, fcu))       
353                 return;
354         
355         /* check if any group used this directly */
356         if (fcu->grp) {
357                 bActionGroup *agrp= fcu->grp;
358                 
359                 if (agrp->channels.first == agrp->channels.last) {
360                         if (agrp->channels.first == fcu) {
361                                 agrp->channels.first= NULL;
362                                 agrp->channels.last= NULL;
363                         }
364                 }
365                 else if (agrp->channels.first == fcu) {
366                         if ((fcu->next) && (fcu->next->grp==agrp))
367                                 agrp->channels.first= fcu->next;
368                         else
369                                 agrp->channels.first= NULL;
370                 }
371                 else if (agrp->channels.last == fcu) {
372                         if ((fcu->prev) && (fcu->prev->grp==agrp))
373                                 agrp->channels.last= fcu->prev;
374                         else
375                                 agrp->channels.last= NULL;
376                 }
377                 
378                 fcu->grp= NULL;
379         }
380         
381         /* now just remove from list */
382         BLI_remlink(&act->curves, fcu);
383 }
384
385 /* Find a group with the given name */
386 bActionGroup *action_groups_find_named (bAction *act, const char name[])
387 {
388         /* sanity checks */
389         if (ELEM3(NULL, act, act->groups.first, name) || (name[0] == 0))
390                 return NULL;
391                 
392         /* do string comparisons */
393         return BLI_findstring(&act->groups, name, offsetof(bActionGroup, name));
394 }
395
396 /* Clear all 'temp' flags on all groups */
397 void action_groups_clear_tempflags(bAction *act)
398 {
399         bActionGroup *agrp;
400         
401         /* sanity checks */
402         if (ELEM(NULL, act, act->groups.first))
403                 return;
404                 
405         /* flag clearing loop */
406         for (agrp = act->groups.first; agrp; agrp = agrp->next)
407                 agrp->flag &= ~AGRP_TEMP;
408 }
409
410 /* *************** Pose channels *************** */
411
412 /* usually used within a loop, so we got a N^2 slowdown */
413 bPoseChannel *get_pose_channel(const bPose *pose, const char *name)
414 {
415         if (ELEM(NULL, pose, name) || (name[0] == 0))
416                 return NULL;
417         
418         if (pose->chanhash)
419                 return BLI_ghash_lookup(pose->chanhash, (void *)name);
420         
421         return BLI_findstring(&((bPose *)pose)->chanbase, name, offsetof(bPoseChannel, name));
422 }
423
424 /* Use with care, not on Armature poses but for temporal ones */
425 /* (currently used for action constraints and in rebuild_pose) */
426 bPoseChannel *verify_pose_channel(bPose *pose, const char *name)
427 {
428         bPoseChannel *chan;
429         
430         if (pose == NULL)
431                 return NULL;
432         
433         /* See if this channel exists */
434         chan= BLI_findstring(&pose->chanbase, name, offsetof(bPoseChannel, name));
435         if (chan) {
436                 return chan;
437         }
438
439         /* If not, create it and add it */
440         chan = MEM_callocN(sizeof(bPoseChannel), "verifyPoseChannel");
441         
442         BLI_strncpy(chan->name, name, sizeof(chan->name));
443         /* init vars to prevent math errors */
444         unit_qt(chan->quat);
445         unit_axis_angle(chan->rotAxis, &chan->rotAngle);
446         chan->size[0] = chan->size[1] = chan->size[2] = 1.0f;
447         
448         chan->limitmin[0]= chan->limitmin[1]= chan->limitmin[2]= -180.0f;
449         chan->limitmax[0]= chan->limitmax[1]= chan->limitmax[2]= 180.0f;
450         chan->stiffness[0]= chan->stiffness[1]= chan->stiffness[2]= 0.0f;
451         chan->ikrotweight = chan->iklinweight = 0.0f;
452         unit_m4(chan->constinv);
453         
454         chan->protectflag = OB_LOCK_ROT4D;      /* lock by components by default */
455         
456         BLI_addtail(&pose->chanbase, chan);
457         free_pose_channels_hash(pose);
458         
459         return chan;
460 }
461
462 /* Find the active posechannel for an object (we can't just use pose, as layer info is in armature) */
463 bPoseChannel *get_active_posechannel (Object *ob)
464 {
465         bArmature *arm= (ob) ? ob->data : NULL;
466         bPoseChannel *pchan;
467
468         if (ELEM3(NULL, ob, ob->pose, arm)) {
469                 return NULL;
470         }
471
472         /* find active */
473         for (pchan= ob->pose->chanbase.first; pchan; pchan= pchan->next) {
474                 if ((pchan->bone) && (pchan->bone == arm->act_bone) && (pchan->bone->layer & arm->layer))
475                         return pchan;
476         }
477         
478         return NULL;
479 }
480
481 const char *get_ikparam_name(bPose *pose)
482 {
483         if (pose) {
484                 switch (pose->iksolver) {
485                 case IKSOLVER_LEGACY:
486                         return NULL;
487                 case IKSOLVER_ITASC:
488                         return "bItasc";
489                 }
490         }
491         return NULL;
492 }
493 /* dst should be freed already, makes entire duplicate */
494 void copy_pose(bPose **dst, bPose *src, int copycon)
495 {
496         bPose *outPose;
497         bPoseChannel *pchan;
498         ListBase listb;
499         
500         if (!src) {
501                 *dst=NULL;
502                 return;
503         }
504         
505         if (*dst==src) {
506                 printf("copy_pose source and target are the same\n");
507                 *dst=NULL;
508                 return;
509         }
510         
511         outPose= MEM_callocN(sizeof(bPose), "pose");
512         
513         BLI_duplicatelist(&outPose->chanbase, &src->chanbase);
514         
515         outPose->iksolver = src->iksolver;
516         outPose->ikdata = NULL;
517         outPose->ikparam = MEM_dupallocN(src->ikparam);
518         
519         for (pchan=outPose->chanbase.first; pchan; pchan=pchan->next) {
520                 // TODO: rename this argument...
521                 if (copycon) {
522                         copy_constraints(&listb, &pchan->constraints, TRUE);  // copy_constraints NULLs listb
523                         pchan->constraints= listb;
524                         pchan->mpath= NULL; /* motion paths should not get copied yet... */
525                 }
526                 
527                 if (pchan->prop) {
528                         pchan->prop= IDP_CopyProperty(pchan->prop);
529                 }
530         }
531
532         /* for now, duplicate Bone Groups too when doing this */
533         if (copycon)
534                 BLI_duplicatelist(&outPose->agroups, &src->agroups);
535         
536         *dst=outPose;
537 }
538
539 void init_pose_itasc(bItasc *itasc)
540 {
541         if (itasc) {
542                 itasc->iksolver = IKSOLVER_ITASC;
543                 itasc->minstep = 0.01f;
544                 itasc->maxstep = 0.06f;
545                 itasc->numiter = 100;
546                 itasc->numstep = 4;
547                 itasc->precision = 0.005f;
548                 itasc->flag = ITASC_AUTO_STEP|ITASC_INITIAL_REITERATION;
549                 itasc->feedback = 20.0f;
550                 itasc->maxvel = 50.0f;
551                 itasc->solver = ITASC_SOLVER_SDLS;
552                 itasc->dampmax = 0.5;
553                 itasc->dampeps = 0.15;
554         }
555 }
556 void init_pose_ikparam(bPose *pose)
557 {
558         bItasc *itasc;
559         switch (pose->iksolver) {
560         case IKSOLVER_ITASC:
561                 itasc = MEM_callocN(sizeof(bItasc), "itasc");
562                 init_pose_itasc(itasc);
563                 pose->ikparam = itasc;
564                 break;
565         case IKSOLVER_LEGACY:
566         default:
567                 pose->ikparam = NULL;
568                 break;
569         }
570 }
571
572 void make_pose_channels_hash(bPose *pose) 
573 {
574         if (!pose->chanhash) {
575                 bPoseChannel *pchan;
576
577                 pose->chanhash= BLI_ghash_new(BLI_ghashutil_strhash, BLI_ghashutil_strcmp, "make_pose_chan gh");
578                 for (pchan=pose->chanbase.first; pchan; pchan=pchan->next)
579                         BLI_ghash_insert(pose->chanhash, pchan->name, pchan);
580         }
581 }
582
583 void free_pose_channels_hash(bPose *pose) 
584 {
585         if (pose->chanhash) {
586                 BLI_ghash_free(pose->chanhash, NULL, NULL);
587                 pose->chanhash= NULL;
588         }
589 }
590
591
592 void free_pose_channel(bPoseChannel *pchan)
593 {
594
595         if (pchan->mpath) {
596                 animviz_free_motionpath(pchan->mpath);
597                 pchan->mpath= NULL;
598         }
599
600         free_constraints(&pchan->constraints);
601         
602         if (pchan->prop) {
603                 IDP_FreeProperty(pchan->prop);
604                 MEM_freeN(pchan->prop);
605         }
606 }
607
608 void free_pose_channels(bPose *pose) 
609 {
610         bPoseChannel *pchan;
611         
612         if (pose->chanbase.first) {
613                 for (pchan = pose->chanbase.first; pchan; pchan=pchan->next)
614                         free_pose_channel(pchan);
615                 
616                 BLI_freelistN(&pose->chanbase);
617         }
618
619         free_pose_channels_hash(pose);
620 }
621
622 void free_pose(bPose *pose)
623 {
624         if (pose) {
625                 /* free pose-channels */
626                 free_pose_channels(pose);
627                 
628                 /* free pose-groups */
629                 if (pose->agroups.first)
630                         BLI_freelistN(&pose->agroups);
631                 
632                 /* free IK solver state */
633                 BIK_clear_data(pose);
634                 
635                 /* free IK solver param */
636                 if (pose->ikparam)
637                         MEM_freeN(pose->ikparam);
638                 
639                 /* free pose */
640                 MEM_freeN(pose);
641         }
642 }
643
644 static void copy_pose_channel_data(bPoseChannel *pchan, const bPoseChannel *chan)
645 {
646         bConstraint *pcon, *con;
647         
648         copy_v3_v3(pchan->loc, chan->loc);
649         copy_v3_v3(pchan->size, chan->size);
650         copy_v3_v3(pchan->eul, chan->eul);
651         copy_v3_v3(pchan->rotAxis, chan->rotAxis);
652         pchan->rotAngle= chan->rotAngle;
653         copy_qt_qt(pchan->quat, chan->quat);
654         pchan->rotmode= chan->rotmode;
655         copy_m4_m4(pchan->chan_mat, (float(*)[4])chan->chan_mat);
656         copy_m4_m4(pchan->pose_mat, (float(*)[4])chan->pose_mat);
657         pchan->flag= chan->flag;
658         
659         con= chan->constraints.first;
660         for (pcon= pchan->constraints.first; pcon && con; pcon= pcon->next, con= con->next) {
661                 pcon->enforce= con->enforce;
662                 pcon->headtail= con->headtail;
663         }
664 }
665
666 /* makes copies of internal data, unlike copy_pose_channel_data which only
667  * copies the pose state.
668  * hint: use when copying bones in editmode (on returned value from verify_pose_channel) */
669 void duplicate_pose_channel_data(bPoseChannel *pchan, const bPoseChannel *pchan_from)
670 {
671         /* copy transform locks */
672         pchan->protectflag = pchan_from->protectflag;
673
674         /* copy rotation mode */
675         pchan->rotmode = pchan_from->rotmode;
676
677         /* copy bone group */
678         pchan->agrp_index= pchan_from->agrp_index;
679
680         /* ik (dof) settings */
681         pchan->ikflag = pchan_from->ikflag;
682         copy_v3_v3(pchan->limitmin, pchan_from->limitmin);
683         copy_v3_v3(pchan->limitmax, pchan_from->limitmax);
684         copy_v3_v3(pchan->stiffness, pchan_from->stiffness);
685         pchan->ikstretch= pchan_from->ikstretch;
686         pchan->ikrotweight= pchan_from->ikrotweight;
687         pchan->iklinweight= pchan_from->iklinweight;
688
689         /* constraints */
690         copy_constraints(&pchan->constraints, &pchan_from->constraints, TRUE);
691
692         /* id-properties */
693         if (pchan->prop) {
694                 /* unlikely but possible it exists */
695                 IDP_FreeProperty(pchan->prop);
696                 MEM_freeN(pchan->prop);
697                 pchan->prop= NULL;
698         }
699         if (pchan_from->prop) {
700                 pchan->prop= IDP_CopyProperty(pchan_from->prop);
701         }
702
703         /* custom shape */
704         pchan->custom= pchan_from->custom;
705 }
706
707
708 /* checks for IK constraint, Spline IK, and also for Follow-Path constraint.
709  * can do more constraints flags later 
710  */
711 /* pose should be entirely OK */
712 void update_pose_constraint_flags(bPose *pose)
713 {
714         bPoseChannel *pchan, *parchan;
715         bConstraint *con;
716         
717         /* clear */
718         for (pchan= pose->chanbase.first; pchan; pchan= pchan->next) {
719                 pchan->constflag= 0;
720         }
721         pose->flag &= ~POSE_CONSTRAINTS_TIMEDEPEND;
722         
723         /* detect */
724         for (pchan= pose->chanbase.first; pchan; pchan=pchan->next) {
725                 for (con= pchan->constraints.first; con; con= con->next) {
726                         if (con->type==CONSTRAINT_TYPE_KINEMATIC) {
727                                 bKinematicConstraint *data = (bKinematicConstraint*)con->data;
728                                 
729                                 pchan->constflag |= PCHAN_HAS_IK;
730                                 
731                                 if (data->tar==NULL || (data->tar->type==OB_ARMATURE && data->subtarget[0]==0))
732                                         pchan->constflag |= PCHAN_HAS_TARGET;
733                                 
734                                 /* negative rootbone = recalc rootbone index. used in do_versions */
735                                 if (data->rootbone<0) {
736                                         data->rootbone= 0;
737                                         
738                                         if (data->flag & CONSTRAINT_IK_TIP) parchan= pchan;
739                                         else parchan= pchan->parent;
740                                         
741                                         while (parchan) {
742                                                 data->rootbone++;
743                                                 if ((parchan->bone->flag & BONE_CONNECTED)==0)
744                                                         break;
745                                                 parchan= parchan->parent;
746                                         }
747                                 }
748                         }
749                         else if (con->type == CONSTRAINT_TYPE_FOLLOWPATH) {
750                                 bFollowPathConstraint *data= (bFollowPathConstraint *)con->data;
751                                 
752                                 /* for drawing constraint colors when color set allows this */
753                                 pchan->constflag |= PCHAN_HAS_CONST;
754                                 
755                                 /* if we have a valid target, make sure that this will get updated on frame-change
756                                  * (needed for when there is no anim-data for this pose)
757                                  */
758                                 if ((data->tar) && (data->tar->type==OB_CURVE))
759                                         pose->flag |= POSE_CONSTRAINTS_TIMEDEPEND;
760                         }
761                         else if (con->type == CONSTRAINT_TYPE_SPLINEIK)
762                                 pchan->constflag |= PCHAN_HAS_SPLINEIK;
763                         else 
764                                 pchan->constflag |= PCHAN_HAS_CONST;
765                 }
766         }
767 }
768
769 /* Clears all BONE_UNKEYED flags for every pose channel in every pose 
770  * This should only be called on frame changing, when it is acceptable to
771  * do this. Otherwise, these flags should not get cleared as poses may get lost.
772  */
773 void framechange_poses_clear_unkeyed(void)
774 {
775         Object *ob;
776         bPose *pose;
777         bPoseChannel *pchan;
778         
779         /* This needs to be done for each object that has a pose */
780         // TODO: proxies may/may not be correctly handled here... (this needs checking) 
781         for (ob= G.main->object.first; ob; ob= ob->id.next) {
782                 /* we only need to do this on objects with a pose */
783                 if ( (pose= ob->pose) ) {
784                         for (pchan= pose->chanbase.first; pchan; pchan= pchan->next) {
785                                 if (pchan->bone) 
786                                         pchan->bone->flag &= ~BONE_UNKEYED;
787                         }
788                 }
789         }
790 }
791
792 /* ************************** Bone Groups ************************** */
793
794 /* Adds a new bone-group */
795 void pose_add_group(Object *ob)
796 {
797         bPose *pose= (ob) ? ob->pose : NULL;
798         bActionGroup *grp;
799         
800         if (ELEM(NULL, ob, ob->pose))
801                 return;
802         
803         grp= MEM_callocN(sizeof(bActionGroup), "PoseGroup");
804         BLI_strncpy(grp->name, "Group", sizeof(grp->name));
805         BLI_addtail(&pose->agroups, grp);
806         BLI_uniquename(&pose->agroups, grp, "Group", '.', offsetof(bActionGroup, name), sizeof(grp->name));
807         
808         pose->active_group= BLI_countlist(&pose->agroups);
809 }
810
811 /* Remove the active bone-group */
812 void pose_remove_group(Object *ob)
813 {
814         bPose *pose= (ob) ? ob->pose : NULL;
815         bActionGroup *grp = NULL;
816         bPoseChannel *pchan;
817         
818         /* sanity checks */
819         if (ELEM(NULL, ob, pose))
820                 return;
821         if (pose->active_group <= 0)
822                 return;
823         
824         /* get group to remove */
825         grp= BLI_findlink(&pose->agroups, pose->active_group-1);
826         if (grp) {
827                 /* adjust group references (the trouble of using indices!):
828                  *      - firstly, make sure nothing references it 
829                  *      - also, make sure that those after this item get corrected
830                  */
831                 for (pchan= pose->chanbase.first; pchan; pchan= pchan->next) {
832                         if (pchan->agrp_index == pose->active_group)
833                                 pchan->agrp_index= 0;
834                         else if (pchan->agrp_index > pose->active_group)
835                                 pchan->agrp_index--;
836                 }
837                 
838                 /* now, remove it from the pose */
839                 BLI_freelinkN(&pose->agroups, grp);
840                 pose->active_group--;
841                 if (pose->active_group < 0 || pose->agroups.first == NULL) {
842                         pose->active_group= 0;
843                 }
844         }
845 }
846
847 /* ************** F-Curve Utilities for Actions ****************** */
848
849 /* Check if the given action has any keyframes */
850 short action_has_motion(const bAction *act)
851 {
852         FCurve *fcu;
853         
854         /* return on the first F-Curve that has some keyframes/samples defined */
855         if (act) {
856                 for (fcu= act->curves.first; fcu; fcu= fcu->next) {
857                         if (fcu->totvert)
858                                 return 1;
859                 }
860         }
861         
862         /* nothing found */
863         return 0;
864 }
865
866 /* Calculate the extents of given action */
867 void calc_action_range(const bAction *act, float *start, float *end, short incl_modifiers)
868 {
869         FCurve *fcu;
870         float min=999999999.0f, max=-999999999.0f;
871         short foundvert=0, foundmod=0;
872
873         if (act) {
874                 for (fcu= act->curves.first; fcu; fcu= fcu->next) {
875                         /* if curve has keyframes, consider them first */
876                         if (fcu->totvert) {
877                                 float nmin, nmax;
878                                 
879                                 /* get extents for this curve */
880                                 // TODO: allow enabling/disabling this?
881                                 calc_fcurve_range(fcu, &nmin, &nmax, FALSE, TRUE);
882                                 
883                                 /* compare to the running tally */
884                                 min= MIN2(min, nmin);
885                                 max= MAX2(max, nmax);
886                                 
887                                 foundvert= 1;
888                         }
889                         
890                         /* if incl_modifiers is enabled, need to consider modifiers too
891                          *      - only really care about the last modifier
892                          */
893                         if ((incl_modifiers) && (fcu->modifiers.last)) {
894                                 FModifier *fcm= fcu->modifiers.last;
895                                 
896                                 /* only use the maximum sensible limits of the modifiers if they are more extreme */
897                                 switch (fcm->type) {
898                                         case FMODIFIER_TYPE_LIMITS: /* Limits F-Modifier */
899                                         {
900                                                 FMod_Limits *fmd= (FMod_Limits *)fcm->data;
901                                                 
902                                                 if (fmd->flag & FCM_LIMIT_XMIN) {
903                                                         min= MIN2(min, fmd->rect.xmin);
904                                                 }
905                                                 if (fmd->flag & FCM_LIMIT_XMAX) {
906                                                         max= MAX2(max, fmd->rect.xmax);
907                                                 }
908                                         }
909                                                 break;
910                                                 
911                                         case FMODIFIER_TYPE_CYCLES: /* Cycles F-Modifier */
912                                         {
913                                                 FMod_Cycles *fmd= (FMod_Cycles *)fcm->data;
914                                                 
915                                                 if (fmd->before_mode != FCM_EXTRAPOLATE_NONE)
916                                                         min= MINAFRAMEF;
917                                                 if (fmd->after_mode != FCM_EXTRAPOLATE_NONE)
918                                                         max= MAXFRAMEF;
919                                         }
920                                                 break;
921                                                 
922                                         // TODO: function modifier may need some special limits
923                                                 
924                                         default: /* all other standard modifiers are on the infinite range... */
925                                                 min= MINAFRAMEF;
926                                                 max= MAXFRAMEF;
927                                                 break;
928                                 }
929                                 
930                                 foundmod= 1;
931                         }
932                 }
933         }       
934         
935         if (foundvert || foundmod) {
936                 if (min==max) max+= 1.0f;
937                 *start= min;
938                 *end= max;
939         }
940         else {
941                 *start= 0.0f;
942                 *end= 1.0f;
943         }
944 }
945
946 /* Return flags indicating which transforms the given object/posechannel has 
947  *      - if 'curves' is provided, a list of links to these curves are also returned
948  */
949 short action_get_item_transforms(bAction *act, Object *ob, bPoseChannel *pchan, ListBase *curves)
950 {
951         PointerRNA ptr;
952         FCurve *fcu;
953         char *basePath=NULL;
954         short flags=0;
955         
956         /* build PointerRNA from provided data to obtain the paths to use */
957         if (pchan)
958                 RNA_pointer_create((ID *)ob, &RNA_PoseBone, pchan, &ptr);
959         else if (ob)
960                 RNA_id_pointer_create((ID *)ob, &ptr);
961         else    
962                 return 0;
963                 
964         /* get the basic path to the properties of interest */
965         basePath= RNA_path_from_ID_to_struct(&ptr);
966         if (basePath == NULL)
967                 return 0;
968                 
969         /* search F-Curves for the given properties 
970          *      - we cannot use the groups, since they may not be grouped in that way...
971          */
972         for (fcu= act->curves.first; fcu; fcu= fcu->next) {
973                 char *bPtr=NULL, *pPtr=NULL;
974                 
975                 /* if enough flags have been found, we can stop checking unless we're also getting the curves */
976                 if ((flags == ACT_TRANS_ALL) && (curves == NULL))
977                         break;
978                         
979                 /* just in case... */
980                 if (fcu->rna_path == NULL)
981                         continue;
982                 
983                 /* step 1: check for matching base path */
984                 bPtr= strstr(fcu->rna_path, basePath);
985                 
986                 if (bPtr) {
987                         /* we must add len(basePath) bytes to the match so that we are at the end of the 
988                          * base path so that we don't get false positives with these strings in the names
989                          */
990                         bPtr += strlen(basePath);
991                         
992                         /* step 2: check for some property with transforms 
993                          *      - to speed things up, only check for the ones not yet found 
994                          *        unless we're getting the curves too
995                          *      - if we're getting the curves, the BLI_genericNodeN() creates a LinkData
996                          *        node wrapping the F-Curve, which then gets added to the list
997                          *      - once a match has been found, the curve cannot possibly be any other one
998                          */
999                         if ((curves) || (flags & ACT_TRANS_LOC) == 0) {
1000                                 pPtr= strstr(bPtr, "location");
1001                                 if (pPtr) {
1002                                         flags |= ACT_TRANS_LOC;
1003                                         
1004                                         if (curves) 
1005                                                 BLI_addtail(curves, BLI_genericNodeN(fcu));
1006                                         continue;
1007                                 }
1008                         }
1009                         
1010                         if ((curves) || (flags & ACT_TRANS_SCALE) == 0) {
1011                                 pPtr= strstr(bPtr, "scale");
1012                                 if (pPtr) {
1013                                         flags |= ACT_TRANS_SCALE;
1014                                         
1015                                         if (curves) 
1016                                                 BLI_addtail(curves, BLI_genericNodeN(fcu));
1017                                         continue;
1018                                 }
1019                         }
1020                         
1021                         if ((curves) || (flags & ACT_TRANS_ROT) == 0) {
1022                                 pPtr= strstr(bPtr, "rotation");
1023                                 if (pPtr) {
1024                                         flags |= ACT_TRANS_ROT;
1025                                         
1026                                         if (curves) 
1027                                                 BLI_addtail(curves, BLI_genericNodeN(fcu));
1028                                         continue;
1029                                 }
1030                         }
1031                         
1032                         if ((curves) || (flags & ACT_TRANS_PROP) == 0) {
1033                                 /* custom properties only */
1034                                 pPtr= strstr(bPtr, "[\""); /* extra '"' comment here to keep my texteditor functionlist working :) */  
1035                                 if (pPtr) {
1036                                         flags |= ACT_TRANS_PROP;
1037                                         
1038                                         if (curves)
1039                                                 BLI_addtail(curves, BLI_genericNodeN(fcu));
1040                                         continue;
1041                                 }
1042                         }
1043                 }
1044         }
1045         
1046         /* free basePath */
1047         MEM_freeN(basePath);
1048         
1049         /* return flags found */
1050         return flags;
1051 }
1052
1053 /* ************** Pose Management Tools ****************** */
1054
1055 /* Copy the data from the action-pose (src) into the pose */
1056 /* both args are assumed to be valid */
1057 /* exported to game engine */
1058 /* Note! this assumes both poses are aligned, this isn't always true when dealing with user poses */
1059 void extract_pose_from_pose(bPose *pose, const bPose *src)
1060 {
1061         const bPoseChannel *schan;
1062         bPoseChannel *pchan= pose->chanbase.first;
1063
1064         if (pose==src) {
1065                 printf("extract_pose_from_pose source and target are the same\n");
1066                 return;
1067         }
1068
1069         for (schan=src->chanbase.first; (schan && pchan); schan=schan->next, pchan= pchan->next) {
1070                 copy_pose_channel_data(pchan, schan);
1071         }
1072 }
1073
1074 /* for do_all_pose_actions, clears the pose. Now also exported for proxy and tools */
1075 void rest_pose(bPose *pose)
1076 {
1077         bPoseChannel *pchan;
1078         
1079         if (!pose)
1080                 return;
1081         
1082         memset(pose->stride_offset, 0, sizeof(pose->stride_offset));
1083         memset(pose->cyclic_offset, 0, sizeof(pose->cyclic_offset));
1084         
1085         for (pchan=pose->chanbase.first; pchan; pchan= pchan->next) {
1086                 zero_v3(pchan->loc);
1087                 zero_v3(pchan->eul);
1088                 unit_qt(pchan->quat);
1089                 unit_axis_angle(pchan->rotAxis, &pchan->rotAngle);
1090                 pchan->size[0]= pchan->size[1]= pchan->size[2]= 1.0f;
1091
1092                 pchan->flag &= ~(POSE_LOC|POSE_ROT|POSE_SIZE);
1093         }
1094 }
1095
1096 /* both poses should be in sync */
1097 void copy_pose_result(bPose *to, bPose *from)
1098 {
1099         bPoseChannel *pchanto, *pchanfrom;
1100         
1101         if (to==NULL || from==NULL) {
1102                 printf("pose result copy error to:%p from:%p\n", (void *)to, (void *)from); // debug temp
1103                 return;
1104         }
1105
1106         if (to==from) {
1107                 printf("copy_pose_result source and target are the same\n");
1108                 return;
1109         }
1110
1111
1112         for (pchanfrom= from->chanbase.first; pchanfrom; pchanfrom= pchanfrom->next) {
1113                 pchanto= get_pose_channel(to, pchanfrom->name);
1114                 if (pchanto) {
1115                         copy_m4_m4(pchanto->pose_mat, pchanfrom->pose_mat);
1116                         copy_m4_m4(pchanto->chan_mat, pchanfrom->chan_mat);
1117                         
1118                         /* used for local constraints */
1119                         copy_v3_v3(pchanto->loc, pchanfrom->loc);
1120                         copy_qt_qt(pchanto->quat, pchanfrom->quat);
1121                         copy_v3_v3(pchanto->eul, pchanfrom->eul);
1122                         copy_v3_v3(pchanto->size, pchanfrom->size);
1123                         
1124                         copy_v3_v3(pchanto->pose_head, pchanfrom->pose_head);
1125                         copy_v3_v3(pchanto->pose_tail, pchanfrom->pose_tail);
1126                         
1127                         pchanto->rotmode= pchanfrom->rotmode;
1128                         pchanto->flag= pchanfrom->flag;
1129                         pchanto->protectflag= pchanfrom->protectflag;
1130                 }
1131         }
1132 }
1133
1134 /* For the calculation of the effects of an Action at the given frame on an object 
1135  * This is currently only used for the Action Constraint 
1136  */
1137 void what_does_obaction(Object *ob, Object *workob, bPose *pose, bAction *act, char groupname[], float cframe)
1138 {
1139         bActionGroup *agrp= action_groups_find_named(act, groupname);
1140         
1141         /* clear workob */
1142         clear_workob(workob);
1143         
1144         /* init workob */
1145         copy_m4_m4(workob->obmat, ob->obmat);
1146         copy_m4_m4(workob->parentinv, ob->parentinv);
1147         copy_m4_m4(workob->constinv, ob->constinv);
1148         workob->parent= ob->parent;
1149         
1150         workob->rotmode= ob->rotmode;
1151         
1152         workob->trackflag= ob->trackflag;
1153         workob->upflag= ob->upflag;
1154         
1155         workob->partype= ob->partype;
1156         workob->par1= ob->par1;
1157         workob->par2= ob->par2;
1158         workob->par3= ob->par3;
1159
1160         workob->constraints.first = ob->constraints.first;
1161         workob->constraints.last = ob->constraints.last;
1162         
1163         workob->pose= pose;     /* need to set pose too, since this is used for both types of Action Constraint */
1164
1165         BLI_strncpy(workob->parsubstr, ob->parsubstr, sizeof(workob->parsubstr));
1166         BLI_strncpy(workob->id.name, "OB<ConstrWorkOb>", sizeof(workob->id.name)); /* we don't use real object name, otherwise RNA screws with the real thing */
1167         
1168         /* if we're given a group to use, it's likely to be more efficient (though a bit more dangerous) */
1169         if (agrp) {
1170                 /* specifically evaluate this group only */
1171                 PointerRNA id_ptr;
1172                 
1173                 /* get RNA-pointer for the workob's ID */
1174                 RNA_id_pointer_create(&workob->id, &id_ptr);
1175                 
1176                 /* execute action for this group only */
1177                 animsys_evaluate_action_group(&id_ptr, act, agrp, NULL, cframe);
1178         }
1179         else {
1180                 AnimData adt= {NULL};
1181                 
1182                 /* init animdata, and attach to workob */
1183                 workob->adt= &adt;
1184                 
1185                 adt.recalc= ADT_RECALC_ANIM;
1186                 adt.action= act;
1187                 
1188                 /* execute effects of Action on to workob (or it's PoseChannels) */
1189                 BKE_animsys_evaluate_animdata(NULL, &workob->id, &adt, cframe, ADT_RECALC_ANIM);
1190         }
1191 }
1192
1193 /* ********** NLA with non-poses works with ipo channels ********** */
1194
1195 #if 0 // XXX OLD ANIMATION SYSTEM (TO BE REMOVED)
1196
1197 /* ************************ Blending with NLA *************** */
1198
1199 static void blend_pose_strides(bPose *dst, bPose *src, float srcweight, short mode)
1200 {
1201         float dstweight;
1202         
1203         switch (mode) {
1204                 case ACTSTRIPMODE_BLEND:
1205                         dstweight = 1.0F - srcweight;
1206                         break;
1207                 case ACTSTRIPMODE_ADD:
1208                         dstweight = 1.0F;
1209                         break;
1210                 default :
1211                         dstweight = 1.0F;
1212         }
1213         
1214         interp_v3_v3v3(dst->stride_offset, dst->stride_offset, src->stride_offset, srcweight);
1215 }
1216
1217
1218 /*
1219  * bone matching diagram, strips A and B
1220  * 
1221  *                  .------------------------.
1222  *                  |         A              |
1223  *                  '------------------------'
1224  *                  .          .             b2
1225  *                  .          .-------------v----------.
1226  *                  .          |         B   .          |
1227  *                  .          '------------------------'
1228  *                  .          .             .
1229  *                  .          .             .
1230  * offset:          .    0     .    A-B      .  A-b2+B
1231  *                  .          .             .
1232  *
1233  * */
1234
1235
1236 static void blend_pose_offset_bone(bActionStrip *strip, bPose *dst, bPose *src, float srcweight, short mode)
1237 {
1238         /* matching offset bones */
1239         /* take dst offset, and put src on on that location */
1240         
1241         if (strip->offs_bone[0]==0)
1242                 return;
1243         
1244         /* are we also blending with matching bones? */
1245         if (strip->prev && strip->start>=strip->prev->start) {
1246                 bPoseChannel *dpchan= get_pose_channel(dst, strip->offs_bone);
1247                 if (dpchan) {
1248                         bPoseChannel *spchan= get_pose_channel(src, strip->offs_bone);
1249                         if (spchan) {
1250                                 float vec[3];
1251                                 
1252                                 /* dst->ctime has the internal strip->prev action time */
1253                                 /* map this time to nla time */
1254                                 
1255                                 float ctime= get_actionstrip_frame(strip, src->ctime, 1);
1256                                 
1257                                 if ( ctime > strip->prev->end) {
1258                                         bActionChannel *achan;
1259                                         
1260                                         /* add src to dest, minus the position of src on strip->prev->end */
1261                                         
1262                                         ctime= get_actionstrip_frame(strip, strip->prev->end, 0);
1263                                         
1264                                         achan= get_action_channel(strip->act, strip->offs_bone);
1265                                         if (achan && achan->ipo) {
1266                                                 bPoseChannel pchan;
1267                                                 /* Evaluates and sets the internal ipo value */
1268                                                 calc_ipo(achan->ipo, ctime);
1269                                                 /* This call also sets the pchan flags */
1270                                                 execute_action_ipo(achan, &pchan);
1271                                                 
1272                                                 /* store offset that moves src to location of pchan */
1273                                                 sub_v3_v3v3(vec, dpchan->loc, pchan.loc);
1274                                                 
1275                                                 mul_mat3_m4_v3(dpchan->bone->arm_mat, vec);
1276                                         }
1277                                 }
1278                                 else {
1279                                         /* store offset that moves src to location of dst */
1280                                         
1281                                         sub_v3_v3v3(vec, dpchan->loc, spchan->loc);
1282                                         mul_mat3_m4_v3(dpchan->bone->arm_mat, vec);
1283                                 }
1284                                 
1285                                 /* if blending, we only add with factor scrweight */
1286                                 mul_v3_fl(vec, srcweight);
1287                                 
1288                                 add_v3_v3(dst->cyclic_offset, vec);
1289                         }
1290                 }
1291         }
1292         
1293         add_v3_v3(dst->cyclic_offset, src->cyclic_offset);
1294 }
1295
1296 /* added "sizecorr" here, to allow armatures to be scaled and still have striding.
1297  * Only works for uniform scaling. In general I'd advise against scaling armatures ever though! (ton)
1298  */
1299 static float stridechannel_frame(Object *ob, float sizecorr, bActionStrip *strip, Path *path, float pathdist, float *stride_offset)
1300 {
1301         bAction *act= strip->act;
1302         const char *name= strip->stridechannel;
1303         bActionChannel *achan= get_action_channel(act, name);
1304         int stride_axis= strip->stride_axis;
1305
1306         if (achan && achan->ipo) {
1307                 IpoCurve *icu= NULL;
1308                 float minx=0.0f, maxx=0.0f, miny=0.0f, maxy=0.0f;
1309                 int foundvert= 0;
1310                 
1311                 if (stride_axis==0) stride_axis= AC_LOC_X;
1312                 else if (stride_axis==1) stride_axis= AC_LOC_Y;
1313                 else stride_axis= AC_LOC_Z;
1314                 
1315                 /* calculate the min/max */
1316                 for (icu=achan->ipo->curve.first; icu; icu=icu->next) {
1317                         if (icu->adrcode==stride_axis) {
1318                                 if (icu->totvert>1) {
1319                                         foundvert= 1;
1320                                         minx= icu->bezt[0].vec[1][0];
1321                                         maxx= icu->bezt[icu->totvert-1].vec[1][0];
1322                                         
1323                                         miny= icu->bezt[0].vec[1][1];
1324                                         maxy= icu->bezt[icu->totvert-1].vec[1][1];
1325                                 }
1326                                 break;
1327                         }
1328                 }
1329                 
1330                 if (foundvert && miny!=maxy) {
1331                         float stridelen= sizecorr*fabs(maxy-miny), striptime;
1332                         float actiondist, pdist, pdistNewNormalized, offs;
1333                         float vec1[4], vec2[4], dir[3];
1334                         
1335                         /* internal cycling, actoffs is in frames */
1336                         offs= stridelen*strip->actoffs/(maxx-minx);
1337                         
1338                         /* amount path moves object */
1339                         pdist = (float)fmod (pathdist+offs, stridelen);
1340                         striptime= pdist/stridelen;
1341                         
1342                         /* amount stride bone moves */
1343                         actiondist= sizecorr*eval_icu(icu, minx + striptime*(maxx-minx)) - miny;
1344                         
1345                         pdist = fabs(actiondist) - pdist;
1346                         pdistNewNormalized = (pathdist+pdist)/path->totdist;
1347                         
1348                         /* now we need to go pdist further (or less) on cu path */
1349                         where_on_path(ob, (pathdist)/path->totdist, vec1, dir); /* vec needs size 4 */
1350                         if (pdistNewNormalized <= 1) {
1351                                 // search for correction in positive path-direction
1352                                 where_on_path(ob, pdistNewNormalized, vec2, dir);       /* vec needs size 4 */
1353                                 sub_v3_v3v3(stride_offset, vec2, vec1);
1354                         }
1355                         else {
1356                                 // we reached the end of the path, search backwards instead
1357                                 where_on_path(ob, (pathdist-pdist)/path->totdist, vec2, dir);   /* vec needs size 4 */
1358                                 sub_v3_v3v3(stride_offset, vec1, vec2);
1359                         }
1360                         mul_mat3_m4_v3(ob->obmat, stride_offset);
1361                         return striptime;
1362                 }
1363         }
1364         return 0.0f;
1365 }
1366
1367 static void cyclic_offs_bone(Object *ob, bPose *pose, bActionStrip *strip, float time)
1368 {
1369         /* only called when strip has cyclic, so >= 1.0f works... */
1370         if (time >= 1.0f) {
1371                 bActionChannel *achan= get_action_channel(strip->act, strip->offs_bone);
1372
1373                 if (achan && achan->ipo) {
1374                         IpoCurve *icu= NULL;
1375                         Bone *bone;
1376                         float min[3]={0.0f, 0.0f, 0.0f}, max[3]={0.0f, 0.0f, 0.0f};
1377                         int index=0, foundvert= 0;
1378                         
1379                         /* calculate the min/max */
1380                         for (icu=achan->ipo->curve.first; icu; icu=icu->next) {
1381                                 if (icu->totvert>1) {
1382                                         
1383                                         if (icu->adrcode==AC_LOC_X)
1384                                                 index= 0;
1385                                         else if (icu->adrcode==AC_LOC_Y)
1386                                                 index= 1;
1387                                         else if (icu->adrcode==AC_LOC_Z)
1388                                                 index= 2;
1389                                         else
1390                                                 continue;
1391                                 
1392                                         foundvert= 1;
1393                                         min[index]= icu->bezt[0].vec[1][1];
1394                                         max[index]= icu->bezt[icu->totvert-1].vec[1][1];
1395                                 }
1396                         }
1397                         if (foundvert) {
1398                                 /* bring it into armature space */
1399                                 sub_v3_v3v3(min, max, min);
1400                                 bone= get_named_bone(ob->data, strip->offs_bone);       /* weak */
1401                                 if (bone) {
1402                                         mul_mat3_m4_v3(bone->arm_mat, min);
1403                                         
1404                                         /* dominant motion, cyclic_offset was cleared in rest_pose */
1405                                         if (strip->flag & (ACTSTRIP_CYCLIC_USEX | ACTSTRIP_CYCLIC_USEY | ACTSTRIP_CYCLIC_USEZ)) {
1406                                                 if (strip->flag & ACTSTRIP_CYCLIC_USEX) pose->cyclic_offset[0]= time*min[0];
1407                                                 if (strip->flag & ACTSTRIP_CYCLIC_USEY) pose->cyclic_offset[1]= time*min[1];
1408                                                 if (strip->flag & ACTSTRIP_CYCLIC_USEZ) pose->cyclic_offset[2]= time*min[2];
1409                                         }
1410                                         else {
1411                                                 if ( fabs(min[0]) >= fabs(min[1]) && fabs(min[0]) >= fabs(min[2]))
1412                                                         pose->cyclic_offset[0]= time*min[0];
1413                                                 else if ( fabs(min[1]) >= fabs(min[0]) && fabs(min[1]) >= fabs(min[2]))
1414                                                         pose->cyclic_offset[1]= time*min[1];
1415                                                 else
1416                                                         pose->cyclic_offset[2]= time*min[2];
1417                                         }
1418                                 }
1419                         }
1420                 }
1421         }
1422 }
1423
1424 /* simple case for now; only the curve path with constraint value > 0.5 */
1425 /* blending we might do later... */
1426 static Object *get_parent_path(Object *ob)
1427 {
1428         bConstraint *con;
1429         
1430         if (ob->parent && ob->parent->type==OB_CURVE)
1431                 return ob->parent;
1432         
1433         for (con = ob->constraints.first; con; con=con->next) {
1434                 if (con->type==CONSTRAINT_TYPE_FOLLOWPATH) {
1435                         if (con->enforce>0.5f) {
1436                                 bFollowPathConstraint *data= con->data;
1437                                 return data->tar;
1438                         }
1439                 }
1440         }
1441         return NULL;
1442 }
1443
1444 /* ************** do the action ************ */
1445
1446 /* ----- nla, etc. --------- */
1447
1448 static void do_nla(Scene *scene, Object *ob, int blocktype)
1449 {
1450         bPose *tpose= NULL;
1451         Key *key= NULL;
1452         ListBase tchanbase={NULL, NULL}, chanbase={NULL, NULL};
1453         bActionStrip *strip, *striplast=NULL, *stripfirst=NULL;
1454         float striptime, frametime, length, actlength;
1455         float blendfac, stripframe;
1456         float scene_cfra= BKE_curframe(scene);
1457         int     doit, dostride;
1458         
1459         if (blocktype==ID_AR) {
1460                 copy_pose(&tpose, ob->pose, 1);
1461                 rest_pose(ob->pose);            // potentially destroying current not-keyed pose
1462         }
1463         else {
1464                 key= ob_get_key(ob);
1465         }
1466         
1467         /* check on extend to left or right, when no strip is hit by 'cfra' */
1468         for (strip=ob->nlastrips.first; strip; strip=strip->next) {
1469                 /* escape loop on a hit */
1470                 if ( scene_cfra >= strip->start && scene_cfra <= strip->end + 0.1f)     /* note 0.1 comes back below */
1471                         break;
1472                 if (scene_cfra < strip->start) {
1473                         if (stripfirst==NULL)
1474                                 stripfirst= strip;
1475                         else if (stripfirst->start > strip->start)
1476                                 stripfirst= strip;
1477                 }
1478                 else if (scene_cfra > strip->end) {
1479                         if (striplast==NULL)
1480                                 striplast= strip;
1481                         else if (striplast->end < strip->end)
1482                                 striplast= strip;
1483                 }
1484         }
1485         if (strip==NULL) {      /* extend */
1486                 if (striplast)
1487                         scene_cfra= striplast->end;
1488                 else if (stripfirst)
1489                         scene_cfra= stripfirst->start;
1490         }
1491         
1492         /* and now go over all strips */
1493         for (strip=ob->nlastrips.first; strip; strip=strip->next) {
1494                 doit=dostride= 0;
1495                 
1496                 if (strip->act && !(strip->flag & ACTSTRIP_MUTE)) {     /* so theres an action */
1497                         
1498                         /* Determine if the current frame is within the strip's range */
1499                         length = strip->end-strip->start;
1500                         actlength = strip->actend-strip->actstart;
1501                         striptime = (scene_cfra - strip->start) / length;
1502                         stripframe = (scene_cfra - strip->start);
1503
1504                         if (striptime>=0.0) {
1505                                 
1506                                 if (blocktype==ID_AR) 
1507                                         rest_pose(tpose);
1508                                 
1509                                 /* To handle repeat, we add 0.1 frame extra to make sure the last frame is included */
1510                                 if (striptime < 1.0f + 0.1f/length) {
1511                                         
1512                                         /* Handle path */
1513                                         if ((strip->flag & ACTSTRIP_USESTRIDE) && (blocktype==ID_AR) && (ob->ipoflag & OB_DISABLE_PATH)==0) {
1514                                                 Object *parent= get_parent_path(ob);
1515                                                 
1516                                                 if (parent) {
1517                                                         Curve *cu = parent->data;
1518                                                         float ctime, pdist;
1519                                                         
1520                                                         if (cu->flag & CU_PATH) {
1521                                                                 /* Ensure we have a valid path */
1522                                                                 if (cu->path==NULL || cu->path->data==NULL) makeDispListCurveTypes(scene, parent, 0);
1523                                                                 if (cu->path) {
1524                                                                         
1525                                                                         /* Find the position on the path */
1526                                                                         ctime= bsystem_time(scene, ob, scene_cfra, 0.0);
1527                                                                         
1528                                                                         if (calc_ipo_spec(cu->ipo, CU_SPEED, &ctime)==0) {
1529                                                                                 /* correct for actions not starting on zero */
1530                                                                                 ctime= (ctime - strip->actstart)/cu->pathlen;
1531                                                                                 CLAMP(ctime, 0.0, 1.0);
1532                                                                         }
1533                                                                         pdist = ctime*cu->path->totdist;
1534                                                                         
1535                                                                         if (tpose && strip->stridechannel[0]) {
1536                                                                                 striptime= stridechannel_frame(parent, ob->size[0], strip, cu->path, pdist, tpose->stride_offset);
1537                                                                         }                                                                       
1538                                                                         else {
1539                                                                                 if (strip->stridelen) {
1540                                                                                         striptime = pdist / strip->stridelen;
1541                                                                                         striptime = (float)fmod (striptime+strip->actoffs, 1.0);
1542                                                                                 }
1543                                                                                 else
1544                                                                                         striptime = 0;
1545                                                                         }
1546                                                                         
1547                                                                         frametime = (striptime * actlength) + strip->actstart;
1548                                                                         frametime= bsystem_time(scene, ob, frametime, 0.0);
1549                                                                         
1550                                                                         if (blocktype==ID_AR) {
1551                                                                                 extract_pose_from_action (tpose, strip->act, frametime);
1552                                                                         }
1553                                                                         else if (blocktype==ID_OB) {
1554                                                                                 extract_ipochannels_from_action(&tchanbase, &ob->id, strip->act, "Object", frametime);
1555                                                                                 if (key)
1556                                                                                         extract_ipochannels_from_action(&tchanbase, &key->id, strip->act, "Shape", frametime);
1557                                                                         }
1558                                                                         doit=dostride= 1;
1559                                                                 }
1560                                                         }
1561                                                 }
1562                                         }
1563                                         /* To handle repeat, we add 0.1 frame extra to make sure the last frame is included */
1564                                         else {
1565                                                 
1566                                                 /* Mod to repeat */
1567                                                 if (strip->repeat!=1.0f) {
1568                                                         float cycle= striptime*strip->repeat;
1569                                                         
1570                                                         striptime = (float)fmod (cycle, 1.0f + 0.1f/length);
1571                                                         cycle-= striptime;
1572                                                         
1573                                                         if (blocktype==ID_AR)
1574                                                                 cyclic_offs_bone(ob, tpose, strip, cycle);
1575                                                 }
1576
1577                                                 frametime = (striptime * actlength) + strip->actstart;
1578                                                 frametime= nla_time(scene, frametime, (float)strip->repeat);
1579                                                         
1580                                                 if (blocktype==ID_AR) {
1581                                                         extract_pose_from_action (tpose, strip->act, frametime);
1582                                                 }
1583                                                 else if (blocktype==ID_OB) {
1584                                                         extract_ipochannels_from_action(&tchanbase, &ob->id, strip->act, "Object", frametime);
1585                                                         if (key)
1586                                                                 extract_ipochannels_from_action(&tchanbase, &key->id, strip->act, "Shape", frametime);
1587                                                 }
1588                                                 
1589                                                 doit=1;
1590                                         }
1591                                 }
1592                                 /* Handle extend */
1593                                 else {
1594                                         if (strip->flag & ACTSTRIP_HOLDLASTFRAME) {
1595                                                 /* we want the strip to hold on the exact fraction of the repeat value */
1596                                                 
1597                                                 frametime = actlength * (strip->repeat-(int)strip->repeat);
1598                                                 if (frametime<=0.000001f) frametime= actlength; /* rounding errors... */
1599                                                 frametime= bsystem_time(scene, ob, frametime+strip->actstart, 0.0);
1600                                                 
1601                                                 if (blocktype==ID_AR)
1602                                                         extract_pose_from_action (tpose, strip->act, frametime);
1603                                                 else if (blocktype==ID_OB) {
1604                                                         extract_ipochannels_from_action(&tchanbase, &ob->id, strip->act, "Object", frametime);
1605                                                         if (key)
1606                                                                 extract_ipochannels_from_action(&tchanbase, &key->id, strip->act, "Shape", frametime);
1607                                                 }
1608                                                 
1609                                                 /* handle cycle hold */
1610                                                 if (strip->repeat!=1.0f) {
1611                                                         if (blocktype==ID_AR)
1612                                                                 cyclic_offs_bone(ob, tpose, strip, strip->repeat-1.0f);
1613                                                 }
1614                                                 
1615                                                 doit=1;
1616                                         }
1617                                 }
1618                                 
1619                                 /* Handle blendin & blendout */
1620                                 if (doit) {
1621                                         /* Handle blendin */
1622                                         
1623                                         if (strip->blendin>0.0 && stripframe<=strip->blendin && scene_cfra>=strip->start) {
1624                                                 blendfac = stripframe/strip->blendin;
1625                                         }
1626                                         else if (strip->blendout>0.0 && stripframe>=(length-strip->blendout) && scene_cfra<=strip->end) {
1627                                                 blendfac = (length-stripframe)/(strip->blendout);
1628                                         }
1629                                         else
1630                                                 blendfac = 1;
1631                                         
1632                                         if (blocktype==ID_AR) {/* Blend this pose with the accumulated pose */
1633                                                 /* offset bone, for matching cycles */
1634                                                 blend_pose_offset_bone (strip, ob->pose, tpose, blendfac, strip->mode);
1635                                                 
1636                                                 blend_poses (ob->pose, tpose, blendfac, strip->mode);
1637                                                 if (dostride)
1638                                                         blend_pose_strides (ob->pose, tpose, blendfac, strip->mode);
1639                                         }
1640                                         else {
1641                                                 blend_ipochannels(&chanbase, &tchanbase, blendfac, strip->mode);
1642                                                 BLI_freelistN(&tchanbase);
1643                                         }
1644                                 }
1645                         }                                       
1646                 }
1647         }
1648         
1649         if (blocktype==ID_OB) {
1650                 execute_ipochannels(&chanbase);
1651         }
1652         else if (blocktype==ID_AR) {
1653                 /* apply stride offset to object */
1654                 add_v3_v3(ob->obmat[3], ob->pose->stride_offset);
1655         }
1656         
1657         /* free */
1658         if (tpose)
1659                 free_pose(tpose);
1660         if (chanbase.first)
1661                 BLI_freelistN(&chanbase);
1662 }
1663
1664 #endif // XXX OLD ANIMATION SYSTEM (TO BE REMOVED)