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