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