e10a17a3338154defe4e34b48ef4358adfe0dd39
[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 math 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         Mat4One(chan->constinv);
251         
252         BLI_addtail (&pose->chanbase, chan);
253         
254         return chan;
255 }
256
257
258 /* dst should be freed already, makes entire duplicate */
259 void copy_pose(bPose **dst, bPose *src, int copycon)
260 {
261         bPose *outPose;
262         bPoseChannel    *pchan;
263         ListBase listb;
264         
265         if (!src){
266                 *dst=NULL;
267                 return;
268         }
269         
270         outPose= MEM_callocN(sizeof(bPose), "pose");
271         
272         duplicatelist (&outPose->chanbase, &src->chanbase);
273         
274         if (copycon) {
275                 for (pchan=outPose->chanbase.first; pchan; pchan=pchan->next) {
276                         copy_constraints(&listb, &pchan->constraints);  // copy_constraints NULLs listb
277                         pchan->constraints= listb;
278                         pchan->path= NULL;
279                 }
280         }
281         
282         *dst=outPose;
283 }
284
285 void free_pose_channels(bPose *pose) 
286 {
287         bPoseChannel *pchan;
288         
289         if (pose->chanbase.first){
290                 for (pchan = pose->chanbase.first; pchan; pchan=pchan->next){
291                         if(pchan->path)
292                                 MEM_freeN(pchan->path);
293                         free_constraints(&pchan->constraints);
294                 }
295                 BLI_freelistN (&pose->chanbase);
296         }
297 }
298
299 static void copy_pose_channel_data(bPoseChannel *pchan, const bPoseChannel *chan)
300 {
301         bConstraint *pcon, *con;
302         
303         VECCOPY(pchan->loc, chan->loc);
304         VECCOPY(pchan->size, chan->size);
305         QUATCOPY(pchan->quat, chan->quat);
306         pchan->flag= chan->flag;
307         
308         con= chan->constraints.first;
309         for(pcon= pchan->constraints.first; pcon; pcon= pcon->next)
310                 pcon->enforce= con->enforce;
311 }
312
313 /* checks for IK constraint, can do more constraints flags later */
314 /* pose should be entirely OK */
315 void update_pose_constraint_flags(bPose *pose)
316 {
317         bPoseChannel *pchan, *parchan;
318         bConstraint *con;
319         
320         /* clear */
321         for (pchan = pose->chanbase.first; pchan; pchan=pchan->next) {
322                 pchan->constflag= 0;
323         }
324         /* detect */
325         for (pchan = pose->chanbase.first; pchan; pchan=pchan->next) {
326                 for(con= pchan->constraints.first; con; con= con->next) {
327                         if(con->type==CONSTRAINT_TYPE_KINEMATIC) {
328                                 bKinematicConstraint *data = (bKinematicConstraint*)con->data;
329                                 
330                                 pchan->constflag |= PCHAN_HAS_IK;
331                                 
332                                 if(data->tar==NULL || (data->tar->type==OB_ARMATURE && data->subtarget[0]==0))
333                                         pchan->constflag |= PCHAN_HAS_TARGET;
334                                 
335                                 /* negative rootbone = recalc rootbone index. used in do_versions */
336                                 if(data->rootbone<0) {
337                                         data->rootbone= 0;
338                                         
339                                         if(data->flag & CONSTRAINT_IK_TIP) parchan= pchan;
340                                         else parchan= pchan->parent;
341                                         
342                                         while(parchan) {
343                                                 data->rootbone++;
344                                                 if((parchan->bone->flag & BONE_CONNECTED)==0)
345                                                         break;
346                                                 parchan= parchan->parent;
347                                         }
348                                 }
349                         }
350                         else pchan->constflag |= PCHAN_HAS_CONST;
351                 }
352         }
353 }
354
355
356 /* ************************ END Pose channels *************** */
357
358 /* ************************ Action channels *************** */
359
360
361 bActionChannel *get_action_channel(bAction *act, const char *name)
362 {
363         bActionChannel *chan;
364         
365         if (!act || !name)
366                 return NULL;
367         
368         for (chan = act->chanbase.first; chan; chan=chan->next){
369                 if (!strcmp (chan->name, name))
370                         return chan;
371         }
372         
373         return NULL;
374 }
375
376 /* returns existing channel, or adds new one. In latter case it doesnt activate it, context is required for that*/
377 bActionChannel *verify_action_channel(bAction *act, const char *name)
378 {
379         bActionChannel *chan;
380         
381         chan= get_action_channel(act, name);
382         if(chan==NULL) {
383                 if (!chan) {
384                         chan = MEM_callocN (sizeof(bActionChannel), "actionChannel");
385                         strncpy (chan->name, name, 31);
386                         BLI_addtail (&act->chanbase, chan);
387                 }
388         }
389         return chan;
390 }
391
392 /* ************** time ****************** */
393
394 static bActionStrip *get_active_strip(Object *ob)
395 {
396         bActionStrip *strip;
397         
398         if(ob->action==NULL)
399                 return NULL;
400         
401         for (strip=ob->nlastrips.first; strip; strip=strip->next)
402                 if(strip->flag & ACTSTRIP_ACTIVE)
403                         break;
404         
405         if(strip && strip->act==ob->action)
406                 return strip;
407         return NULL;
408 }
409
410 /* non clipped mapping of strip */
411 static float get_actionstrip_frame(bActionStrip *strip, float cframe, int invert)
412 {
413         float length, actlength, repeat;
414         
415         if (strip->flag & ACTSTRIP_USESTRIDE)
416                 repeat= 1.0f;
417         else
418                 repeat= strip->repeat;
419         
420         length = strip->end-strip->start;
421         if(length==0.0f)
422                 length= 1.0f;
423         actlength = strip->actend-strip->actstart;
424         
425         
426         
427         if(invert)
428                 return length*(cframe - strip->actstart)/(repeat*actlength) + strip->start;
429         else
430                 return repeat*actlength*(cframe - strip->start)/length + strip->actstart;
431 }
432
433 /* if the conditions match, it converts current time to strip time */
434 float get_action_frame(Object *ob, float cframe)
435 {
436         bActionStrip *strip= get_active_strip(ob);
437         
438         if(strip)
439                 return get_actionstrip_frame(strip, cframe, 0);
440         return cframe;
441 }
442
443 /* inverted, strip time to current time */
444 float get_action_frame_inv(Object *ob, float cframe)
445 {
446         bActionStrip *strip= get_active_strip(ob);
447         
448         if(strip)
449                 return get_actionstrip_frame(strip, cframe, 1);
450         return cframe;
451 }
452
453
454 /* ************************ Blending with NLA *************** */
455
456 static void blend_pose_strides(bPose *dst, bPose *src, float srcweight, short mode)
457 {
458         float dstweight;
459         
460         switch (mode){
461                 case ACTSTRIPMODE_BLEND:
462                         dstweight = 1.0F - srcweight;
463                         break;
464                 case ACTSTRIPMODE_ADD:
465                         dstweight = 1.0F;
466                         break;
467                 default :
468                         dstweight = 1.0F;
469         }
470         
471         VecLerpf(dst->stride_offset, dst->stride_offset, src->stride_offset, srcweight);
472 }
473
474
475 /* 
476
477 bone matching diagram, strips A and B
478
479                  .------------------------.
480                  |         A              |
481                  '------------------------'
482                                  .          .             b2
483                  .          .-------------v----------.
484                  .              |         B   .          |
485                  .          '------------------------'
486                  .          .             .
487                  .          .             .
488 offset:          .    0     .    A-B      .  A-b2+B     
489                  .          .             .
490
491 */
492
493
494 static void blend_pose_offset_bone(bActionStrip *strip, bPose *dst, bPose *src, float srcweight, short mode)
495 {
496         /* matching offset bones */
497         /* take dst offset, and put src on on that location */
498         
499         if(strip->offs_bone[0]==0)
500                 return;
501         
502         /* are we also blending with matching bones? */
503         if(strip->prev && strip->start>=strip->prev->start) {
504                 bPoseChannel *dpchan= get_pose_channel(dst, strip->offs_bone);
505                 if(dpchan) {
506                         bPoseChannel *spchan= get_pose_channel(src, strip->offs_bone);
507                         if(spchan) {
508                                 float vec[3];
509                                 
510                                 /* dst->ctime has the internal strip->prev action time */
511                                 /* map this time to nla time */
512                                 
513                                 float ctime= get_actionstrip_frame(strip, src->ctime, 1);
514                                 
515                                 if( ctime > strip->prev->end) {
516                                         bActionChannel *achan;
517                                         
518                                         /* add src to dest, minus the position of src on strip->prev->end */
519                                         
520                                         ctime= get_actionstrip_frame(strip, strip->prev->end, 0);
521                                         
522                                         achan= get_action_channel(strip->act, strip->offs_bone);
523                                         if(achan && achan->ipo) {
524                                                 bPoseChannel pchan;
525                                                 /* Evaluates and sets the internal ipo value */
526                                                 calc_ipo(achan->ipo, ctime);
527                                                 /* This call also sets the pchan flags */
528                                                 execute_action_ipo(achan, &pchan);
529                                                 
530                                                 /* store offset that moves src to location of pchan */
531                                                 VecSubf(vec, dpchan->loc, pchan.loc);
532                                                 
533                                                 Mat4Mul3Vecfl(dpchan->bone->arm_mat, vec);
534                                         }
535                                 }
536                                 else {
537                                         /* store offset that moves src to location of dst */
538                                         
539                                         VecSubf(vec, dpchan->loc, spchan->loc);
540                                         Mat4Mul3Vecfl(dpchan->bone->arm_mat, vec);
541                                 }
542                                 
543                                 /* if blending, we only add with factor scrweight */
544                                 VecMulf(vec, srcweight);
545                                 
546                                 VecAddf(dst->cyclic_offset, dst->cyclic_offset, vec);
547                         }
548                 }
549         }
550         
551         VecAddf(dst->cyclic_offset, dst->cyclic_offset, src->cyclic_offset);
552 }
553
554
555 /* Only allowed for Poses with identical channels */
556 void blend_poses(bPose *dst, bPose *src, float srcweight, short mode)
557 {
558         bPoseChannel *dchan;
559         const bPoseChannel *schan;
560         bConstraint *dcon, *scon;
561         float   dquat[4], squat[4];
562         float dstweight;
563         int i;
564         
565         switch (mode){
566         case ACTSTRIPMODE_BLEND:
567                 dstweight = 1.0F - srcweight;
568                 break;
569         case ACTSTRIPMODE_ADD:
570                 dstweight = 1.0F;
571                 break;
572         default :
573                 dstweight = 1.0F;
574         }
575         
576         schan= src->chanbase.first;
577         for (dchan = dst->chanbase.first; dchan; dchan=dchan->next, schan= schan->next){
578                 if (schan->flag & (POSE_ROT|POSE_LOC|POSE_SIZE)) {
579                         /* replaced quat->matrix->quat conversion with decent quaternion interpol (ton) */
580                         
581                         /* Do the transformation blend */
582                         if (schan->flag & POSE_ROT) {
583                                 QUATCOPY(dquat, dchan->quat);
584                                 QUATCOPY(squat, schan->quat);
585                                 if(mode==ACTSTRIPMODE_BLEND)
586                                         QuatInterpol(dchan->quat, dquat, squat, srcweight);
587                                 else
588                                         QuatAdd(dchan->quat, dquat, squat, srcweight);
589                                 
590                                 NormalQuat (dchan->quat);
591                         }
592
593                         for (i=0; i<3; i++){
594                                 if (schan->flag & POSE_LOC)
595                                         dchan->loc[i] = (dchan->loc[i]*dstweight) + (schan->loc[i]*srcweight);
596                                 if (schan->flag & POSE_SIZE)
597                                         dchan->size[i] = 1.0f + ((dchan->size[i]-1.0f)*dstweight) + ((schan->size[i]-1.0f)*srcweight);
598                         }
599                         dchan->flag |= schan->flag;
600                 }
601                 for(dcon= dchan->constraints.first, scon= schan->constraints.first; dcon && scon; dcon= dcon->next, scon= scon->next) {
602                         /* no 'add' option for constraint blending */
603                         dcon->enforce= dcon->enforce*(1.0f-srcweight) + scon->enforce*srcweight;
604                 }
605         }
606         
607         /* this pose is now in src time */
608         dst->ctime= src->ctime;
609 }
610
611
612 void calc_action_range(const bAction *act, float *start, float *end, int incl_hidden)
613 {
614         const bActionChannel *chan;
615         const bConstraintChannel *conchan;
616         const IpoCurve  *icu;
617         float min=999999999.0f, max=-999999999.0;
618         int     foundvert=0;
619
620         if(act) {
621                 for (chan=act->chanbase.first; chan; chan=chan->next) {
622                         if(incl_hidden || (chan->flag & ACHAN_HIDDEN)==0) {
623                                 if(chan->ipo) {
624                                         for (icu=chan->ipo->curve.first; icu; icu=icu->next) {
625                                                 if(icu->totvert) {
626                                                         min= MIN2 (min, icu->bezt[0].vec[1][0]);
627                                                         max= MAX2 (max, icu->bezt[icu->totvert-1].vec[1][0]);
628                                                         foundvert=1;
629                                                 }
630                                         }
631                                 }
632                                 for (conchan=chan->constraintChannels.first; conchan; conchan=conchan->next) {
633                                         if(conchan->ipo) {
634                                                 for (icu=conchan->ipo->curve.first; icu; icu=icu->next) {
635                                                         if(icu->totvert) {
636                                                                 min= MIN2 (min, icu->bezt[0].vec[1][0]);
637                                                                 max= MAX2 (max, icu->bezt[icu->totvert-1].vec[1][0]);
638                                                                 foundvert=1;
639                                                         }
640                                                 }
641                                         }
642                                 }
643                         }
644                 }
645         }       
646         if (foundvert) {
647                 if(min==max) max+= 1.0f;
648                 *start= min;
649                 *end= max;
650         }
651         else {
652                 *start= 0.0f;
653                 *end= 1.0f;
654         }
655 }
656
657 /* Copy the data from the action-pose (src) into the pose */
658 /* both args are assumed to be valid */
659 /* exported to game engine */
660 void extract_pose_from_pose(bPose *pose, const bPose *src)
661 {
662         const bPoseChannel *schan;
663         bPoseChannel *pchan= pose->chanbase.first;
664
665         for (schan=src->chanbase.first; schan; schan=schan->next, pchan= pchan->next) {
666                 copy_pose_channel_data(pchan, schan);
667         }
668 }
669
670 /* Pose should exist, can have any number of channels too (used for constraint) */
671 void extract_pose_from_action(bPose *pose, bAction *act, float ctime) 
672 {
673         bActionChannel *achan;
674         bPoseChannel    *pchan;
675         Ipo                             *ipo;
676
677         if (!act)
678                 return;
679         if (!pose)
680                 return;
681         
682         /* Copy the data from the action into the pose */
683         for (pchan= pose->chanbase.first; pchan; pchan=pchan->next) {
684                 achan= get_action_channel(act, pchan->name);
685                 pchan->flag &= ~(POSE_LOC|POSE_ROT|POSE_SIZE);
686                 if(achan) {
687                         ipo = achan->ipo;
688                         if (ipo) {
689                                 /* Evaluates and sets the internal ipo value */
690                                 calc_ipo(ipo, ctime);
691                                 /* This call also sets the pchan flags */
692                                 execute_action_ipo(achan, pchan);
693                         }
694                         do_constraint_channels(&pchan->constraints, &achan->constraintChannels, ctime);
695                 }
696         }
697         
698         pose->ctime= ctime;     /* used for cyclic offset matching */
699 }
700
701 /* for do_all_pose_actions, clears the pose. Now also exported for proxy and tools */
702 void rest_pose(bPose *pose)
703 {
704         bPoseChannel *pchan;
705         int i;
706         
707         if (!pose)
708                 return;
709         
710         memset(pose->stride_offset, 0, sizeof(pose->stride_offset));
711         memset(pose->cyclic_offset, 0, sizeof(pose->cyclic_offset));
712         
713         for (pchan=pose->chanbase.first; pchan; pchan= pchan->next){
714                 for (i=0; i<3; i++) {
715                         pchan->loc[i]= 0.0f;
716                         pchan->quat[i+1]= 0.0f;
717                         pchan->size[i]= 1.0f;
718                 }
719                 pchan->quat[0]= 1.0f;
720                 
721                 pchan->flag &= ~(POSE_LOC|POSE_ROT|POSE_SIZE);
722         }
723 }
724
725 /* both poses should be in sync */
726 void copy_pose_result(bPose *to, bPose *from)
727 {
728         bPoseChannel *pchanto, *pchanfrom;
729         
730         if(to==NULL || from==NULL) {
731                 printf("pose result copy error\n"); // debug temp
732                 return;
733         }
734
735         for(pchanfrom= from->chanbase.first; pchanfrom; pchanfrom= pchanfrom->next) {
736                 pchanto= get_pose_channel(to, pchanfrom->name);
737                 if(pchanto) {
738                         Mat4CpyMat4(pchanto->pose_mat, pchanfrom->pose_mat);
739                         Mat4CpyMat4(pchanto->chan_mat, pchanfrom->chan_mat);
740                         /* used for local constraints */
741                         VECCOPY(pchanto->loc, pchanfrom->loc);
742                         QUATCOPY(pchanto->quat, pchanfrom->quat);
743                         VECCOPY(pchanto->size, pchanfrom->size);
744                         
745                         VECCOPY(pchanto->pose_head, pchanfrom->pose_head);
746                         VECCOPY(pchanto->pose_tail, pchanfrom->pose_tail);
747                         pchanto->flag= pchanfrom->flag;
748                 }
749         }
750 }
751
752 /* ********** NLA with non-poses works with ipo channels ********** */
753
754 typedef struct NlaIpoChannel {
755         struct NlaIpoChannel *next, *prev;
756         float val;
757         void *poin;
758         int type;
759 } NlaIpoChannel;
760
761 static void extract_ipochannels_from_action(ListBase *lb, ID *id, bAction *act, char *name, float ctime)
762 {
763         bActionChannel *achan= get_action_channel(act, name);
764         IpoCurve *icu;
765         NlaIpoChannel *nic;
766         
767         if(achan==NULL) return;
768         
769         if(achan->ipo) {
770                 calc_ipo(achan->ipo, ctime);
771                 
772                 for(icu= achan->ipo->curve.first; icu; icu= icu->next) {
773                         /* skip IPO_BITS, is for layers and cannot be blended */
774                         if(icu->vartype != IPO_BITS) {
775                                 nic= MEM_callocN(sizeof(NlaIpoChannel), "NlaIpoChannel");
776                                 BLI_addtail(lb, nic);
777                                 nic->val= icu->curval;
778                                 nic->poin= get_ipo_poin(id, icu, &nic->type);
779                         }
780                 }
781         }
782         
783         /* constraint channels only for objects */
784         if(GS(id->name)==ID_OB) {
785                 Object *ob= (Object *)id;
786                 bConstraint *con;
787                 bConstraintChannel *conchan;
788                 
789                 for (con=ob->constraints.first; con; con=con->next) {
790                         conchan = get_constraint_channel(&achan->constraintChannels, con->name);
791                         
792                         if(conchan && conchan->ipo) {
793                                 calc_ipo(conchan->ipo, ctime);
794
795                                 icu= conchan->ipo->curve.first; // only one ipo now
796                                 if(icu) {
797                                         nic= MEM_callocN(sizeof(NlaIpoChannel), "NlaIpoChannel constr");
798                                         BLI_addtail(lb, nic);
799                                         nic->val= icu->curval;
800                                         nic->poin= &con->enforce;
801                                         nic->type= IPO_FLOAT;
802                                 }
803                         }
804                 }
805         }
806 }
807
808 static NlaIpoChannel *find_nla_ipochannel(ListBase *lb, void *poin)
809 {
810         NlaIpoChannel *nic;
811         
812         if(poin) {
813                 for(nic= lb->first; nic; nic= nic->next) {
814                         if(nic->poin==poin)
815                                 return nic;
816                 }
817         }
818         return NULL;
819 }
820
821
822 static void blend_ipochannels(ListBase *dst, ListBase *src, float srcweight, int mode)
823 {
824         NlaIpoChannel *snic, *dnic, *next;
825         float dstweight;
826         
827         switch (mode){
828                 case ACTSTRIPMODE_BLEND:
829                         dstweight = 1.0F - srcweight;
830                         break;
831                 case ACTSTRIPMODE_ADD:
832                         dstweight = 1.0F;
833                         break;
834                 default :
835                         dstweight = 1.0F;
836         }
837         
838         for(snic= src->first; snic; snic= next) {
839                 next= snic->next;
840                 
841                 dnic= find_nla_ipochannel(dst, snic->poin);
842                 if(dnic==NULL) {
843                         /* remove from src list, and insert in dest */
844                         BLI_remlink(src, snic);
845                         BLI_addtail(dst, snic);
846                 }
847                 else {
848                         /* we do the blend */
849                         dnic->val= dstweight*dnic->val + srcweight*snic->val;
850                 }
851         }
852 }
853
854 static void execute_ipochannels(ListBase *lb)
855 {
856         NlaIpoChannel *nic;
857         
858         for(nic= lb->first; nic; nic= nic->next) {
859                 if(nic->poin) {
860                         write_ipo_poin(nic->poin, nic->type, nic->val);
861                 }
862         }
863 }
864
865 /* nla timing */
866
867 /* this now only used for repeating cycles, to enable fields and blur. */
868 /* the whole time control in blender needs serious thinking... */
869 static float nla_time(float cfra, float unit)
870 {
871         extern float bluroffs;  // bad construct, borrowed from object.c for now
872         extern float fieldoffs;
873         
874         /* motion blur & fields */
875         cfra+= unit*(bluroffs+fieldoffs);
876         
877         /* global time */
878         cfra*= G.scene->r.framelen;     
879
880
881         /* decide later... */
882 //      if(no_speed_curve==0) if(ob && ob->ipo) cfra= calc_ipo_time(ob->ipo, cfra);
883
884         return cfra;
885 }
886
887 /* added "sizecorr" here, to allow armatures to be scaled and still have striding.
888    Only works for uniform scaling. In general I'd advise against scaling armatures ever though! (ton)
889 */
890 static float stridechannel_frame(Object *ob, float sizecorr, bActionStrip *strip, Path *path, float pathdist, float *stride_offset)
891 {
892         bAction *act= strip->act;
893         char *name= strip->stridechannel;
894         bActionChannel *achan= get_action_channel(act, name);
895         int stride_axis= strip->stride_axis;
896
897         if(achan && achan->ipo) {
898                 IpoCurve *icu= NULL;
899                 float minx=0.0f, maxx=0.0f, miny=0.0f, maxy=0.0f;
900                 int foundvert= 0;
901                 
902                 if(stride_axis==0) stride_axis= AC_LOC_X;
903                 else if(stride_axis==1) stride_axis= AC_LOC_Y;
904                 else stride_axis= AC_LOC_Z;
905                 
906                 /* calculate the min/max */
907                 for (icu=achan->ipo->curve.first; icu; icu=icu->next) {
908                         if(icu->adrcode==stride_axis) {
909                                 if(icu->totvert>1) {
910                                         foundvert= 1;
911                                         minx= icu->bezt[0].vec[1][0];
912                                         maxx= icu->bezt[icu->totvert-1].vec[1][0];
913                                         
914                                         miny= icu->bezt[0].vec[1][1];
915                                         maxy= icu->bezt[icu->totvert-1].vec[1][1];
916                                 }
917                                 break;
918                         }
919                 }
920                 
921                 if(foundvert && miny!=maxy) {
922                         float stridelen= sizecorr*fabs(maxy-miny), striptime;
923                         float actiondist, pdist, pdistNewNormalized, offs;
924                         float vec1[4], vec2[4], dir[3];
925                         
926                         /* internal cycling, actoffs is in frames */
927                         offs= stridelen*strip->actoffs/(maxx-minx);
928                         
929                         /* amount path moves object */
930                         pdist = (float)fmod (pathdist+offs, stridelen);
931                         striptime= pdist/stridelen;
932                         
933                         /* amount stride bone moves */
934                         actiondist= sizecorr*eval_icu(icu, minx + striptime*(maxx-minx)) - miny;
935                         
936                         pdist = fabs(actiondist) - pdist;
937                         pdistNewNormalized = (pathdist+pdist)/path->totdist;
938                         
939                         /* now we need to go pdist further (or less) on cu path */
940                         where_on_path(ob, (pathdist)/path->totdist, vec1, dir); /* vec needs size 4 */
941                         if (pdistNewNormalized <= 1) {
942                                 // search for correction in positive path-direction
943                                 where_on_path(ob, pdistNewNormalized, vec2, dir);       /* vec needs size 4 */
944                                 VecSubf(stride_offset, vec2, vec1);
945                         }
946                         else {
947                                 // we reached the end of the path, search backwards instead
948                                 where_on_path(ob, (pathdist-pdist)/path->totdist, vec2, dir);   /* vec needs size 4 */
949                                 VecSubf(stride_offset, vec1, vec2);
950                         }
951                         Mat4Mul3Vecfl(ob->obmat, stride_offset);
952                         return striptime;
953                 }
954         }
955         return 0.0f;
956 }
957
958 static void cyclic_offs_bone(Object *ob, bPose *pose, bActionStrip *strip, float time)
959 {
960         /* only called when strip has cyclic, so >= 1.0f works... */
961         if(time >= 1.0f) {
962                 bActionChannel *achan= get_action_channel(strip->act, strip->offs_bone);
963
964                 if(achan && achan->ipo) {
965                         IpoCurve *icu= NULL;
966                         Bone *bone;
967                         float min[3]={0.0f, 0.0f, 0.0f}, max[3]={0.0f, 0.0f, 0.0f};
968                         int index=0, foundvert= 0;
969                         
970                         /* calculate the min/max */
971                         for (icu=achan->ipo->curve.first; icu; icu=icu->next) {
972                                 if(icu->totvert>1) {
973                                         
974                                         if(icu->adrcode==AC_LOC_X)
975                                                 index= 0;
976                                         else if(icu->adrcode==AC_LOC_Y)
977                                                 index= 1;
978                                         else if(icu->adrcode==AC_LOC_Z)
979                                                 index= 2;
980                                         else
981                                                 continue;
982                                 
983                                         foundvert= 1;
984                                         min[index]= icu->bezt[0].vec[1][1];
985                                         max[index]= icu->bezt[icu->totvert-1].vec[1][1];
986                                 }
987                         }
988                         if(foundvert) {
989                                 /* bring it into armature space */
990                                 VecSubf(min, max, min);
991                                 bone= get_named_bone(ob->data, strip->offs_bone);       /* weak */
992                                 if(bone) {
993                                         Mat4Mul3Vecfl(bone->arm_mat, min);
994                                         
995                                         /* dominant motion, cyclic_offset was cleared in rest_pose */
996                                         if (strip->flag & (ACTSTRIP_CYCLIC_USEX | ACTSTRIP_CYCLIC_USEY | ACTSTRIP_CYCLIC_USEZ)) {
997                                                 if (strip->flag & ACTSTRIP_CYCLIC_USEX) pose->cyclic_offset[0]= time*min[0];
998                                                 if (strip->flag & ACTSTRIP_CYCLIC_USEY) pose->cyclic_offset[1]= time*min[1];
999                                                 if (strip->flag & ACTSTRIP_CYCLIC_USEZ) pose->cyclic_offset[2]= time*min[2];
1000                                         } else {
1001                                                 if( fabs(min[0]) >= fabs(min[1]) && fabs(min[0]) >= fabs(min[2]))
1002                                                         pose->cyclic_offset[0]= time*min[0];
1003                                                 else if( fabs(min[1]) >= fabs(min[0]) && fabs(min[1]) >= fabs(min[2]))
1004                                                         pose->cyclic_offset[1]= time*min[1];
1005                                                 else
1006                                                         pose->cyclic_offset[2]= time*min[2];
1007                                         }
1008                                 }
1009                         }
1010                 }
1011         }
1012 }
1013
1014 /* simple case for now; only the curve path with constraint value > 0.5 */
1015 /* blending we might do later... */
1016 static Object *get_parent_path(Object *ob)
1017 {
1018         bConstraint *con;
1019         
1020         if(ob->parent && ob->parent->type==OB_CURVE)
1021                 return ob->parent;
1022         
1023         for (con = ob->constraints.first; con; con=con->next) {
1024                 if(con->type==CONSTRAINT_TYPE_FOLLOWPATH) {
1025                         if(con->enforce>0.5f) {
1026                                 bFollowPathConstraint *data= con->data;
1027                                 return data->tar;
1028                         }
1029                 }
1030         }
1031         return NULL;
1032 }
1033
1034 /* ************** do the action ************ */
1035
1036 static void do_nla(Object *ob, int blocktype)
1037 {
1038         bPose *tpose= NULL;
1039         Key *key= NULL;
1040         ListBase tchanbase={NULL, NULL}, chanbase={NULL, NULL};
1041         bActionStrip *strip, *striplast=NULL, *stripfirst=NULL;
1042         float striptime, frametime, length, actlength;
1043         float blendfac, stripframe;
1044         float scene_cfra= G.scene->r.cfra;
1045         int     doit, dostride;
1046         
1047         if(blocktype==ID_AR) {
1048                 copy_pose(&tpose, ob->pose, 1);
1049                 rest_pose(ob->pose);            // potentially destroying current not-keyed pose
1050         }
1051         else {
1052                 key= ob_get_key(ob);
1053         }
1054         
1055         /* check on extend to left or right, when no strip is hit by 'cfra' */
1056         for (strip=ob->nlastrips.first; strip; strip=strip->next) {
1057                 /* escape loop on a hit */
1058                 if( scene_cfra >= strip->start && scene_cfra <= strip->end + 0.1f)      /* note 0.1 comes back below */
1059                         break;
1060                 if(scene_cfra < strip->start) {
1061                         if(stripfirst==NULL)
1062                                 stripfirst= strip;
1063                         else if(stripfirst->start > strip->start)
1064                                 stripfirst= strip;
1065                 }
1066                 else if(scene_cfra > strip->end) {
1067                         if(striplast==NULL)
1068                                 striplast= strip;
1069                         else if(striplast->end < strip->end)
1070                                 striplast= strip;
1071                 }
1072         }
1073         if(strip==NULL) {       /* extend */
1074                 if(striplast)
1075                         scene_cfra= striplast->end;
1076                 else if(stripfirst)
1077                         scene_cfra= stripfirst->start;
1078         }
1079         
1080         /* and now go over all strips */
1081         for (strip=ob->nlastrips.first; strip; strip=strip->next){
1082                 doit=dostride= 0;
1083                 
1084                 if (strip->act && !(strip->flag & ACTSTRIP_MUTE)) {     /* so theres an action */
1085                         
1086                         /* Determine if the current frame is within the strip's range */
1087                         length = strip->end-strip->start;
1088                         actlength = strip->actend-strip->actstart;
1089                         striptime = (scene_cfra-(strip->start)) / length;
1090                         stripframe = (scene_cfra-(strip->start)) ;
1091
1092                         if (striptime>=0.0){
1093                                 
1094                                 if(blocktype==ID_AR) 
1095                                         rest_pose(tpose);
1096                                 
1097                                 /* To handle repeat, we add 0.1 frame extra to make sure the last frame is included */
1098                                 if (striptime < 1.0f + 0.1f/length) {
1099                                         
1100                                         /* Handle path */
1101                                         if ((strip->flag & ACTSTRIP_USESTRIDE) && (blocktype==ID_AR) && (ob->ipoflag & OB_DISABLE_PATH)==0){
1102                                                 Object *parent= get_parent_path(ob);
1103                                                 
1104                                                 if (parent) {
1105                                                         Curve *cu = parent->data;
1106                                                         float ctime, pdist;
1107                                                         
1108                                                         if (cu->flag & CU_PATH){
1109                                                                 /* Ensure we have a valid path */
1110                                                                 if(cu->path==NULL || cu->path->data==NULL) makeDispListCurveTypes(parent, 0);
1111                                                                 if(cu->path) {
1112                                                                         
1113                                                                         /* Find the position on the path */
1114                                                                         ctime= bsystem_time(ob, scene_cfra, 0.0);
1115                                                                         
1116                                                                         if(calc_ipo_spec(cu->ipo, CU_SPEED, &ctime)==0) {
1117                                                                                 /* correct for actions not starting on zero */
1118                                                                                 ctime= (ctime - strip->actstart)/cu->pathlen;
1119                                                                                 CLAMP(ctime, 0.0, 1.0);
1120                                                                         }
1121                                                                         pdist = ctime*cu->path->totdist;
1122                                                                         
1123                                                                         if(tpose && strip->stridechannel[0]) {
1124                                                                                 striptime= stridechannel_frame(parent, ob->size[0], strip, cu->path, pdist, tpose->stride_offset);
1125                                                                         }                                                                       
1126                                                                         else {
1127                                                                                 if (strip->stridelen) {
1128                                                                                         striptime = pdist / strip->stridelen;
1129                                                                                         striptime = (float)fmod (striptime+strip->actoffs, 1.0);
1130                                                                                 }
1131                                                                                 else
1132                                                                                         striptime = 0;
1133                                                                         }
1134                                                                         
1135                                                                         frametime = (striptime * actlength) + strip->actstart;
1136                                                                         frametime= bsystem_time(ob, frametime, 0.0);
1137                                                                         
1138                                                                         if(blocktype==ID_AR) {
1139                                                                                 extract_pose_from_action (tpose, strip->act, frametime);
1140                                                                         }
1141                                                                         else if(blocktype==ID_OB) {
1142                                                                                 extract_ipochannels_from_action(&tchanbase, &ob->id, strip->act, "Object", frametime);
1143                                                                                 if(key)
1144                                                                                         extract_ipochannels_from_action(&tchanbase, &key->id, strip->act, "Shape", frametime);
1145                                                                         }
1146                                                                         doit=dostride= 1;
1147                                                                 }
1148                                                         }
1149                                                 }
1150                                         }
1151                                         /* To handle repeat, we add 0.1 frame extra to make sure the last frame is included */
1152                                         else  {
1153                                                 
1154                                                 /* Mod to repeat */
1155                                                 if(strip->repeat!=1.0f) {
1156                                                         float cycle= striptime*strip->repeat;
1157                                                         
1158                                                         striptime = (float)fmod (cycle, 1.0f + 0.1f/length);
1159                                                         cycle-= striptime;
1160                                                         
1161                                                         if(blocktype==ID_AR)
1162                                                                 cyclic_offs_bone(ob, tpose, strip, cycle);
1163                                                 }
1164
1165                                                 frametime = (striptime * actlength) + strip->actstart;
1166                                                 frametime= nla_time(frametime, (float)strip->repeat);
1167                                                         
1168                                                 if(blocktype==ID_AR) {
1169                                                         extract_pose_from_action (tpose, strip->act, frametime);
1170                                                 }
1171                                                 else if(blocktype==ID_OB) {
1172                                                         extract_ipochannels_from_action(&tchanbase, &ob->id, strip->act, "Object", frametime);
1173                                                         if(key)
1174                                                                 extract_ipochannels_from_action(&tchanbase, &key->id, strip->act, "Shape", frametime);
1175                                                 }
1176                                                 
1177                                                 doit=1;
1178                                         }
1179                                 }
1180                                 /* Handle extend */
1181                                 else {
1182                                         if (strip->flag & ACTSTRIP_HOLDLASTFRAME){
1183                                                 /* we want the strip to hold on the exact fraction of the repeat value */
1184                                                 
1185                                                 frametime = actlength * (strip->repeat-(int)strip->repeat);
1186                                                 if(frametime<=0.000001f) frametime= actlength;  /* rounding errors... */
1187                                                 frametime= bsystem_time(ob, frametime+strip->actstart, 0.0);
1188                                                 
1189                                                 if(blocktype==ID_AR)
1190                                                         extract_pose_from_action (tpose, strip->act, frametime);
1191                                                 else if(blocktype==ID_OB) {
1192                                                         extract_ipochannels_from_action(&tchanbase, &ob->id, strip->act, "Object", frametime);
1193                                                         if(key)
1194                                                                 extract_ipochannels_from_action(&tchanbase, &key->id, strip->act, "Shape", frametime);
1195                                                 }
1196                                                 
1197                                                 /* handle cycle hold */
1198                                                 if(strip->repeat!=1.0f) {
1199                                                         if(blocktype==ID_AR)
1200                                                                 cyclic_offs_bone(ob, tpose, strip, strip->repeat-1.0f);
1201                                                 }
1202                                                 
1203                                                 doit=1;
1204                                         }
1205                                 }
1206                                 
1207                                 /* Handle blendin & blendout */
1208                                 if (doit){
1209                                         /* Handle blendin */
1210                                         
1211                                         if (strip->blendin>0.0 && stripframe<=strip->blendin && scene_cfra>=strip->start){
1212                                                 blendfac = stripframe/strip->blendin;
1213                                         }
1214                                         else if (strip->blendout>0.0 && stripframe>=(length-strip->blendout) && scene_cfra<=strip->end){
1215                                                 blendfac = (length-stripframe)/(strip->blendout);
1216                                         }
1217                                         else
1218                                                 blendfac = 1;
1219                                         
1220                                         if(blocktype==ID_AR) {/* Blend this pose with the accumulated pose */
1221                                                 /* offset bone, for matching cycles */
1222                                                 blend_pose_offset_bone (strip, ob->pose, tpose, blendfac, strip->mode);
1223                                                 
1224                                                 blend_poses (ob->pose, tpose, blendfac, strip->mode);
1225                                                 if(dostride)
1226                                                         blend_pose_strides (ob->pose, tpose, blendfac, strip->mode);
1227                                         }
1228                                         else {
1229                                                 blend_ipochannels(&chanbase, &tchanbase, blendfac, strip->mode);
1230                                                 BLI_freelistN(&tchanbase);
1231                                         }
1232                                 }
1233                         }                                       
1234                 }
1235         }
1236         
1237         if(blocktype==ID_OB) {
1238                 execute_ipochannels(&chanbase);
1239         }
1240         else if(blocktype==ID_AR) {
1241                 /* apply stride offset to object */
1242                 VecAddf(ob->obmat[3], ob->obmat[3], ob->pose->stride_offset);
1243         }
1244         
1245         /* free */
1246         if (tpose){
1247                 free_pose_channels(tpose);
1248                 MEM_freeN(tpose);
1249         }
1250         if(chanbase.first)
1251                 BLI_freelistN(&chanbase);
1252 }
1253
1254 void do_all_pose_actions(Object *ob)
1255 {
1256
1257         // only to have safe calls from editor
1258         if(ob==NULL) return;
1259         if(ob->type!=OB_ARMATURE || ob->pose==NULL) return;
1260
1261         if(ob->pose->flag & POSE_LOCKED) {  // no actions to execute while transform
1262                 if(ob->pose->flag & POSE_DO_UNLOCK)
1263                         ob->pose->flag &= ~(POSE_LOCKED|POSE_DO_UNLOCK);
1264         }
1265         else if(ob->action && ((ob->nlaflag & OB_NLA_OVERRIDE)==0 || ob->nlastrips.first==NULL) ) {
1266                 float cframe= (float) G.scene->r.cfra;
1267                 
1268                 cframe= get_action_frame(ob, cframe);
1269                 
1270                 extract_pose_from_action (ob->pose, ob->action, bsystem_time(ob, cframe, 0.0));
1271         }
1272         else if(ob->nlastrips.first) {
1273                 do_nla(ob, ID_AR);
1274         }
1275 }
1276
1277 /* called from where_is_object */
1278 void do_all_object_actions(Object *ob)
1279 {
1280         if(ob==NULL) return;
1281         if(ob->dup_group) return;       /* prevent conflicts, might add smarter check later */
1282         
1283         /* Do local action */
1284         if(ob->action && ((ob->nlaflag & OB_NLA_OVERRIDE)==0 || ob->nlastrips.first==NULL) ) {
1285                 ListBase tchanbase= {NULL, NULL};
1286                 Key *key= ob_get_key(ob);
1287                 float cframe= (float) G.scene->r.cfra;
1288                 
1289                 cframe= get_action_frame(ob, cframe);
1290                 
1291                 extract_ipochannels_from_action(&tchanbase, &ob->id, ob->action, "Object", bsystem_time(ob, cframe, 0.0));
1292                 if(key)
1293                         extract_ipochannels_from_action(&tchanbase, &key->id, ob->action, "Shape", bsystem_time(ob, cframe, 0.0));
1294                 
1295                 if(tchanbase.first) {
1296                         execute_ipochannels(&tchanbase);
1297                         BLI_freelistN(&tchanbase);
1298                 }
1299         }
1300         else if(ob->nlastrips.first) {
1301                 do_nla(ob, ID_OB);
1302         }
1303 }
1304
1305