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