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