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