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