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