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