bugfix #6672
[blender.git] / source / blender / blenkernel / intern / action.c
1 /**
2  * $Id$
3  *
4  * ***** BEGIN GPL/BL DUAL 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. The Blender
10  * Foundation also sells licenses for use in proprietary software under
11  * the Blender License.  See http://www.blender.org/BL/ for information
12  * about this.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU General Public License for more details.
18  *
19  * You should have received a copy of the GNU General Public License
20  * along with this program; if not, write to the Free Software Foundation,
21  * Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
22  *
23  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
24  * All rights reserved.
25  *
26  * Contributor(s): Full recode, Ton Roosendaal, Crete 2005
27  *
28  * ***** END GPL/BL DUAL LICENSE BLOCK *****
29  */
30
31 #ifdef HAVE_CONFIG_H
32 #include <config.h>
33 #endif
34
35 #include <string.h>
36 #include <math.h>
37 #include <stdlib.h>     /* for NULL */
38
39 #include "MEM_guardedalloc.h"
40
41 #include "DNA_action_types.h"
42 #include "DNA_armature_types.h"
43 #include "DNA_constraint_types.h"
44 #include "DNA_curve_types.h"
45 #include "DNA_ipo_types.h"
46 #include "DNA_key_types.h"
47 #include "DNA_nla_types.h"
48 #include "DNA_object_types.h"
49 #include "DNA_scene_types.h"
50
51 #include "BKE_action.h"
52 #include "BKE_anim.h"
53 #include "BKE_armature.h"
54 #include "BKE_blender.h"
55 #include "BKE_constraint.h"
56 #include "BKE_displist.h"
57 #include "BKE_global.h"
58 #include "BKE_ipo.h"
59 #include "BKE_key.h"
60 #include "BKE_lattice.h"
61 #include "BKE_library.h"
62 #include "BKE_main.h"
63 #include "BKE_object.h"
64 #include "BKE_utildefines.h"
65
66 #include "BLI_arithb.h"
67 #include "BLI_blenlib.h"
68
69 #include "nla.h"
70
71 /* *********************** NOTE ON POSE AND ACTION **********************
72
73   - Pose is the local (object level) component of armature. The current
74     object pose is saved in files, and (will be) is presorted for dependency
75   - Actions have fewer (or other) channels, and write data to a Pose
76   - Currently ob->pose data is controlled in where_is_pose only. The (recalc)
77     event system takes care of calling that
78   - The NLA system (here too) uses Poses as interpolation format for Actions
79   - Therefore we assume poses to be static, and duplicates of poses have channels in
80     same order, for quick interpolation reasons
81
82   ****************************** (ton) ************************************ */
83
84 /* ***************** Library data level operations on action ************** */
85
86 static void make_local_action_channels(bAction *act)
87 {
88         bActionChannel *chan;
89         bConstraintChannel *conchan;
90         
91         for (chan=act->chanbase.first; chan; chan=chan->next) {
92                 if(chan->ipo) {
93                         if(chan->ipo->id.us==1) {
94                                 chan->ipo->id.lib= NULL;
95                                 chan->ipo->id.flag= LIB_LOCAL;
96                                 new_id(0, (ID *)chan->ipo, 0);
97                         }
98                         else {
99                                 chan->ipo= copy_ipo(chan->ipo);
100                         }
101                 }
102                 for (conchan=chan->constraintChannels.first; conchan; conchan=conchan->next) {
103                         if(conchan->ipo) {
104                                 if(conchan->ipo->id.us==1) {
105                                         conchan->ipo->id.lib= NULL;
106                                         conchan->ipo->id.flag= LIB_LOCAL;
107                                         new_id(0, (ID *)conchan->ipo, 0);
108                                 }
109                                 else {
110                                         conchan->ipo= copy_ipo(conchan->ipo);
111                                 }
112                         }
113                 }
114         }
115                                         
116 }
117
118 void make_local_action(bAction *act)
119 {
120         Object *ob;
121         bAction *actn;
122         int local=0, lib=0;
123         
124         if(act->id.lib==0) return;
125         if(act->id.us==1) {
126                 act->id.lib= 0;
127                 act->id.flag= LIB_LOCAL;
128                 make_local_action_channels(act);
129                 new_id(0, (ID *)act, 0);
130                 return;
131         }
132         
133         ob= G.main->object.first;
134         while(ob) {
135                 if(ob->action==act) {
136                         if(ob->id.lib) lib= 1;
137                         else local= 1;
138                 }
139                 ob= ob->id.next;
140         }
141         
142         if(local && lib==0) {
143                 act->id.lib= 0;
144                 act->id.flag= LIB_LOCAL;
145                 make_local_action_channels(act);
146                 new_id(0, (ID *)act, 0);
147         }
148         else if(local && lib) {
149                 actn= copy_action(act);
150                 actn->id.us= 0;
151                 
152                 ob= G.main->object.first;
153                 while(ob) {
154                         if(ob->action==act) {
155                                 
156                                 if(ob->id.lib==0) {
157                                         ob->action = actn;
158                                         actn->id.us++;
159                                         act->id.us--;
160                                 }
161                         }
162                         ob= ob->id.next;
163                 }
164         }
165 }
166
167
168 void free_action(bAction *act)
169 {
170         bActionChannel *chan;
171         
172         /* Free channels */
173         for (chan=act->chanbase.first; chan; chan=chan->next){
174                 if (chan->ipo)
175                         chan->ipo->id.us--;
176                 free_constraint_channels(&chan->constraintChannels);
177         }
178         
179         if (act->chanbase.first)
180                 BLI_freelistN (&act->chanbase);
181 }
182
183 bAction* copy_action(bAction *src)
184 {
185         bAction *dst = NULL;
186         bActionChannel *dchan, *schan;
187         
188         if(!src) return NULL;
189         
190         dst= copy_libblock(src);
191         duplicatelist(&(dst->chanbase), &(src->chanbase));
192         
193         for (dchan=dst->chanbase.first, schan=src->chanbase.first; dchan; dchan=dchan->next, schan=schan->next){
194                 dchan->ipo = copy_ipo(dchan->ipo);
195                 copy_constraint_channels(&dchan->constraintChannels, &schan->constraintChannels);
196         }
197         dst->id.flag |= LIB_FAKEUSER;
198         dst->id.us++;
199         return dst;
200 }
201
202
203
204 /* ************************ Pose channels *************** */
205
206 /* usually used within a loop, so we got a N^2 slowdown */
207 bPoseChannel *get_pose_channel(const bPose *pose, const char *name)
208 {
209         bPoseChannel *chan;
210
211         if(pose==NULL) return NULL;
212         
213         for (chan=pose->chanbase.first; chan; chan=chan->next) {
214                 if(chan->name[0] == name[0])
215                         if (!strcmp (chan->name, name))
216                                 return chan;
217         }
218
219         return NULL;
220 }
221
222 /* Use with care, not on Armature poses but for temporal ones */
223 /* (currently used for action constraints and in rebuild_pose) */
224 bPoseChannel *verify_pose_channel(bPose* pose, const char* name)
225 {
226         bPoseChannel *chan;
227         
228         if (!pose){
229                 return NULL;
230         }
231         
232         /*      See if this channel exists */
233         for (chan=pose->chanbase.first; chan; chan=chan->next){
234                 if (!strcmp (name, chan->name))
235                         return chan;
236         }
237         
238         /* If not, create it and add it */
239         chan = MEM_callocN(sizeof(bPoseChannel), "verifyPoseChannel");
240         
241         strncpy (chan->name, name, 31);
242         /* init vars to prevent mat errors */
243         chan->quat[0] = 1.0F;
244         chan->size[0] = chan->size[1] = chan->size[2] = 1.0F;
245         
246         chan->limitmin[0]= chan->limitmin[1]= chan->limitmin[2]= -180.0f;
247         chan->limitmax[0]= chan->limitmax[1]= chan->limitmax[2]= 180.0f;
248         chan->stiffness[0]= chan->stiffness[1]= chan->stiffness[2]= 0.0f;
249         
250         BLI_addtail (&pose->chanbase, chan);
251         
252         return chan;
253 }
254
255
256 /* dst should be freed already, makes entire duplicate */
257 void copy_pose(bPose **dst, bPose *src, int copycon)
258 {
259         bPose *outPose;
260         bPoseChannel    *pchan;
261         ListBase listb;
262         
263         if (!src){
264                 *dst=NULL;
265                 return;
266         }
267         
268         outPose= MEM_callocN(sizeof(bPose), "pose");
269         
270         duplicatelist (&outPose->chanbase, &src->chanbase);
271         
272         if (copycon) {
273                 for (pchan=outPose->chanbase.first; pchan; pchan=pchan->next) {
274                         copy_constraints(&listb, &pchan->constraints);  // copy_constraints NULLs listb
275                         pchan->constraints= listb;
276                         pchan->path= NULL;
277                 }
278         }
279         
280         *dst=outPose;
281 }
282
283 void free_pose_channels(bPose *pose) 
284 {
285         bPoseChannel *pchan;
286         
287         if (pose->chanbase.first){
288                 for (pchan = pose->chanbase.first; pchan; pchan=pchan->next){
289                         if(pchan->path)
290                                 MEM_freeN(pchan->path);
291                         free_constraints(&pchan->constraints);
292                 }
293                 BLI_freelistN (&pose->chanbase);
294         }
295 }
296
297 static void copy_pose_channel_data(bPoseChannel *pchan, const bPoseChannel *chan)
298 {
299         bConstraint *pcon, *con;
300         
301         VECCOPY(pchan->loc, chan->loc);
302         VECCOPY(pchan->size, chan->size);
303         QUATCOPY(pchan->quat, chan->quat);
304         pchan->flag= chan->flag;
305         
306         con= chan->constraints.first;
307         for(pcon= pchan->constraints.first; pcon; pcon= pcon->next)
308                 pcon->enforce= con->enforce;
309 }
310
311 /* checks for IK constraint, can do more constraints flags later */
312 /* pose should be entirely OK */
313 void update_pose_constraint_flags(bPose *pose)
314 {
315         bPoseChannel *pchan, *parchan;
316         bConstraint *con;
317         
318         /* clear */
319         for (pchan = pose->chanbase.first; pchan; pchan=pchan->next) {
320                 pchan->constflag= 0;
321         }
322         /* detect */
323         for (pchan = pose->chanbase.first; pchan; pchan=pchan->next) {
324                 for(con= pchan->constraints.first; con; con= con->next) {
325                         if(con->type==CONSTRAINT_TYPE_KINEMATIC) {
326                                 bKinematicConstraint *data = (bKinematicConstraint*)con->data;
327                                 
328                                 pchan->constflag |= PCHAN_HAS_IK;
329                                 
330                                 if(data->tar==NULL || (data->tar->type==OB_ARMATURE && data->subtarget[0]==0))
331                                         pchan->constflag |= PCHAN_HAS_TARGET;
332                                 
333                                 /* negative rootbone = recalc rootbone index. used in do_versions */
334                                 if(data->rootbone<0) {
335                                         data->rootbone= 0;
336                                         
337                                         if(data->flag & CONSTRAINT_IK_TIP) parchan= pchan;
338                                         else parchan= pchan->parent;
339                                         
340                                         while(parchan) {
341                                                 data->rootbone++;
342                                                 if((parchan->bone->flag & BONE_CONNECTED)==0)
343                                                         break;
344                                                 parchan= parchan->parent;
345                                         }
346                                 }
347                         }
348                         else pchan->constflag |= PCHAN_HAS_CONST;
349                 }
350         }
351 }
352
353
354 /* ************************ END Pose channels *************** */
355
356 /* ************************ Action channels *************** */
357
358
359 bActionChannel *get_action_channel(bAction *act, const char *name)
360 {
361         bActionChannel *chan;
362         
363         if (!act || !name)
364                 return NULL;
365         
366         for (chan = act->chanbase.first; chan; chan=chan->next){
367                 if (!strcmp (chan->name, name))
368                         return chan;
369         }
370         
371         return NULL;
372 }
373
374 /* returns existing channel, or adds new one. In latter case it doesnt activate it, context is required for that*/
375 bActionChannel *verify_action_channel(bAction *act, const char *name)
376 {
377         bActionChannel *chan;
378         
379         chan= get_action_channel(act, name);
380         if(chan==NULL) {
381                 if (!chan) {
382                         chan = MEM_callocN (sizeof(bActionChannel), "actionChannel");
383                         strncpy (chan->name, name, 31);
384                         BLI_addtail (&act->chanbase, chan);
385                 }
386         }
387         return chan;
388 }
389
390 /* ************** time ****************** */
391
392 static bActionStrip *get_active_strip(Object *ob)
393 {
394         bActionStrip *strip;
395         
396         if(ob->action==NULL)
397                 return NULL;
398         
399         for (strip=ob->nlastrips.first; strip; strip=strip->next)
400                 if(strip->flag & ACTSTRIP_ACTIVE)
401                         break;
402         
403         if(strip && strip->act==ob->action)
404                 return strip;
405         return NULL;
406 }
407
408 /* non clipped mapping of strip */
409 static float get_actionstrip_frame(bActionStrip *strip, float cframe, int invert)
410 {
411         float length, actlength, repeat;
412         
413         if (strip->flag & ACTSTRIP_USESTRIDE)
414                 repeat= 1.0f;
415         else
416                 repeat= strip->repeat;
417         
418         length = strip->end-strip->start;
419         if(length==0.0f)
420                 length= 1.0f;
421         actlength = strip->actend-strip->actstart;
422         
423         
424         
425         if(invert)
426                 return length*(cframe - strip->actstart)/(repeat*actlength) + strip->start;
427         else
428                 return repeat*actlength*(cframe - strip->start)/length + strip->actstart;
429 }
430
431 /* if the conditions match, it converts current time to strip time */
432 float get_action_frame(Object *ob, float cframe)
433 {
434         bActionStrip *strip= get_active_strip(ob);
435         
436         if(strip)
437                 return get_actionstrip_frame(strip, cframe, 0);
438         return cframe;
439 }
440
441 /* inverted, strip time to current time */
442 float get_action_frame_inv(Object *ob, float cframe)
443 {
444         bActionStrip *strip= get_active_strip(ob);
445         
446         if(strip)
447                 return get_actionstrip_frame(strip, cframe, 1);
448         return cframe;
449 }
450
451
452 /* ************************ Blending with NLA *************** */
453
454 static void blend_pose_strides(bPose *dst, bPose *src, float srcweight, short mode)
455 {
456         float dstweight;
457         
458         switch (mode){
459                 case POSE_BLEND:
460                         dstweight = 1.0F - srcweight;
461                         break;
462                 case POSE_ADD:
463                         dstweight = 1.0F;
464                         break;
465                 default :
466                         dstweight = 1.0F;
467         }
468         
469         VecLerpf(dst->stride_offset, dst->stride_offset, src->stride_offset, srcweight);
470 }
471
472
473 /* 
474
475 bone matching diagram, strips A and B
476
477                  .------------------------.
478                  |         A              |
479                  '------------------------'
480                                  .          .             b2
481                  .          .-------------v----------.
482                  .              |         B   .          |
483                  .          '------------------------'
484                  .          .             .
485                  .          .             .
486 offset:          .    0     .    A-B      .  A-b2+B     
487                  .          .             .
488
489 */
490
491
492 static void blend_pose_offset_bone(bActionStrip *strip, bPose *dst, bPose *src, float srcweight, short mode)
493 {
494         /* matching offset bones */
495         /* take dst offset, and put src on on that location */
496         
497         if(strip->offs_bone[0]==0)
498                 return;
499         
500         /* are we also blending with matching bones? */
501         if(strip->prev && strip->start>=strip->prev->start) {
502                 bPoseChannel *dpchan= get_pose_channel(dst, strip->offs_bone);
503                 if(dpchan) {
504                         bPoseChannel *spchan= get_pose_channel(src, strip->offs_bone);
505                         if(spchan) {
506                                 float vec[3];
507                                 
508                                 /* dst->ctime has the internal strip->prev action time */
509                                 /* map this time to nla time */
510                                 
511                                 float ctime= get_actionstrip_frame(strip, src->ctime, 1);
512                                 
513                                 if( ctime > strip->prev->end) {
514                                         bActionChannel *achan;
515                                         
516                                         /* add src to dest, minus the position of src on strip->prev->end */
517                                         
518                                         ctime= get_actionstrip_frame(strip, strip->prev->end, 0);
519                                         
520                                         achan= get_action_channel(strip->act, strip->offs_bone);
521                                         if(achan && achan->ipo) {
522                                                 bPoseChannel pchan;
523                                                 /* Evaluates and sets the internal ipo value */
524                                                 calc_ipo(achan->ipo, ctime);
525                                                 /* This call also sets the pchan flags */
526                                                 execute_action_ipo(achan, &pchan);
527                                                 
528                                                 /* store offset that moves src to location of pchan */
529                                                 VecSubf(vec, dpchan->loc, pchan.loc);
530                                                 
531                                                 Mat4Mul3Vecfl(dpchan->bone->arm_mat, vec);
532                                         }
533                                 }
534                                 else {
535                                         /* store offset that moves src to location of dst */
536                                         
537                                         VecSubf(vec, dpchan->loc, spchan->loc);
538                                         Mat4Mul3Vecfl(dpchan->bone->arm_mat, vec);
539                                 }
540                                 
541                                 /* if blending, we only add with factor scrweight */
542                                 VecMulf(vec, srcweight);
543                                 
544                                 VecAddf(dst->cyclic_offset, dst->cyclic_offset, vec);
545                         }
546                 }
547         }
548         
549         VecAddf(dst->cyclic_offset, dst->cyclic_offset, src->cyclic_offset);
550 }
551
552
553 /* Only allowed for Poses with identical channels */
554 void blend_poses(bPose *dst, bPose *src, float srcweight, short mode)
555 {
556         bPoseChannel *dchan;
557         const bPoseChannel *schan;
558         bConstraint *dcon, *scon;
559         float   dquat[4], squat[4];
560         float dstweight;
561         int i;
562         
563         switch (mode){
564         case POSE_BLEND:
565                 dstweight = 1.0F - srcweight;
566                 break;
567         case POSE_ADD:
568                 dstweight = 1.0F;
569                 break;
570         default :
571                 dstweight = 1.0F;
572         }
573         
574         schan= src->chanbase.first;
575         for (dchan = dst->chanbase.first; dchan; dchan=dchan->next, schan= schan->next){
576                 if (schan->flag & (POSE_ROT|POSE_LOC|POSE_SIZE)) {
577                         /* replaced quat->matrix->quat conversion with decent quaternion interpol (ton) */
578                         
579                         /* Do the transformation blend */
580                         if (schan->flag & POSE_ROT) {
581                                 QUATCOPY(dquat, dchan->quat);
582                                 QUATCOPY(squat, schan->quat);
583                                 if(mode==POSE_BLEND)
584                                         QuatInterpol(dchan->quat, dquat, squat, srcweight);
585                                 else
586                                         QuatAdd(dchan->quat, dquat, squat, srcweight);
587                                 
588                                 NormalQuat (dchan->quat);
589                         }
590
591                         for (i=0; i<3; i++){
592                                 if (schan->flag & POSE_LOC)
593                                         dchan->loc[i] = (dchan->loc[i]*dstweight) + (schan->loc[i]*srcweight);
594                                 if (schan->flag & POSE_SIZE)
595                                         dchan->size[i] = 1.0f + ((dchan->size[i]-1.0f)*dstweight) + ((schan->size[i]-1.0f)*srcweight);
596                         }
597                         dchan->flag |= schan->flag;
598                 }
599                 for(dcon= dchan->constraints.first, scon= schan->constraints.first; dcon && scon; dcon= dcon->next, scon= scon->next) {
600                         /* no 'add' option for constraint blending */
601                         dcon->enforce= dcon->enforce*(1.0f-srcweight) + scon->enforce*srcweight;
602                 }
603         }
604         
605         /* this pose is now in src time */
606         dst->ctime= src->ctime;
607 }
608
609
610 void calc_action_range(const bAction *act, float *start, float *end, int incl_hidden)
611 {
612         const bActionChannel *chan;
613         const bConstraintChannel *conchan;
614         const IpoCurve  *icu;
615         float min=999999999.0f, max=-999999999.0;
616         int     foundvert=0;
617
618         if(act) {
619                 for (chan=act->chanbase.first; chan; chan=chan->next) {
620                         if(incl_hidden || (chan->flag & ACHAN_HIDDEN)==0) {
621                                 if(chan->ipo) {
622                                         for (icu=chan->ipo->curve.first; icu; icu=icu->next) {
623                                                 if(icu->totvert) {
624                                                         min= MIN2 (min, icu->bezt[0].vec[1][0]);
625                                                         max= MAX2 (max, icu->bezt[icu->totvert-1].vec[1][0]);
626                                                         foundvert=1;
627                                                 }
628                                         }
629                                 }
630                                 for (conchan=chan->constraintChannels.first; conchan; conchan=conchan->next) {
631                                         if(conchan->ipo) {
632                                                 for (icu=conchan->ipo->curve.first; icu; icu=icu->next) {
633                                                         if(icu->totvert) {
634                                                                 min= MIN2 (min, icu->bezt[0].vec[1][0]);
635                                                                 max= MAX2 (max, icu->bezt[icu->totvert-1].vec[1][0]);
636                                                                 foundvert=1;
637                                                         }
638                                                 }
639                                         }
640                                 }
641                         }
642                 }
643         }       
644         if (foundvert) {
645                 if(min==max) max+= 1.0f;
646                 *start= min;
647                 *end= max;
648         }
649         else {
650                 *start= 0.0f;
651                 *end= 1.0f;
652         }
653 }
654
655 /* Copy the data from the action-pose (src) into the pose */
656 /* both args are assumed to be valid */
657 /* exported to game engine */
658 void extract_pose_from_pose(bPose *pose, const bPose *src)
659 {
660         const bPoseChannel *schan;
661         bPoseChannel *pchan= pose->chanbase.first;
662
663         for (schan=src->chanbase.first; schan; schan=schan->next, pchan= pchan->next) {
664                 copy_pose_channel_data(pchan, schan);
665         }
666 }
667
668 /* Pose should exist, can have any number of channels too (used for constraint) */
669 void extract_pose_from_action(bPose *pose, bAction *act, float ctime) 
670 {
671         bActionChannel *achan;
672         bPoseChannel    *pchan;
673         Ipo                             *ipo;
674
675         if (!act)
676                 return;
677         if (!pose)
678                 return;
679         
680         /* Copy the data from the action into the pose */
681         for (pchan= pose->chanbase.first; pchan; pchan=pchan->next) {
682                 achan= get_action_channel(act, pchan->name);
683                 pchan->flag &= ~(POSE_LOC|POSE_ROT|POSE_SIZE);
684                 if(achan) {
685                         ipo = achan->ipo;
686                         if (ipo) {
687                                 /* Evaluates and sets the internal ipo value */
688                                 calc_ipo(ipo, ctime);
689                                 /* This call also sets the pchan flags */
690                                 execute_action_ipo(achan, pchan);
691                         }
692                         do_constraint_channels(&pchan->constraints, &achan->constraintChannels, ctime);
693                 }
694         }
695         
696         pose->ctime= ctime;     /* used for cyclic offset matching */
697 }
698
699 /* for do_all_pose_actions, clears the pose. Now also exported for proxy and tools */
700 void rest_pose(bPose *pose)
701 {
702         bPoseChannel *pchan;
703         int i;
704         
705         if (!pose)
706                 return;
707         
708         memset(pose->stride_offset, 0, sizeof(pose->stride_offset));
709         memset(pose->cyclic_offset, 0, sizeof(pose->cyclic_offset));
710         
711         for (pchan=pose->chanbase.first; pchan; pchan= pchan->next){
712                 for (i=0; i<3; i++) {
713                         pchan->loc[i]= 0.0f;
714                         pchan->quat[i+1]= 0.0f;
715                         pchan->size[i]= 1.0f;
716                 }
717                 pchan->quat[0]= 1.0f;
718                 
719                 pchan->flag &= ~(POSE_LOC|POSE_ROT|POSE_SIZE);
720         }
721 }
722
723 /* both poses should be in sync */
724 void copy_pose_result(bPose *to, bPose *from)
725 {
726         bPoseChannel *pchanto, *pchanfrom;
727         
728         if(to==NULL || from==NULL) {
729                 printf("pose result copy error\n"); // debug temp
730                 return;
731         }
732
733         for(pchanfrom= from->chanbase.first; pchanfrom; pchanfrom= pchanfrom->next) {
734                 pchanto= get_pose_channel(to, pchanfrom->name);
735                 if(pchanto) {
736                         Mat4CpyMat4(pchanto->pose_mat, pchanfrom->pose_mat);
737                         Mat4CpyMat4(pchanto->chan_mat, pchanfrom->chan_mat);
738                         /* used for local constraints */
739                         VECCOPY(pchanto->loc, pchanfrom->loc);
740                         QUATCOPY(pchanto->quat, pchanfrom->quat);
741                         VECCOPY(pchanto->size, pchanfrom->size);
742                         
743                         VECCOPY(pchanto->pose_head, pchanfrom->pose_head);
744                         VECCOPY(pchanto->pose_tail, pchanfrom->pose_tail);
745                         pchanto->flag= pchanfrom->flag;
746                 }
747         }
748 }
749
750 /* ********** NLA with non-poses works with ipo channels ********** */
751
752 typedef struct NlaIpoChannel {
753         struct NlaIpoChannel *next, *prev;
754         float val;
755         void *poin;
756         int type;
757 } NlaIpoChannel;
758
759 static void extract_ipochannels_from_action(ListBase *lb, ID *id, bAction *act, char *name, float ctime)
760 {
761         bActionChannel *achan= get_action_channel(act, name);
762         IpoCurve *icu;
763         NlaIpoChannel *nic;
764         
765         if(achan==NULL) return;
766         
767         if(achan->ipo) {
768                 calc_ipo(achan->ipo, ctime);
769                 
770                 for(icu= achan->ipo->curve.first; icu; icu= icu->next) {
771                         /* skip IPO_BITS, is for layers and cannot be blended */
772                         if(icu->vartype != IPO_BITS) {
773                                 nic= MEM_callocN(sizeof(NlaIpoChannel), "NlaIpoChannel");
774                                 BLI_addtail(lb, nic);
775                                 nic->val= icu->curval;
776                                 nic->poin= get_ipo_poin(id, icu, &nic->type);
777                         }
778                 }
779         }
780         
781         /* constraint channels only for objects */
782         if(GS(id->name)==ID_OB) {
783                 Object *ob= (Object *)id;
784                 bConstraint *con;
785                 bConstraintChannel *conchan;
786                 
787                 for (con=ob->constraints.first; con; con=con->next) {
788                         conchan = get_constraint_channel(&achan->constraintChannels, con->name);
789                         
790                         if(conchan && conchan->ipo) {
791                                 calc_ipo(conchan->ipo, ctime);
792
793                                 icu= conchan->ipo->curve.first; // only one ipo now
794                                 if(icu) {
795                                         nic= MEM_callocN(sizeof(NlaIpoChannel), "NlaIpoChannel constr");
796                                         BLI_addtail(lb, nic);
797                                         nic->val= icu->curval;
798                                         nic->poin= &con->enforce;
799                                         nic->type= IPO_FLOAT;
800                                 }
801                         }
802                 }
803         }
804 }
805
806 static NlaIpoChannel *find_nla_ipochannel(ListBase *lb, void *poin)
807 {
808         NlaIpoChannel *nic;
809         
810         if(poin) {
811                 for(nic= lb->first; nic; nic= nic->next) {
812                         if(nic->poin==poin)
813                                 return nic;
814                 }
815         }
816         return NULL;
817 }
818
819
820 static void blend_ipochannels(ListBase *dst, ListBase *src, float srcweight, int mode)
821 {
822         NlaIpoChannel *snic, *dnic, *next;
823         float dstweight;
824         
825         switch (mode){
826                 case POSE_BLEND:
827                         dstweight = 1.0F - srcweight;
828                         break;
829                 case POSE_ADD:
830                         dstweight = 1.0F;
831                         break;
832                 default :
833                         dstweight = 1.0F;
834         }
835         
836         for(snic= src->first; snic; snic= next) {
837                 next= snic->next;
838                 
839                 dnic= find_nla_ipochannel(dst, snic->poin);
840                 if(dnic==NULL) {
841                         /* remove from src list, and insert in dest */
842                         BLI_remlink(src, snic);
843                         BLI_addtail(dst, snic);
844                 }
845                 else {
846                         /* we do the blend */
847                         dnic->val= dstweight*dnic->val + srcweight*snic->val;
848                 }
849         }
850 }
851
852 static void execute_ipochannels(ListBase *lb)
853 {
854         NlaIpoChannel *nic;
855         
856         for(nic= lb->first; nic; nic= nic->next) {
857                 if(nic->poin) {
858                         write_ipo_poin(nic->poin, nic->type, nic->val);
859                 }
860         }
861 }
862
863 /* nla timing */
864
865 /* this now only used for repeating cycles, to enable fields and blur. */
866 /* the whole time control in blender needs serious thinking... */
867 static float nla_time(float cfra, float unit)
868 {
869         extern float bluroffs;  // bad construct, borrowed from object.c for now
870         extern float fieldoffs;
871         
872         /* motion blur & fields */
873         cfra+= unit*(bluroffs+fieldoffs);
874         
875         /* global time */
876         cfra*= G.scene->r.framelen;     
877
878
879         /* decide later... */
880 //      if(no_speed_curve==0) if(ob && ob->ipo) cfra= calc_ipo_time(ob->ipo, cfra);
881
882         return cfra;
883 }
884
885 /* added "sizecorr" here, to allow armatures to be scaled and still have striding.
886    Only works for uniform scaling. In general I'd advise against scaling armatures ever though! (ton)
887 */
888 static float stridechannel_frame(Object *ob, float sizecorr, bActionStrip *strip, Path *path, float pathdist, float *stride_offset)
889 {
890         bAction *act= strip->act;
891         char *name= strip->stridechannel;
892         bActionChannel *achan= get_action_channel(act, name);
893         int stride_axis= strip->stride_axis;
894
895         if(achan && achan->ipo) {
896                 IpoCurve *icu= NULL;
897                 float minx=0.0f, maxx=0.0f, miny=0.0f, maxy=0.0f;
898                 int foundvert= 0;
899                 
900                 if(stride_axis==0) stride_axis= AC_LOC_X;
901                 else if(stride_axis==1) stride_axis= AC_LOC_Y;
902                 else stride_axis= AC_LOC_Z;
903                 
904                 /* calculate the min/max */
905                 for (icu=achan->ipo->curve.first; icu; icu=icu->next) {
906                         if(icu->adrcode==stride_axis) {
907                                 if(icu->totvert>1) {
908                                         foundvert= 1;
909                                         minx= icu->bezt[0].vec[1][0];
910                                         maxx= icu->bezt[icu->totvert-1].vec[1][0];
911                                         
912                                         miny= icu->bezt[0].vec[1][1];
913                                         maxy= icu->bezt[icu->totvert-1].vec[1][1];
914                                 }
915                                 break;
916                         }
917                 }
918                 
919                 if(foundvert && miny!=maxy) {
920                         float stridelen= sizecorr*fabs(maxy-miny), striptime;
921                         float actiondist, pdist, pdistNewNormalized, offs;
922                         float vec1[4], vec2[4], dir[3];
923                         
924                         /* internal cycling, actoffs is in frames */
925                         offs= stridelen*strip->actoffs/(maxx-minx);
926                         
927                         /* amount path moves object */
928                         pdist = (float)fmod (pathdist+offs, stridelen);
929                         striptime= pdist/stridelen;
930                         
931                         /* amount stride bone moves */
932                         actiondist= sizecorr*eval_icu(icu, minx + striptime*(maxx-minx)) - miny;
933                         
934                         pdist = fabs(actiondist) - pdist;
935                         pdistNewNormalized = (pathdist+pdist)/path->totdist;
936                         
937                         /* now we need to go pdist further (or less) on cu path */
938                         where_on_path(ob, (pathdist)/path->totdist, vec1, dir); /* vec needs size 4 */
939                         if (pdistNewNormalized <= 1) {
940                                 // search for correction in positive path-direction
941                                 where_on_path(ob, pdistNewNormalized, vec2, dir);       /* vec needs size 4 */
942                                 VecSubf(stride_offset, vec2, vec1);
943                         }
944                         else {
945                                 // we reached the end of the path, search backwards instead
946                                 where_on_path(ob, (pathdist-pdist)/path->totdist, vec2, dir);   /* vec needs size 4 */
947                                 VecSubf(stride_offset, vec1, vec2);
948                         }
949                         Mat4Mul3Vecfl(ob->obmat, stride_offset);
950                         return striptime;
951                 }
952         }
953         return 0.0f;
954 }
955
956 static void cyclic_offs_bone(Object *ob, bPose *pose, bActionStrip *strip, float time)
957 {
958         /* only called when strip has cyclic, so >= 1.0f works... */
959         if(time >= 1.0f) {
960                 bActionChannel *achan= get_action_channel(strip->act, strip->offs_bone);
961
962                 if(achan && achan->ipo) {
963                         IpoCurve *icu= NULL;
964                         Bone *bone;
965                         float min[3]={0.0f, 0.0f, 0.0f}, max[3]={0.0f, 0.0f, 0.0f};
966                         int index=0, foundvert= 0;
967                         
968                         /* calculate the min/max */
969                         for (icu=achan->ipo->curve.first; icu; icu=icu->next) {
970                                 if(icu->totvert>1) {
971                                         
972                                         if(icu->adrcode==AC_LOC_X)
973                                                 index= 0;
974                                         else if(icu->adrcode==AC_LOC_Y)
975                                                 index= 1;
976                                         else if(icu->adrcode==AC_LOC_Z)
977                                                 index= 2;
978                                         else
979                                                 continue;
980                                 
981                                         foundvert= 1;
982                                         min[index]= icu->bezt[0].vec[1][1];
983                                         max[index]= icu->bezt[icu->totvert-1].vec[1][1];
984                                 }
985                         }
986                         if(foundvert) {
987                                 /* bring it into armature space */
988                                 VecSubf(min, max, min);
989                                 bone= get_named_bone(ob->data, strip->offs_bone);       /* weak */
990                                 if(bone) {
991                                         Mat4Mul3Vecfl(bone->arm_mat, min);
992                                         
993                                         /* dominant motion, cyclic_offset was cleared in rest_pose */
994                                         if (strip->flag & (ACTSTRIP_CYCLIC_USEX | ACTSTRIP_CYCLIC_USEY | ACTSTRIP_CYCLIC_USEZ)) {
995                                                 if (strip->flag & ACTSTRIP_CYCLIC_USEX) pose->cyclic_offset[0]= time*min[0];
996                                                 if (strip->flag & ACTSTRIP_CYCLIC_USEY) pose->cyclic_offset[1]= time*min[1];
997                                                 if (strip->flag & ACTSTRIP_CYCLIC_USEZ) pose->cyclic_offset[2]= time*min[2];
998                                         } else {
999                                                 if( fabs(min[0]) >= fabs(min[1]) && fabs(min[0]) >= fabs(min[2]))
1000                                                         pose->cyclic_offset[0]= time*min[0];
1001                                                 else if( fabs(min[1]) >= fabs(min[0]) && fabs(min[1]) >= fabs(min[2]))
1002                                                         pose->cyclic_offset[1]= time*min[1];
1003                                                 else
1004                                                         pose->cyclic_offset[2]= time*min[2];
1005                                         }
1006                                 }
1007                         }
1008                 }
1009         }
1010 }
1011
1012 /* simple case for now; only the curve path with constraint value > 0.5 */
1013 /* blending we might do later... */
1014 static Object *get_parent_path(Object *ob)
1015 {
1016         bConstraint *con;
1017         
1018         if(ob->parent && ob->parent->type==OB_CURVE)
1019                 return ob->parent;
1020         
1021         for (con = ob->constraints.first; con; con=con->next) {
1022                 if(con->type==CONSTRAINT_TYPE_FOLLOWPATH) {
1023                         if(con->enforce>0.5f) {
1024                                 bFollowPathConstraint *data= con->data;
1025                                 return data->tar;
1026                         }
1027                 }
1028         }
1029         return NULL;
1030 }
1031
1032 /* ************** do the action ************ */
1033
1034 static void do_nla(Object *ob, int blocktype)
1035 {
1036         bPose *tpose= NULL;
1037         Key *key= NULL;
1038         ListBase tchanbase={NULL, NULL}, chanbase={NULL, NULL};
1039         bActionStrip *strip, *striplast=NULL, *stripfirst=NULL;
1040         float striptime, frametime, length, actlength;
1041         float blendfac, stripframe;
1042         float scene_cfra= G.scene->r.cfra;
1043         int     doit, dostride;
1044         
1045         if(blocktype==ID_AR) {
1046                 copy_pose(&tpose, ob->pose, 1);
1047                 rest_pose(ob->pose);            // potentially destroying current not-keyed pose
1048         }
1049         else {
1050                 key= ob_get_key(ob);
1051         }
1052         
1053         /* check on extend to left or right, when no strip is hit by 'cfra' */
1054         for (strip=ob->nlastrips.first; strip; strip=strip->next) {
1055                 /* escape loop on a hit */
1056                 if( scene_cfra >= strip->start && scene_cfra <= strip->end + 0.1f)      /* note 0.1 comes back below */
1057                         break;
1058                 if(scene_cfra < strip->start) {
1059                         if(stripfirst==NULL)
1060                                 stripfirst= strip;
1061                         else if(stripfirst->start > strip->start)
1062                                 stripfirst= strip;
1063                 }
1064                 else if(scene_cfra > strip->end) {
1065                         if(striplast==NULL)
1066                                 striplast= strip;
1067                         else if(striplast->end < strip->end)
1068                                 striplast= strip;
1069                 }
1070         }
1071         if(strip==NULL) {       /* extend */
1072                 if(stripfirst)
1073                         scene_cfra= stripfirst->start;
1074                 else if(striplast)
1075                         scene_cfra= striplast->end;
1076         }
1077         
1078         /* and now go over all strips */
1079         for (strip=ob->nlastrips.first; strip; strip=strip->next){
1080                 doit=dostride= 0;
1081                 
1082                 if (strip->act && !(strip->flag & ACTSTRIP_MUTE)) {     /* so theres an action */
1083                         
1084                         /* Determine if the current frame is within the strip's range */
1085                         length = strip->end-strip->start;
1086                         actlength = strip->actend-strip->actstart;
1087                         striptime = (scene_cfra-(strip->start)) / length;
1088                         stripframe = (scene_cfra-(strip->start)) ;
1089
1090                         if (striptime>=0.0){
1091                                 
1092                                 if(blocktype==ID_AR) 
1093                                         rest_pose(tpose);
1094                                 
1095                                 /* To handle repeat, we add 0.1 frame extra to make sure the last frame is included */
1096                                 if (striptime < 1.0f + 0.1f/length) {
1097                                         
1098                                         /* Handle path */
1099                                         if ((strip->flag & ACTSTRIP_USESTRIDE) && (blocktype==ID_AR) && (ob->ipoflag & OB_DISABLE_PATH)==0){
1100                                                 Object *parent= get_parent_path(ob);
1101                                                 
1102                                                 if (parent) {
1103                                                         Curve *cu = parent->data;
1104                                                         float ctime, pdist;
1105                                                         
1106                                                         if (cu->flag & CU_PATH){
1107                                                                 /* Ensure we have a valid path */
1108                                                                 if(cu->path==NULL || cu->path->data==NULL) makeDispListCurveTypes(parent, 0);
1109                                                                 if(cu->path) {
1110                                                                         
1111                                                                         /* Find the position on the path */
1112                                                                         ctime= bsystem_time(ob, parent, scene_cfra, 0.0);
1113                                                                         
1114                                                                         if(calc_ipo_spec(cu->ipo, CU_SPEED, &ctime)==0) {
1115                                                                                 /* correct for actions not starting on zero */
1116                                                                                 ctime= (ctime - strip->actstart)/cu->pathlen;
1117                                                                                 CLAMP(ctime, 0.0, 1.0);
1118                                                                         }
1119                                                                         pdist = ctime*cu->path->totdist;
1120                                                                         
1121                                                                         if(tpose && strip->stridechannel[0]) {
1122                                                                                 striptime= stridechannel_frame(parent, ob->size[0], strip, cu->path, pdist, tpose->stride_offset);
1123                                                                         }                                                                       
1124                                                                         else {
1125                                                                                 if (strip->stridelen) {
1126                                                                                         striptime = pdist / strip->stridelen;
1127                                                                                         striptime = (float)fmod (striptime+strip->actoffs, 1.0);
1128                                                                                 }
1129                                                                                 else
1130                                                                                         striptime = 0;
1131                                                                         }
1132                                                                         
1133                                                                         frametime = (striptime * actlength) + strip->actstart;
1134                                                                         frametime= bsystem_time(ob, 0, frametime, 0.0);
1135                                                                         
1136                                                                         if(blocktype==ID_AR) {
1137                                                                                 extract_pose_from_action (tpose, strip->act, frametime);
1138                                                                         }
1139                                                                         else if(blocktype==ID_OB) {
1140                                                                                 extract_ipochannels_from_action(&tchanbase, &ob->id, strip->act, "Object", frametime);
1141                                                                                 if(key)
1142                                                                                         extract_ipochannels_from_action(&tchanbase, &key->id, strip->act, "Shape", frametime);
1143                                                                         }
1144                                                                         doit=dostride= 1;
1145                                                                 }
1146                                                         }
1147                                                 }
1148                                         }
1149                                         /* To handle repeat, we add 0.1 frame extra to make sure the last frame is included */
1150                                         else  {
1151                                                 
1152                                                 /* Mod to repeat */
1153                                                 if(strip->repeat!=1.0f) {
1154                                                         float cycle= striptime*strip->repeat;
1155                                                         
1156                                                         striptime = (float)fmod (cycle, 1.0f + 0.1f/length);
1157                                                         cycle-= striptime;
1158                                                         
1159                                                         if(blocktype==ID_AR)
1160                                                                 cyclic_offs_bone(ob, tpose, strip, cycle);
1161                                                 }
1162
1163                                                 frametime = (striptime * actlength) + strip->actstart;
1164                                                 frametime= nla_time(frametime, (float)strip->repeat);
1165                                                         
1166                                                 if(blocktype==ID_AR) {
1167                                                         extract_pose_from_action (tpose, strip->act, frametime);
1168                                                 }
1169                                                 else if(blocktype==ID_OB) {
1170                                                         extract_ipochannels_from_action(&tchanbase, &ob->id, strip->act, "Object", frametime);
1171                                                         if(key)
1172                                                                 extract_ipochannels_from_action(&tchanbase, &key->id, strip->act, "Shape", frametime);
1173                                                 }
1174                                                 
1175                                                 doit=1;
1176                                         }
1177                                 }
1178                                 /* Handle extend */
1179                                 else {
1180                                         if (strip->flag & ACTSTRIP_HOLDLASTFRAME){
1181                                                 /* we want the strip to hold on the exact fraction of the repeat value */
1182                                                 
1183                                                 frametime = actlength * (strip->repeat-(int)strip->repeat);
1184                                                 if(frametime<=0.000001f) frametime= actlength;  /* rounding errors... */
1185                                                 frametime= bsystem_time(ob, 0, frametime+strip->actstart, 0.0);
1186                                                 
1187                                                 if(blocktype==ID_AR)
1188                                                         extract_pose_from_action (tpose, strip->act, frametime);
1189                                                 else if(blocktype==ID_OB) {
1190                                                         extract_ipochannels_from_action(&tchanbase, &ob->id, strip->act, "Object", frametime);
1191                                                         if(key)
1192                                                                 extract_ipochannels_from_action(&tchanbase, &key->id, strip->act, "Shape", frametime);
1193                                                 }
1194                                                 
1195                                                 /* handle cycle hold */
1196                                                 if(strip->repeat!=1.0f) {
1197                                                         if(blocktype==ID_AR)
1198                                                                 cyclic_offs_bone(ob, tpose, strip, strip->repeat-1.0f);
1199                                                 }
1200                                                 
1201                                                 doit=1;
1202                                         }
1203                                 }
1204                                 
1205                                 /* Handle blendin & blendout */
1206                                 if (doit){
1207                                         /* Handle blendin */
1208                                         
1209                                         if (strip->blendin>0.0 && stripframe<=strip->blendin && scene_cfra>=strip->start){
1210                                                 blendfac = stripframe/strip->blendin;
1211                                         }
1212                                         else if (strip->blendout>0.0 && stripframe>=(length-strip->blendout) && scene_cfra<=strip->end){
1213                                                 blendfac = (length-stripframe)/(strip->blendout);
1214                                         }
1215                                         else
1216                                                 blendfac = 1;
1217                                         
1218                                         if(blocktype==ID_AR) {/* Blend this pose with the accumulated pose */
1219                                                 /* offset bone, for matching cycles */
1220                                                 blend_pose_offset_bone (strip, ob->pose, tpose, blendfac, strip->mode);
1221                                                 
1222                                                 blend_poses (ob->pose, tpose, blendfac, strip->mode);
1223                                                 if(dostride)
1224                                                         blend_pose_strides (ob->pose, tpose, blendfac, strip->mode);
1225                                         }
1226                                         else {
1227                                                 blend_ipochannels(&chanbase, &tchanbase, blendfac, strip->mode);
1228                                                 BLI_freelistN(&tchanbase);
1229                                         }
1230                                 }
1231                         }                                       
1232                 }
1233         }
1234         
1235         if(blocktype==ID_OB) {
1236                 execute_ipochannels(&chanbase);
1237         }
1238         else if(blocktype==ID_AR) {
1239                 /* apply stride offset to object */
1240                 VecAddf(ob->obmat[3], ob->obmat[3], ob->pose->stride_offset);
1241         }
1242         
1243         /* free */
1244         if (tpose){
1245                 free_pose_channels(tpose);
1246                 MEM_freeN(tpose);
1247         }
1248         if(chanbase.first)
1249                 BLI_freelistN(&chanbase);
1250 }
1251
1252 void do_all_pose_actions(Object *ob)
1253 {
1254
1255         // only to have safe calls from editor
1256         if(ob==NULL) return;
1257         if(ob->type!=OB_ARMATURE || ob->pose==NULL) return;
1258
1259         if(ob->pose->flag & POSE_LOCKED) {  // no actions to execute while transform
1260                 if(ob->pose->flag & POSE_DO_UNLOCK)
1261                         ob->pose->flag &= ~(POSE_LOCKED|POSE_DO_UNLOCK);
1262         }
1263         else if(ob->action && ((ob->nlaflag & OB_NLA_OVERRIDE)==0 || ob->nlastrips.first==NULL) ) {
1264                 float cframe= (float) G.scene->r.cfra;
1265                 
1266                 cframe= get_action_frame(ob, cframe);
1267                 
1268                 extract_pose_from_action (ob->pose, ob->action, bsystem_time(ob, 0, cframe, 0.0));
1269         }
1270         else if(ob->nlastrips.first) {
1271                 do_nla(ob, ID_AR);
1272         }
1273 }
1274
1275 /* called from where_is_object */
1276 void do_all_object_actions(Object *ob)
1277 {
1278         if(ob==NULL) return;
1279         if(ob->dup_group) return;       /* prevent conflicts, might add smarter check later */
1280         
1281         /* Do local action */
1282         if(ob->action && ((ob->nlaflag & OB_NLA_OVERRIDE)==0 || ob->nlastrips.first==NULL) ) {
1283                 ListBase tchanbase= {NULL, NULL};
1284                 Key *key= ob_get_key(ob);
1285                 float cframe= (float) G.scene->r.cfra;
1286                 
1287                 cframe= get_action_frame(ob, cframe);
1288                 
1289                 extract_ipochannels_from_action(&tchanbase, &ob->id, ob->action, "Object", bsystem_time(ob, 0, cframe, 0.0));
1290                 if(key)
1291                         extract_ipochannels_from_action(&tchanbase, &key->id, ob->action, "Shape", bsystem_time(ob, 0, cframe, 0.0));
1292                 
1293                 if(tchanbase.first) {
1294                         execute_ipochannels(&tchanbase);
1295                         BLI_freelistN(&tchanbase);
1296                 }
1297         }
1298         else if(ob->nlastrips.first) {
1299                 do_nla(ob, ID_OB);
1300         }
1301 }
1302
1303