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