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