remove unused includes
[blender.git] / source / blender / editors / armature / poselib.c
1 /**
2  * $Id$
3  *
4  * ***** BEGIN GPL LICENSE BLOCK *****
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License
8  * as published by the Free Software Foundation; either version 2
9  * of the License, or (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software Foundation,
18  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19  *
20  * The Original Code is Copyright (C) 2007, Blender Foundation
21  * This is a new part of Blender
22  *
23  * Contributor(s): Joshua Leung
24  *
25  * ***** END GPL LICENSE BLOCK *****
26  */
27  
28 #include <stdlib.h>
29 #include <stdio.h>
30 #include <stddef.h>
31 #include <string.h>
32 #include <math.h>
33 #include <float.h>
34
35 #include "MEM_guardedalloc.h"
36
37 #include "BLI_math.h"
38 #include "BLI_blenlib.h"
39 #include "BLI_dynstr.h"
40 #include "BLI_dlrbTree.h"
41
42 #include "DNA_anim_types.h"
43 #include "DNA_armature_types.h"
44 #include "DNA_object_types.h"
45 #include "DNA_scene_types.h"
46
47 #include "BKE_animsys.h"
48 #include "BKE_action.h"
49 #include "BKE_armature.h"
50 #include "BKE_depsgraph.h"
51
52 #include "BKE_context.h"
53 #include "BKE_report.h"
54
55 #include "RNA_access.h"
56 #include "RNA_define.h"
57 #include "RNA_enum_types.h"
58
59 #include "WM_api.h"
60 #include "WM_types.h"
61
62 #include "UI_interface.h"
63 #include "UI_resources.h"
64
65 #include "ED_anim_api.h"
66 #include "ED_armature.h"
67 #include "ED_keyframes_draw.h"
68 #include "ED_keyframing.h"
69 #include "ED_keyframes_edit.h"
70 #include "ED_screen.h"
71
72 #include "armature_intern.h"
73
74 /* ******* XXX ********** */
75
76 static void action_set_activemarker() {}
77
78 /* ************************************************************* */
79 /* == POSE-LIBRARY TOOL FOR BLENDER == 
80  *      
81  * Overview: 
82  *      This tool allows animators to store a set of frequently used poses to dump into
83  *      the active action to help in "budget" productions to quickly block out new actions.
84  *      It acts as a kind of "glorified clipboard for poses", allowing for naming of poses.
85  *
86  * Features:
87  *      - PoseLibs are simply normal Actions
88  *      - Each "pose" is simply a set of keyframes that occur on a particular frame
89  *              -> a set of TimeMarkers that belong to each Action, help 'label' where a 'pose' can be
90  *                 found in the Action
91  *      - The Scrollwheel or PageUp/Down buttons when used in a special mode or after pressing/holding
92  *        [a modifier] key, cycles through the poses available for the active pose's poselib, allowing the
93  *        animator to preview what action best suits that pose
94  */
95 /* ************************************************************* */
96
97 /* gets list of poses in poselib as a string usable for pupmenu() */
98 char *poselib_build_poses_menu (bAction *act, char title[])
99 {
100         DynStr *pupds= BLI_dynstr_new();
101         TimeMarker *marker;
102         char *str;
103         char buf[64];
104         int i;
105         
106         /* add title first */
107         sprintf(buf, "%s%%t|", title);
108         BLI_dynstr_append(pupds, buf);
109         
110         /* loop through markers, adding them */
111         for (marker=act->markers.first, i=1; marker; marker=marker->next, i++) {
112                 BLI_dynstr_append(pupds, marker->name);
113                 
114                 sprintf(buf, "%%x%d", i);
115                 BLI_dynstr_append(pupds, buf);
116                 
117                 if (marker->next)
118                         BLI_dynstr_append(pupds, "|");
119         }
120         
121         /* convert to normal MEM_malloc'd string */
122         str= BLI_dynstr_get_cstring(pupds);
123         BLI_dynstr_free(pupds);
124         
125         return str;
126 }
127
128 /* gets the first available frame in poselib to store a pose on 
129  *      - frames start from 1, and a pose should occur on every frame... 0 is error!
130  */
131 int poselib_get_free_index (bAction *act)
132 {
133         TimeMarker *marker;
134         int low=0, high=0;
135         
136         /* sanity checks */
137         if (ELEM(NULL, act, act->markers.first)) return 1;
138         
139         /* loop over poses finding various values (poses are not stored in chronological order) */
140         for (marker= act->markers.first; marker; marker= marker->next) {
141                 /* only increase low if value is 1 greater than low, to find "gaps" where
142                  * poses were removed from the poselib
143                  */
144                 if (marker->frame == (low + 1)) 
145                         low++;
146                 
147                 /* value replaces high if it is the highest value encountered yet */
148                 if (marker->frame > high) 
149                         high= marker->frame;
150         }
151         
152         /* - if low is not equal to high, then low+1 is a gap 
153          * - if low is equal to high, then high+1 is the next index (add at end) 
154          */
155         if (low < high) 
156                 return (low + 1);
157         else 
158                 return (high + 1);
159 }
160
161 /* returns the active pose for a poselib */
162 TimeMarker *poselib_get_active_pose (bAction *act)
163 {       
164         if ((act) && (act->active_marker))
165                 return BLI_findlink(&act->markers, act->active_marker-1);
166         else
167                 return NULL;
168 }
169
170 /* ************************************************************* */
171
172 /* Initialise a new poselib (whether it is needed or not) */
173 bAction *poselib_init_new (Object *ob)
174 {
175         /* sanity checks - only for armatures */
176         if (ELEM(NULL, ob, ob->pose))
177                 return NULL;
178         
179         /* init object's poselib action (unlink old one if there) */
180         if (ob->poselib)
181                 ob->poselib->id.us--;
182         ob->poselib= add_empty_action("PoseLib");
183         
184         return ob->poselib;
185 }
186
187 /* Initialise a new poselib (checks if that needs to happen) */
188 bAction *poselib_validate (Object *ob)
189 {
190         if (ELEM(NULL, ob, ob->pose))
191                 return NULL;
192         else if (ob->poselib == NULL)
193                 return poselib_init_new(ob);
194         else
195                 return ob->poselib;
196 }
197
198
199 /* This tool automagically generates/validates poselib data so that it corresponds to the data 
200  * in the action. This is for use in making existing actions usable as poselibs.
201  */
202 // TODO: operatorfy me!
203 void poselib_validate_act (bAction *act)
204 {
205         DLRBT_Tree keys = {NULL, NULL};
206         ActKeyColumn *ak;
207         TimeMarker *marker, *markern;
208         
209         /* validate action and poselib */
210         if (act == NULL)  {
211                 //error("No Action to validate");
212                 return;
213         }
214         
215         /* determine which frames have keys */
216         BLI_dlrbTree_init(&keys);
217         action_to_keylist(NULL, act, &keys, NULL);
218         BLI_dlrbTree_linkedlist_sync(&keys);
219         
220         /* for each key, make sure there is a correspnding pose */
221         for (ak= keys.first; ak; ak= ak->next) {
222                 /* check if any pose matches this */
223                 // TODO: don't go looking through the list like this every time...
224                 for (marker= act->markers.first; marker; marker= marker->next) {
225                         if (IS_EQ(marker->frame, ak->cfra)) {
226                                 marker->flag = -1;
227                                 break;
228                         }
229                 }
230                 
231                 /* add new if none found */
232                 if (marker == NULL) {
233                         char name[64];
234                         
235                         /* add pose to poselib */
236                         marker= MEM_callocN(sizeof(TimeMarker), "ActionMarker");
237                         
238                         strcpy(name, "Pose");
239                         BLI_strncpy(marker->name, name, sizeof(marker->name));
240                         
241                         marker->frame= (int)ak->cfra;
242                         marker->flag= -1;
243                         
244                         BLI_addtail(&act->markers, marker);
245                 }
246         }
247         
248         /* remove all untagged poses (unused), and remove all tags */
249         for (marker= act->markers.first; marker; marker= markern) {
250                 markern= marker->next;
251                 
252                 if (marker->flag != -1)
253                         BLI_freelinkN(&act->markers, marker);
254                 else
255                         marker->flag = 0;
256         }
257         
258         /* free temp memory */
259         BLI_freelistN((ListBase *)&keys);
260         
261         //BIF_undo_push("PoseLib Validate Action");
262 }
263
264 /* ************************************************************* */
265
266 /* Pointers to the builtin KeyingSets that we want to use */
267 static KeyingSet *poselib_ks_locrotscale = NULL;                /* the only keyingset we'll need */
268
269 /* ----- */
270
271 static void poselib_add_menu_invoke__replacemenu (bContext *C, uiLayout *layout, void *arg)
272 {
273         Object *ob= CTX_data_active_object(C);
274         bAction *act= ob->poselib;
275         TimeMarker *marker;
276         
277         /* set the operator execution context correctly */
278         uiLayoutSetOperatorContext(layout, WM_OP_EXEC_DEFAULT);
279         
280         /* add each marker to this menu */
281         for (marker= act->markers.first; marker; marker= marker->next)
282                 uiItemIntO(layout, marker->name, ICON_ARMATURE_DATA, "POSELIB_OT_pose_add", "frame", marker->frame);
283 }
284
285 static int poselib_add_menu_invoke (bContext *C, wmOperator *op, wmEvent *evt)
286 {
287         Scene *scene= CTX_data_scene(C);
288         Object *ob= CTX_data_active_object(C);
289         bArmature *arm= (ob) ? ob->data : NULL;
290         bPose *pose= (ob) ? ob->pose : NULL;
291         uiPopupMenu *pup;
292         uiLayout *layout;
293         
294         /* sanity check */
295         if (ELEM3(NULL, ob, arm, pose)) 
296                 return OPERATOR_CANCELLED;
297         
298         /* start building */
299         pup= uiPupMenuBegin(C, op->type->name, 0);
300         layout= uiPupMenuLayout(pup);
301         uiLayoutSetOperatorContext(layout, WM_OP_EXEC_DEFAULT);
302         
303         /* add new (adds to the first unoccupied frame) */
304         uiItemIntO(layout, "Add New", 0, "POSELIB_OT_pose_add", "frame", poselib_get_free_index(ob->poselib));
305         
306         /* check if we have any choices to add a new pose in any other way */
307         if ((ob->poselib) && (ob->poselib->markers.first)) {
308                 /* add new (on current frame) */
309                 uiItemIntO(layout, "Add New (Current Frame)", 0, "POSELIB_OT_pose_add", "frame", CFRA);
310                 
311                 /* replace existing - submenu */
312                 uiItemMenuF(layout, "Replace Existing...", 0, poselib_add_menu_invoke__replacemenu, NULL);
313         }
314         
315         uiPupMenuEnd(C, pup);
316         
317         /* this operator is only for a menu, not used further */
318         return OPERATOR_CANCELLED;
319 }
320
321
322 static int poselib_add_exec (bContext *C, wmOperator *op)
323 {
324         Object *ob= CTX_data_active_object(C);
325         bAction *act = poselib_validate(ob);
326         bArmature *arm= (ob) ? ob->data : NULL;
327         bPose *pose= (ob) ? ob->pose : NULL;
328         TimeMarker *marker;
329         int frame= RNA_int_get(op->ptr, "frame");
330         char name[64];
331         
332         /* sanity check (invoke should have checked this anyway) */
333         if (ELEM3(NULL, ob, arm, pose)) 
334                 return OPERATOR_CANCELLED;
335         
336         /* get name to give to pose */
337         RNA_string_get(op->ptr, "name", name);
338         
339         /* add pose to poselib - replaces any existing pose there
340          *      - for the 'replace' option, this should end up finding the appropriate marker,
341          *        so no new one will be added
342          */
343         for (marker= act->markers.first; marker; marker= marker->next) {
344                 if (marker->frame == frame) {
345                         BLI_strncpy(marker->name, name, sizeof(marker->name));
346                         break;
347                 }
348         }
349         if (marker == NULL) {
350                 marker= MEM_callocN(sizeof(TimeMarker), "ActionMarker");
351                 
352                 BLI_strncpy(marker->name, name, sizeof(marker->name));
353                 marker->frame= frame;
354                 
355                 BLI_addtail(&act->markers, marker);
356         }
357         
358         /* validate name */
359         BLI_uniquename(&act->markers, marker, "Pose", '.', offsetof(TimeMarker, name), sizeof(marker->name));
360         
361         /* KeyingSet to use depends on rotation mode (but that's handled by the templates code)  */
362         if (poselib_ks_locrotscale == NULL)
363                 poselib_ks_locrotscale= ANIM_builtin_keyingset_get_named(NULL, "LocRotScale");
364                 
365         /* make the keyingset use context info to determine where to add keyframes */
366         ANIM_apply_keyingset(C, NULL, act, poselib_ks_locrotscale, MODIFYKEY_MODE_INSERT, (float)frame);
367         
368         /* store new 'active' pose number */
369         act->active_marker= BLI_countlist(&act->markers);
370         
371         /* done */
372         return OPERATOR_FINISHED;
373 }
374
375 void POSELIB_OT_pose_add (wmOperatorType *ot)
376 {
377         /* identifiers */
378         ot->name= "PoseLib Add Pose";
379         ot->idname= "POSELIB_OT_pose_add";
380         ot->description= "Add the current Pose to the active Pose Library";
381         
382         /* api callbacks */
383         ot->invoke= poselib_add_menu_invoke;
384         ot->exec= poselib_add_exec;
385         ot->poll= ED_operator_posemode;
386         
387         /* flags */
388         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
389         
390         /* properties */
391         RNA_def_int(ot->srna, "frame", 1, 0, INT_MAX, "Frame", "Frame to store pose on", 0, INT_MAX);
392         RNA_def_string(ot->srna, "name", "Pose", 64, "Pose Name", "Name of newly added Pose");
393 }
394
395 /* ----- */
396
397 static EnumPropertyItem *poselib_stored_pose_itemf(bContext *C, PointerRNA *ptr, int *free)
398 {
399         Object *ob= CTX_data_active_object(C);
400         bAction *act= (ob) ? ob->poselib : NULL;
401         TimeMarker *marker;
402         EnumPropertyItem *item= NULL, item_tmp;
403         int totitem= 0;
404         int i= 0;
405
406         if (C==NULL) {
407                 return DummyRNA_DEFAULT_items;
408         }
409
410         memset(&item_tmp, 0, sizeof(item_tmp));
411         
412         /* check that the action exists */
413         if (act) {
414                 /* add each marker to the list */
415                 for (marker=act->markers.first, i=0; marker; marker= marker->next, i++) {
416                         item_tmp.identifier= item_tmp.name= marker->name;
417                         item_tmp.icon= ICON_ARMATURE_DATA;
418                         item_tmp.value= i;
419                         RNA_enum_item_add(&item, &totitem, &item_tmp);
420                 }
421         }
422
423         RNA_enum_item_end(&item, &totitem);
424         *free= 1;
425
426         return item;
427 }
428
429 static int poselib_remove_exec (bContext *C, wmOperator *op)
430 {
431         Object *ob= CTX_data_active_object(C);
432         bAction *act= (ob) ? ob->poselib : NULL;
433         TimeMarker *marker;
434         FCurve *fcu;
435         
436         /* check if valid poselib */
437         if (act == NULL) {
438                 BKE_report(op->reports, RPT_ERROR, "Object doesn't have PoseLib data");
439                 return OPERATOR_CANCELLED;
440         }
441         
442         /* get index (and pointer) of pose to remove */
443         marker= BLI_findlink(&act->markers, RNA_int_get(op->ptr, "pose"));
444         if (marker == NULL) {
445                 BKE_report(op->reports, RPT_ERROR, "Invalid index for Pose");
446                 return OPERATOR_CANCELLED;
447         }
448         
449         /* remove relevant keyframes */
450         for (fcu= act->curves.first; fcu; fcu= fcu->next) {
451                 BezTriple *bezt;
452                 int i;
453                 
454                 if (fcu->bezt) {
455                         for (i=0, bezt=fcu->bezt; i < fcu->totvert; i++, bezt++) {
456                                 /* check if remove */
457                                 if (IS_EQ(bezt->vec[1][0], marker->frame)) {
458                                         delete_fcurve_key(fcu, i, 1);
459                                         break;
460                                 }
461                         }
462                 }
463         }
464         
465         /* remove poselib from list */
466         BLI_freelinkN(&act->markers, marker);
467         
468         /* fix active pose number */
469         act->active_marker= 0;
470         
471         /* done */
472         return OPERATOR_FINISHED;
473 }
474
475 void POSELIB_OT_pose_remove (wmOperatorType *ot)
476 {
477         PropertyRNA *prop;
478         
479         /* identifiers */
480         ot->name= "PoseLib Remove Pose";
481         ot->idname= "POSELIB_OT_pose_remove";
482         ot->description= "Remove nth pose from the active Pose Library";
483         
484         /* api callbacks */
485         ot->invoke= WM_menu_invoke;
486         ot->exec= poselib_remove_exec;
487         ot->poll= ED_operator_posemode;
488         
489         /* flags */
490         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
491         
492         /* properties */
493         prop= RNA_def_enum(ot->srna, "pose", DummyRNA_DEFAULT_items, 0, "Pose", "The pose to remove");
494         RNA_def_enum_funcs(prop, poselib_stored_pose_itemf);
495         ot->prop= prop;
496 }
497
498 static int poselib_rename_invoke (bContext *C, wmOperator *op, wmEvent *evt)
499 {
500         Object *ob= CTX_data_active_object(C);
501         bAction *act= (ob) ? ob->poselib : NULL;
502         TimeMarker *marker;
503         
504         /* check if valid poselib */
505         if (act == NULL) {
506                 BKE_report(op->reports, RPT_ERROR, "Object doesn't have PoseLib data");
507                 return OPERATOR_CANCELLED;
508         }
509         
510         /* get index (and pointer) of pose to remove */
511         marker= BLI_findlink(&act->markers, act->active_marker-1);
512         if (marker == NULL) {
513                 BKE_report(op->reports, RPT_ERROR, "Invalid index for Pose");
514                 return OPERATOR_CANCELLED;
515         }
516         else {
517                 /* use the existing name of the marker as the name, and use the active marker as the one to rename */
518                 RNA_enum_set(op->ptr, "pose", act->active_marker-1);
519                 RNA_string_set(op->ptr, "name", marker->name);
520         }
521         
522         /* part to sync with other similar operators... */
523         return WM_operator_props_popup(C, op, evt);
524 }
525
526 static int poselib_rename_exec (bContext *C, wmOperator *op)
527 {
528         Object *ob= CTX_data_active_object(C);
529         bAction *act= (ob) ? ob->poselib : NULL;
530         TimeMarker *marker;
531         char newname[64];
532         
533         /* check if valid poselib */
534         if (act == NULL) {
535                 BKE_report(op->reports, RPT_ERROR, "Object doesn't have PoseLib data");
536                 return OPERATOR_CANCELLED;
537         }
538         
539         /* get index (and pointer) of pose to remove */
540         marker= BLI_findlink(&act->markers, RNA_int_get(op->ptr, "pose"));
541         if (marker == NULL) {
542                 BKE_report(op->reports, RPT_ERROR, "Invalid index for Pose");
543                 return OPERATOR_CANCELLED;
544         }
545         
546         /* get new name */
547         RNA_string_get(op->ptr, "name", newname);
548         
549         /* copy name and validate it */
550         BLI_strncpy(marker->name, newname, sizeof(marker->name));
551         BLI_uniquename(&act->markers, marker, "Pose", '.', offsetof(TimeMarker, name), sizeof(marker->name));
552         
553         /* done */
554         return OPERATOR_FINISHED;
555 }
556
557 void POSELIB_OT_pose_rename (wmOperatorType *ot)
558 {
559         PropertyRNA *prop;
560         static EnumPropertyItem prop_poses_dummy_types[] = {
561                 {0, NULL, 0, NULL, NULL}
562         };
563         
564         /* identifiers */
565         ot->name= "PoseLib Rename Pose";
566         ot->idname= "POSELIB_OT_pose_rename";
567         ot->description= "Rename nth pose from the active Pose Library";
568         
569         /* api callbacks */
570         ot->invoke= poselib_rename_invoke;
571         ot->exec= poselib_rename_exec;
572         ot->poll= ED_operator_posemode;
573         
574         /* flags */
575         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
576         
577         /* properties */
578         prop= RNA_def_enum(ot->srna, "pose", prop_poses_dummy_types, 0, "Pose", "The pose to rename");
579                 RNA_def_enum_funcs(prop, poselib_stored_pose_itemf);
580         RNA_def_string(ot->srna, "name", "RenamedPose", 64, "New Pose Name", "New name for pose");
581 }
582
583 /* ************************************************************* */
584
585 /* Simple struct for storing settings/data for use during PoseLib preview */
586 typedef struct tPoseLib_PreviewData {
587         ListBase backups;               /* tPoseLib_Backup structs for restoring poses */
588         ListBase searchp;               /* LinkData structs storing list of poses which match the current search-string */
589         
590         Scene *scene;                   /* active scene */
591         ScrArea *sa;                    /* active area */
592         
593         PointerRNA rna_ptr;             /* RNA-Pointer to Object 'ob' */
594         Object *ob;                             /* object to work on */
595         bArmature *arm;                 /* object's armature data */
596         bPose *pose;                    /* object's pose */
597         bAction *act;                   /* poselib to use */
598         TimeMarker *marker;             /* 'active' pose */
599         
600         int selcount;                   /* number of selected elements to work on */
601         int totcount;                   /* total number of elements to work on */
602         
603         short state;                    /* state of main loop */
604         short redraw;                   /* redraw/update settings during main loop */
605         short flag;                             /* flags for various settings */
606         
607         short search_cursor;    /* position of cursor in searchstr (cursor occurs before the item at the nominated index) */
608         char searchstr[64];             /* (Part of) Name to search for to filter poses that get shown */
609         char searchold[64];             /* Previously set searchstr (from last loop run), so that we can detected when to rebuild searchp */
610         
611         char headerstr[200];    /* Info-text to print in header */
612 } tPoseLib_PreviewData;
613
614 /* defines for tPoseLib_PreviewData->state values */
615 enum {
616         PL_PREVIEW_ERROR = -1,
617         PL_PREVIEW_RUNNING,
618         PL_PREVIEW_CONFIRM,
619         PL_PREVIEW_CANCEL,
620         PL_PREVIEW_RUNONCE 
621 };
622
623 /* defines for tPoseLib_PreviewData->redraw values */
624 enum {
625         PL_PREVIEW_NOREDRAW = 0,
626         PL_PREVIEW_REDRAWALL,
627         PL_PREVIEW_REDRAWHEADER,
628 };
629
630 /* defines for tPoseLib_PreviewData->flag values */
631 enum {
632         PL_PREVIEW_FIRSTTIME    = (1<<0),
633         PL_PREVIEW_SHOWORIGINAL = (1<<1)
634 };
635
636 /* ---------------------------- */
637
638 /* simple struct for storing backup info */
639 typedef struct tPoseLib_Backup {
640         struct tPoseLib_Backup *next, *prev;
641         
642         bPoseChannel *pchan;
643         bPoseChannel olddata;
644 } tPoseLib_Backup;
645
646 /* Makes a copy of the current pose for restoration purposes - doesn't do constraints currently */
647 static void poselib_backup_posecopy (tPoseLib_PreviewData *pld)
648 {
649         bActionGroup *agrp;
650         bPoseChannel *pchan;
651         
652         /* for each posechannel that has an actionchannel in */
653         for (agrp= pld->act->groups.first; agrp; agrp= agrp->next) {
654                 /* try to find posechannel */
655                 pchan= get_pose_channel(pld->pose, agrp->name);
656                 
657                 /* backup data if available */
658                 if (pchan) {
659                         tPoseLib_Backup *plb;
660                         
661                         /* store backup */
662                         plb= MEM_callocN(sizeof(tPoseLib_Backup), "tPoseLib_Backup");
663                         
664                         plb->pchan= pchan;
665                         memcpy(&plb->olddata, plb->pchan, sizeof(bPoseChannel));
666                         
667                         BLI_addtail(&pld->backups, plb);
668                         
669                         /* mark as being affected */
670                         if ((pchan->bone) && (pchan->bone->flag & BONE_SELECTED))
671                                 pld->selcount++;
672                         pld->totcount++;
673                 }
674         }
675 }
676
677 /* Restores original pose - doesn't do constraints currently */
678 static void poselib_backup_restore (tPoseLib_PreviewData *pld)
679 {
680         tPoseLib_Backup *plb;
681         
682         for (plb= pld->backups.first; plb; plb= plb->next) {
683                 memcpy(plb->pchan, &plb->olddata, sizeof(bPoseChannel));
684         }
685 }
686
687 /* ---------------------------- */
688
689 /* Applies the appropriate stored pose from the pose-library to the current pose
690  *      - assumes that a valid object, with a poselib has been supplied
691  *      - gets the string to print in the header
692  *      - this code is based on the code for extract_pose_from_action in blenkernel/action.c
693  */
694 static void poselib_apply_pose (tPoseLib_PreviewData *pld)
695 {
696         PointerRNA *ptr= &pld->rna_ptr;
697         bArmature *arm= pld->arm;
698         bPose *pose= pld->pose;
699         bPoseChannel *pchan;
700         bAction *act= pld->act;
701         bActionGroup *agrp;
702         
703         KeyframeEditData ked;
704         KeyframeEditFunc group_ok_cb;
705         int frame= 1;
706         
707         /* get the frame */
708         if (pld->marker)
709                 frame= pld->marker->frame;
710         else
711                 return; 
712         
713         
714         /* init settings for testing groups for keyframes */
715         group_ok_cb= ANIM_editkeyframes_ok(BEZT_OK_FRAMERANGE);
716         memset(&ked, 0, sizeof(KeyframeEditData)); 
717         ked.f1= ((float)frame) - 0.5f;
718         ked.f2= ((float)frame) + 0.5f;
719         
720         
721         /* start applying - only those channels which have a key at this point in time! */
722         for (agrp= act->groups.first; agrp; agrp= agrp->next) {
723                 /* check if group has any keyframes */
724                 if (ANIM_animchanneldata_keyframes_loop(&ked, agrp, ALE_GROUP, NULL, group_ok_cb, NULL, 0)) {
725                         /* has keyframe on this frame, so try to get a PoseChannel with this name */
726                         pchan= get_pose_channel(pose, agrp->name);
727                         
728                         if (pchan) {    
729                                 short ok= 0;
730                                 
731                                 /* check if this bone should get any animation applied */
732                                 if (pld->selcount == 0) {
733                                         /* if no bones are selected, then any bone is ok */
734                                         ok= 1;
735                                 }
736                                 else if (pchan->bone) {
737                                         /* only ok if bone is visible and selected */
738                                         if ( (pchan->bone->flag & BONE_SELECTED || pchan->bone == arm->act_bone) &&
739                                                  (pchan->bone->flag & BONE_HIDDEN_P)==0 &&
740                                                  (pchan->bone->layer & arm->layer) )
741                                                 ok = 1;
742                                 }
743                                 
744                                 if (ok) 
745                                         animsys_evaluate_action_group(ptr, act, agrp, NULL, (float)frame);
746                         }
747                 }
748         }
749 }
750
751 /* Auto-keys/tags bones affected by the pose used from the poselib */
752 static void poselib_keytag_pose (bContext *C, Scene *scene, tPoseLib_PreviewData *pld)
753 {
754         bPose *pose= pld->pose;
755         bPoseChannel *pchan;
756         bAction *act= pld->act;
757         bActionGroup *agrp;
758         
759         /* start tagging/keying */
760         for (agrp= act->groups.first; agrp; agrp= agrp->next) {
761                 /* only for selected action channels */
762                 if (agrp->flag & AGRP_SELECTED) {
763                         pchan= get_pose_channel(pose, agrp->name);
764                         
765                         if (pchan) {
766                                 if (autokeyframe_cfra_can_key(scene, &pld->ob->id)) {
767                                         ListBase dsources = {NULL, NULL};
768                                         KeyingSet *ks = NULL;
769                                         
770                                         /* get KeyingSet to use 
771                                          *      - use the active KeyingSet if defined (and user wants to use it for all autokeying), 
772                                          *        or otherwise key transforms only
773                                          */
774                                         if (poselib_ks_locrotscale == NULL)
775                                                 poselib_ks_locrotscale= ANIM_builtin_keyingset_get_named(NULL, "LocRotScale");
776                                          
777                                         if (IS_AUTOKEY_FLAG(ONLYKEYINGSET) && (scene->active_keyingset))
778                                                 ks = ANIM_scene_get_active_keyingset(scene);
779                                         else 
780                                                 ks = ANIM_builtin_keyingset_get_named(NULL, "LocRotScale");
781                                         
782                                         /* now insert the keyframe(s) using the Keying Set
783                                          *      1) add datasource override for the PoseChannel
784                                          *      2) insert keyframes
785                                          *      3) free the extra info 
786                                          */
787                                         ANIM_relative_keyingset_add_source(&dsources, &pld->ob->id, &RNA_PoseBone, pchan); 
788                                         ANIM_apply_keyingset(C, &dsources, NULL, ks, MODIFYKEY_MODE_INSERT, (float)CFRA);
789                                         BLI_freelistN(&dsources);
790                                         
791                                         /* clear any unkeyed tags */
792                                         if (pchan->bone)
793                                                 pchan->bone->flag &= ~BONE_UNKEYED;
794                                 }
795                                 else {
796                                         /* add unkeyed tags */
797                                         if (pchan->bone)
798                                                 pchan->bone->flag |= BONE_UNKEYED;
799                                 }
800                         }
801                 }
802         }
803         
804         /* send notifiers for this */
805         WM_event_add_notifier(C, NC_ANIMATION|ND_KEYFRAME|NA_EDITED, NULL);
806 }
807
808 /* Apply the relevant changes to the pose */
809 static void poselib_preview_apply (bContext *C, wmOperator *op)
810 {
811         tPoseLib_PreviewData *pld= (tPoseLib_PreviewData *)op->customdata;
812         
813         /* only recalc pose (and its dependencies) if pose has changed */
814         if (pld->redraw == PL_PREVIEW_REDRAWALL) {
815                 /* don't clear pose if firsttime */
816                 if ((pld->flag & PL_PREVIEW_FIRSTTIME)==0)
817                         poselib_backup_restore(pld);
818                 else
819                         pld->flag &= ~PL_PREVIEW_FIRSTTIME;
820                         
821                 /* pose should be the right one to draw (unless we're temporarily not showing it) */
822                 if ((pld->flag & PL_PREVIEW_SHOWORIGINAL)==0) {
823                         RNA_int_set(op->ptr, "pose_index", BLI_findindex(&pld->act->markers, pld->marker));
824                         poselib_apply_pose(pld);
825                 }
826                 else
827                         RNA_int_set(op->ptr, "pose_index", -2); /* -2 means don't apply any pose */
828                 
829                 /* old optimize trick... this enforces to bypass the depgraph 
830                  *      - note: code copied from transform_generics.c -> recalcData()
831                  */
832                 // FIXME: shouldn't this use the builtin stuff?
833                 if ((pld->arm->flag & ARM_DELAYDEFORM)==0)
834                         DAG_id_flush_update(&pld->ob->id, OB_RECALC_DATA);  /* sets recalc flags */
835                 else
836                         where_is_pose(pld->scene, pld->ob);
837         }
838         
839         /* do header print - if interactively previewing */
840         if (pld->state == PL_PREVIEW_RUNNING) {
841                 if (pld->flag & PL_PREVIEW_SHOWORIGINAL) {
842                         sprintf(pld->headerstr, "PoseLib Previewing Pose: [Showing Original Pose] | Use Tab to start previewing poses again");
843                         ED_area_headerprint(pld->sa, pld->headerstr);
844                 }
845                 else if (pld->searchstr[0]) {
846                         char tempstr[65];
847                         char markern[64];
848                         short index;
849                         
850                         /* get search-string */
851                         index= pld->search_cursor;
852                         
853                         if (index >= 0 && index <= 64) {
854                                 memcpy(&tempstr[0], &pld->searchstr[0], index);
855                                 tempstr[index]= '|';
856                                 memcpy(&tempstr[index+1], &pld->searchstr[index], 64-index);
857                         }
858                         else {
859                                 strncpy(tempstr, pld->searchstr, 64);
860                         }
861                         
862                         /* get marker name */
863                         if (pld->marker)
864                                 strcpy(markern, pld->marker->name);
865                         else
866                                 strcpy(markern, "No Matches");
867                         
868                         sprintf(pld->headerstr, "PoseLib Previewing Pose: Filter - [%s] | Current Pose - \"%s\"  | Use ScrollWheel or PageUp/Down to change", tempstr, markern);
869                         ED_area_headerprint(pld->sa, pld->headerstr);
870                 }
871                 else {
872                         sprintf(pld->headerstr, "PoseLib Previewing Pose: \"%s\"  | Use ScrollWheel or PageUp/Down to change", pld->marker->name);
873                         ED_area_headerprint(pld->sa, pld->headerstr);
874                 }
875         }
876         
877         /* request drawing of view + clear redraw flag */
878         WM_event_add_notifier(C, NC_OBJECT|ND_POSE, pld->ob);
879         pld->redraw= PL_PREVIEW_NOREDRAW;
880 }
881
882 /* ---------------------------- */
883
884 /* This helper function is called during poselib_preview_poses to find the 
885  * pose to preview next (after a change event)
886  */
887 static void poselib_preview_get_next (tPoseLib_PreviewData *pld, int step)
888 {
889         /* check if we no longer have search-string, but don't have any marker */
890         if (pld->marker == NULL) {
891                 if ((step) && (pld->searchstr[0] == 0))
892                         pld->marker= pld->act->markers.first;
893         }       
894         
895         /* the following operations assume that there is a starting point and direction */
896         if ((pld->marker) && (step)) {
897                 /* search-string dictates a special approach */
898                 if (pld->searchstr[0]) {
899                         TimeMarker *marker;
900                         LinkData *ld, *ldn, *ldc;
901                         
902                         /* free and rebuild if needed (i.e. if search-str changed) */
903                         if (strcmp(pld->searchstr, pld->searchold)) {
904                                 /* free list of temporary search matches */
905                                 BLI_freelistN(&pld->searchp);
906                                 
907                                 /* generate a new list of search matches */
908                                 for (marker= pld->act->markers.first; marker; marker= marker->next) {
909                                         /* does the name partially match? 
910                                          *      - don't worry about case, to make it easier for users to quickly input a name (or 
911                                          *        part of one), which is the whole point of this feature
912                                          */
913                                         if (BLI_strcasestr(marker->name, pld->searchstr)) {
914                                                 /* make link-data to store reference to it */
915                                                 ld= MEM_callocN(sizeof(LinkData), "PoseMatch");
916                                                 ld->data= marker;
917                                                 BLI_addtail(&pld->searchp, ld);
918                                         }
919                                 }
920                                 
921                                 /* set current marker to NULL (so that we start from first) */
922                                 pld->marker= NULL;
923                         }
924                         
925                         /* check if any matches */
926                         if (pld->searchp.first == NULL) { 
927                                 pld->marker= NULL;
928                                 return;
929                         }
930                         
931                         /* find first match */
932                         for (ldc= pld->searchp.first; ldc; ldc= ldc->next) {
933                                 if (ldc->data == pld->marker)
934                                         break;
935                         }
936                         if (ldc == NULL)
937                                 ldc= pld->searchp.first;
938                                 
939                         /* Loop through the matches in a cyclic fashion, incrementing/decrementing step as appropriate 
940                          * until step == 0. At this point, marker should be the correct marker.
941                          */
942                         if (step > 0) {
943                                 for (ld=ldc; ld && step; ld=ldn, step--)
944                                         ldn= (ld->next) ? ld->next : pld->searchp.first;
945                         }
946                         else {
947                                 for (ld=ldc; ld && step; ld=ldn, step++)
948                                         ldn= (ld->prev) ? ld->prev : pld->searchp.last;
949                         }
950                         
951                         /* set marker */
952                         if (ld)
953                                 pld->marker= ld->data;
954                 }
955                 else {
956                         TimeMarker *marker, *next;
957                         
958                         /* Loop through the markers in a cyclic fashion, incrementing/decrementing step as appropriate 
959                          * until step == 0. At this point, marker should be the correct marker.
960                          */
961                         if (step > 0) {
962                                 for (marker=pld->marker; marker && step; marker=next, step--)
963                                         next= (marker->next) ? marker->next : pld->act->markers.first;
964                         }
965                         else {
966                                 for (marker=pld->marker; marker && step; marker=next, step++)
967                                         next= (marker->prev) ? marker->prev : pld->act->markers.last;
968                         }
969                         
970                         /* it should be fairly impossible for marker to be NULL */
971                         if (marker)
972                                 pld->marker= marker;
973                 }
974         }
975 }
976
977 /* specially handle events for searching */
978 static void poselib_preview_handle_search (tPoseLib_PreviewData *pld, unsigned short event, char ascii)
979 {
980         /* try doing some form of string manipulation first */
981         switch (event) {
982                 case BACKSPACEKEY:
983                         if (pld->searchstr[0] && pld->search_cursor) {
984                                 short len= strlen(pld->searchstr);
985                                 short index= pld->search_cursor;
986                                 short i;
987                                 
988                                 for (i = index; i <= len; i++) 
989                                         pld->searchstr[i-1] = pld->searchstr[i];
990                                 
991                                 pld->search_cursor--;
992                                 
993                                 poselib_preview_get_next(pld, 1);
994                                 pld->redraw = PL_PREVIEW_REDRAWALL;
995                                 return;
996                         }       
997                         break;
998                         
999                 case DELKEY:
1000                         if (pld->searchstr[0] && pld->searchstr[1]) {
1001                                 short len= strlen(pld->searchstr);
1002                                 short index= pld->search_cursor;
1003                                 int i;
1004                                 
1005                                 if (index < len) {
1006                                         for (i = index; i < len; i++) 
1007                                                 pld->searchstr[i] = pld->searchstr[i+1];
1008                                                 
1009                                         poselib_preview_get_next(pld, 1);
1010                                         pld->redraw = PL_PREVIEW_REDRAWALL;
1011                                         return;
1012                                 }
1013                         }
1014                         break;
1015         }
1016         
1017         if (ascii) {
1018                 /* character to add to the string */
1019                 short index= pld->search_cursor;
1020                 short len= (pld->searchstr[0]) ? strlen(pld->searchstr) : 0;
1021                 short i;
1022                 
1023                 if (len) {
1024                         for (i = len; i > index; i--)  
1025                                 pld->searchstr[i]= pld->searchstr[i-1];
1026                 }
1027                 else
1028                         pld->searchstr[1]= 0;
1029                         
1030                 pld->searchstr[index]= ascii;
1031                 pld->search_cursor++;
1032                 
1033                 poselib_preview_get_next(pld, 1);
1034                 pld->redraw = PL_PREVIEW_REDRAWALL;
1035         }
1036 }
1037
1038 /* handle events for poselib_preview_poses */
1039 static int poselib_preview_handle_event (bContext *C, wmOperator *op, wmEvent *event)
1040 {
1041         tPoseLib_PreviewData *pld= op->customdata; 
1042         int ret = OPERATOR_RUNNING_MODAL;
1043         
1044         /* backup stuff that needs to occur before every operation
1045          *      - make a copy of searchstr, so that we know if cache needs to be rebuilt
1046          */
1047         strcpy(pld->searchold, pld->searchstr);
1048         
1049         /* if we're currently showing the original pose, only certain events are handled */
1050         if (pld->flag & PL_PREVIEW_SHOWORIGINAL) {
1051                 switch (event->type) {
1052                         /* exit - cancel */
1053                         case ESCKEY:
1054                         case RIGHTMOUSE:
1055                                 pld->state= PL_PREVIEW_CANCEL;
1056                                 break;
1057                                 
1058                         /* exit - confirm */
1059                         case LEFTMOUSE:
1060                         case RETKEY:
1061                         case PADENTER:
1062                         case SPACEKEY:
1063                                 pld->state= PL_PREVIEW_CONFIRM;
1064                                 break;
1065                         
1066                         /* view manipulation */
1067                         /* we add pass through here, so that the operators responsible for these can still run, 
1068                          * even though we still maintain control (as RUNNING_MODAL flag is still set too)
1069                          */
1070                         case PAD0: case PAD1: case PAD2: case PAD3: case PAD4:
1071                         case PAD5: case PAD6: case PAD7: case PAD8: case PAD9:
1072                         case PADPLUSKEY: case PADMINUS: case MIDDLEMOUSE:
1073                                 //pld->redraw= PL_PREVIEW_REDRAWHEADER;
1074                                 ret |= OPERATOR_PASS_THROUGH;
1075                                 break;
1076                                 
1077                         /* quicky compare to original */
1078                         case TABKEY:
1079                                 /* only respond to one event */
1080                                 if (event->val == 0) {
1081                                         pld->flag &= ~PL_PREVIEW_SHOWORIGINAL;
1082                                         pld->redraw= PL_PREVIEW_REDRAWALL;
1083                                 }
1084                                 break;
1085                 }
1086                 
1087                 /* EXITS HERE... */
1088                 return ret;
1089         }
1090         
1091         /* NORMAL EVENT HANDLING... */
1092         /* searching takes priority over normal activity */
1093         switch (event->type) {
1094                 /* exit - cancel */
1095                 case ESCKEY:
1096                 case RIGHTMOUSE:
1097                         pld->state= PL_PREVIEW_CANCEL;
1098                         break;
1099                         
1100                 /* exit - confirm */
1101                 case LEFTMOUSE:
1102                 case RETKEY:
1103                 case PADENTER:
1104                 case SPACEKEY:
1105                         pld->state= PL_PREVIEW_CONFIRM;
1106                         break;
1107                         
1108                 /* toggle between original pose and poselib pose*/
1109                 case TABKEY:
1110                         /* only respond to one event */
1111                         if (event->val == 0) {
1112                                 pld->flag |= PL_PREVIEW_SHOWORIGINAL;
1113                                 pld->redraw= PL_PREVIEW_REDRAWALL;
1114                         }
1115                         break;
1116                 
1117                 /* change to previous pose (cyclic) */
1118                 case PAGEUPKEY:
1119                 case WHEELUPMOUSE:
1120                         poselib_preview_get_next(pld, -1);
1121                         pld->redraw= PL_PREVIEW_REDRAWALL;
1122                         break;
1123                 
1124                 /* change to next pose (cyclic) */
1125                 case PAGEDOWNKEY:
1126                 case WHEELDOWNMOUSE:
1127                         poselib_preview_get_next(pld, 1);
1128                         pld->redraw= PL_PREVIEW_REDRAWALL;
1129                         break;
1130                 
1131                 /* jump 5 poses (cyclic, back) */
1132                 case DOWNARROWKEY:
1133                         poselib_preview_get_next(pld, -5);
1134                         pld->redraw= PL_PREVIEW_REDRAWALL;
1135                         break;
1136                 
1137                 /* jump 5 poses (cyclic, forward) */
1138                 case UPARROWKEY:
1139                         poselib_preview_get_next(pld, 5);
1140                         pld->redraw= PL_PREVIEW_REDRAWALL;
1141                         break;
1142                 
1143                 /* change to next pose or searching cursor control */
1144                 case RIGHTARROWKEY:
1145                         if (pld->searchstr[0]) {
1146                                 /* move text-cursor to the right */
1147                                 if (pld->search_cursor < strlen(pld->searchstr))
1148                                         pld->search_cursor++;
1149                                 pld->redraw= PL_PREVIEW_REDRAWHEADER;
1150                         }
1151                         else {
1152                                 /* change to next pose (cyclic) */
1153                                 poselib_preview_get_next(pld, 1);
1154                                 pld->redraw= PL_PREVIEW_REDRAWALL;
1155                         }
1156                         break;
1157                         
1158                 /* change to next pose or searching cursor control */
1159                 case LEFTARROWKEY:
1160                         if (pld->searchstr[0]) {
1161                                 /* move text-cursor to the left */
1162                                 if (pld->search_cursor)
1163                                         pld->search_cursor--;
1164                                 pld->redraw= PL_PREVIEW_REDRAWHEADER;
1165                         }
1166                         else {
1167                                 /* change to previous pose (cyclic) */
1168                                 poselib_preview_get_next(pld, -1);
1169                                 pld->redraw= PL_PREVIEW_REDRAWALL;
1170                         }
1171                         break;
1172                         
1173                 /* change to first pose or start of searching string */
1174                 case HOMEKEY:
1175                         if (pld->searchstr[0]) {
1176                                 pld->search_cursor= 0;
1177                                 pld->redraw= PL_PREVIEW_REDRAWHEADER;
1178                         }
1179                         else {
1180                                 /* change to first pose */
1181                                 pld->marker= pld->act->markers.first;
1182                                 pld->act->active_marker= 1;
1183                                 
1184                                 pld->redraw= PL_PREVIEW_REDRAWALL;
1185                         }
1186                         break;
1187                         
1188                 /* change to last pose or start of searching string */
1189                 case ENDKEY:
1190                         if (pld->searchstr[0]) {
1191                                 pld->search_cursor= strlen(pld->searchstr);
1192                                 pld->redraw= PL_PREVIEW_REDRAWHEADER;
1193                         }
1194                         else {
1195                                 /* change to last pose */
1196                                 pld->marker= pld->act->markers.last;
1197                                 pld->act->active_marker= BLI_countlist(&pld->act->markers);
1198                                 
1199                                 pld->redraw= PL_PREVIEW_REDRAWALL;
1200                         }
1201                         break;
1202                 
1203                 /* view manipulation */
1204                 /* we add pass through here, so that the operators responsible for these can still run, 
1205                  * even though we still maintain control (as RUNNING_MODAL flag is still set too)
1206                  */
1207                 case MIDDLEMOUSE:
1208                         //pld->redraw= PL_PREVIEW_REDRAWHEADER;
1209                         ret |= OPERATOR_PASS_THROUGH;
1210                         break;
1211                         
1212                 /* view manipulation, or searching */
1213                 case PAD0: case PAD1: case PAD2: case PAD3: case PAD4:
1214                 case PAD5: case PAD6: case PAD7: case PAD8: case PAD9:
1215                 case PADPLUSKEY: case PADMINUS:
1216                         if (pld->searchstr[0]) {
1217                                 /* searching... */
1218                                 poselib_preview_handle_search(pld, event->type, event->ascii);
1219                         }
1220                         else {
1221                                 /* view manipulation (see above) */
1222                                 //pld->redraw= PL_PREVIEW_REDRAWHEADER;
1223                                 ret |= OPERATOR_PASS_THROUGH;
1224                         }
1225                         break;
1226                         
1227                 /* otherwise, assume that searching might be able to handle it */
1228                 default:
1229                         poselib_preview_handle_search(pld, event->type, event->ascii);
1230                         break;
1231         }
1232         
1233         return ret;
1234 }
1235
1236 /* ---------------------------- */
1237
1238 /* Init PoseLib Previewing data */
1239 static void poselib_preview_init_data (bContext *C, wmOperator *op)
1240 {
1241         tPoseLib_PreviewData *pld;
1242         Object *ob= CTX_data_active_object(C);
1243         int pose_index = RNA_int_get(op->ptr, "pose_index");
1244         
1245         /* set up preview state info */
1246         op->customdata= pld= MEM_callocN(sizeof(tPoseLib_PreviewData), "PoseLib Preview Data");
1247         
1248         /* get basic data */
1249         pld->ob= ob;
1250         pld->arm= (ob) ? (ob->data) : NULL;
1251         pld->pose= (ob) ? (ob->pose) : NULL;
1252         pld->act= (ob) ? (ob->poselib) : NULL;
1253         
1254         pld->scene= CTX_data_scene(C);
1255         pld->sa= CTX_wm_area(C);
1256         
1257         /* get starting pose based on RNA-props for this operator */
1258         if (pose_index == -1)
1259                 pld->marker= poselib_get_active_pose(pld->act);
1260         else if (pose_index == -2)
1261                 pld->flag |= PL_PREVIEW_SHOWORIGINAL;
1262         else
1263                 pld->marker= (pld->act) ? BLI_findlink(&pld->act->markers, pose_index) : NULL;
1264         
1265         /* check if valid poselib */
1266         if (ELEM3(NULL, pld->ob, pld->pose, pld->arm)) {
1267                 BKE_report(op->reports, RPT_ERROR, "PoseLib is only for Armatures in PoseMode");
1268                 pld->state= PL_PREVIEW_ERROR;
1269                 return;
1270         }
1271         if (pld->act == NULL) {
1272                 BKE_report(op->reports, RPT_ERROR, "Object doesn't have a valid PoseLib");
1273                 pld->state= PL_PREVIEW_ERROR;
1274                 return;
1275         }
1276         if (pld->marker == NULL) {
1277                 if (pld->act->markers.first) {
1278                         /* just use first one then... */
1279                         pld->marker= pld->act->markers.first;
1280                         if (pose_index > -2) 
1281                                 BKE_report(op->reports, RPT_WARNING, "PoseLib had no active pose");
1282                 }
1283                 else {
1284                         BKE_report(op->reports, RPT_ERROR, "PoseLib has no poses to preview/apply");
1285                         pld->state= PL_PREVIEW_ERROR;
1286                         return;
1287                 }
1288         }
1289         
1290         /* get ID pointer for applying poses */
1291         RNA_id_pointer_create(&ob->id, &pld->rna_ptr);
1292         
1293         /* make backups for restoring pose */
1294         poselib_backup_posecopy(pld);
1295         
1296         /* set flags for running */
1297         pld->state= PL_PREVIEW_RUNNING;
1298         pld->redraw= PL_PREVIEW_REDRAWALL;
1299         pld->flag |= PL_PREVIEW_FIRSTTIME;
1300         
1301         /* set depsgraph flags */
1302                 /* make sure the lock is set OK, unlock can be accidentally saved? */
1303         pld->pose->flag |= POSE_LOCKED;
1304         pld->pose->flag &= ~POSE_DO_UNLOCK;
1305         
1306         /* clear strings + search */
1307         strcpy(pld->headerstr, "");
1308         strcpy(pld->searchstr, "");
1309         strcpy(pld->searchold, "");
1310         pld->search_cursor= 0;
1311 }
1312
1313 /* After previewing poses */
1314 static void poselib_preview_cleanup (bContext *C, wmOperator *op)
1315 {
1316         tPoseLib_PreviewData *pld= (tPoseLib_PreviewData *)op->customdata;
1317         Scene *scene= pld->scene;
1318         Object *ob= pld->ob;
1319         bPose *pose= pld->pose;
1320         bArmature *arm= pld->arm;
1321         bAction *act= pld->act;
1322         TimeMarker *marker= pld->marker;
1323         
1324         /* redraw the header so that it doesn't show any of our stuff anymore */
1325         ED_area_headerprint(pld->sa, NULL);
1326         
1327         /* this signal does one recalc on pose, then unlocks, so ESC or edit will work */
1328         pose->flag |= POSE_DO_UNLOCK;
1329         
1330         /* clear pose if cancelled */
1331         if (pld->state == PL_PREVIEW_CANCEL) {
1332                 poselib_backup_restore(pld);
1333                 
1334                 /* old optimize trick... this enforces to bypass the depgraph 
1335                  *      - note: code copied from transform_generics.c -> recalcData()
1336                  */
1337                 if ((arm->flag & ARM_DELAYDEFORM)==0)
1338                         DAG_id_flush_update(&ob->id, OB_RECALC_DATA);  /* sets recalc flags */
1339                 else
1340                         where_is_pose(scene, ob);
1341                 
1342         }
1343         else if (pld->state == PL_PREVIEW_CONFIRM) {
1344                 /* tag poses as appropriate */
1345                 poselib_keytag_pose(C, scene, pld);
1346                 
1347                 /* change active pose setting */
1348                 act->active_marker= BLI_findindex(&act->markers, marker) + 1;
1349                 action_set_activemarker(act, marker, 0);
1350                 
1351                 /* Update event for pose and deformation children */
1352                 DAG_id_flush_update(&ob->id, OB_RECALC_DATA);
1353                 
1354                 /* updates */
1355                 if (IS_AUTOKEY_MODE(scene, NORMAL)) {
1356                         //remake_action_ipos(ob->action);
1357                 }
1358                 else {
1359                         /* need to trick depgraph, action is not allowed to execute on pose */
1360                         where_is_pose(scene, ob);
1361                         ob->recalc= 0;
1362                 }
1363         }
1364         
1365         /* free memory used for backups */
1366         BLI_freelistN(&pld->backups);
1367         BLI_freelistN(&pld->searchp);
1368         
1369         /* free temp data for operator */
1370         MEM_freeN(pld);
1371         op->customdata= NULL;
1372 }
1373
1374 /* End previewing operation */
1375 static int poselib_preview_exit (bContext *C, wmOperator *op)
1376 {
1377         tPoseLib_PreviewData *pld= op->customdata;
1378         
1379         /* finish up */
1380         poselib_preview_cleanup(C, op);
1381         
1382         if (ELEM(pld->state, PL_PREVIEW_CANCEL, PL_PREVIEW_ERROR))
1383                 return OPERATOR_CANCELLED;
1384         else
1385                 return OPERATOR_FINISHED;
1386 }
1387
1388 /* Cancel previewing operation (called when exiting Blender) */
1389 static int poselib_preview_cancel (bContext *C, wmOperator *op)
1390 {
1391         poselib_preview_exit(C, op);
1392         return OPERATOR_CANCELLED;
1393 }
1394
1395 /* main modal status check */
1396 static int poselib_preview_modal (bContext *C, wmOperator *op, wmEvent *event)
1397 {
1398         tPoseLib_PreviewData *pld= op->customdata;
1399         int ret;
1400         
1401         /* 1) check state to see if we're still running */
1402         if (pld->state != PL_PREVIEW_RUNNING)
1403                 return poselib_preview_exit(C, op);
1404         
1405         /* 2) handle events */
1406         ret= poselib_preview_handle_event(C, op, event);
1407         
1408         /* 3) apply changes and redraw, otherwise, confirming goes wrong */
1409         if (pld->redraw)
1410                 poselib_preview_apply(C, op);
1411         
1412         return ret;
1413 }
1414
1415 /* Modal Operator init */
1416 static int poselib_preview_invoke(bContext *C, wmOperator *op, wmEvent *event)
1417 {
1418         tPoseLib_PreviewData *pld;
1419         
1420         /* check if everything is ok, and init settings for modal operator */
1421         poselib_preview_init_data(C, op);
1422         pld= (tPoseLib_PreviewData *)op->customdata;
1423         
1424         if (pld->state == PL_PREVIEW_ERROR) {
1425                 /* an error occurred, so free temp mem used */
1426                 poselib_preview_cleanup(C, op);
1427                 return OPERATOR_CANCELLED;
1428         }
1429         
1430         /* do initial apply to have something to look at */
1431         poselib_preview_apply(C, op);
1432         
1433         /* add temp handler if we're running as a modal operator */
1434         WM_event_add_modal_handler(C, op);
1435
1436         return OPERATOR_RUNNING_MODAL;
1437 }
1438
1439 /* Repeat operator */
1440 static int poselib_preview_exec (bContext *C, wmOperator *op)
1441 {
1442         tPoseLib_PreviewData *pld;
1443         
1444         /* check if everything is ok, and init settings for modal operator */
1445         poselib_preview_init_data(C, op);
1446         pld= (tPoseLib_PreviewData *)op->customdata;
1447         
1448         if (pld->state == PL_PREVIEW_ERROR) {
1449                 /* an error occurred, so free temp mem used */
1450                 poselib_preview_cleanup(C, op);
1451                 return OPERATOR_CANCELLED;
1452         }
1453         
1454         /* the exec() callback is effectively a 'run-once' scenario, so set the state to that
1455          * so that everything draws correctly
1456          */
1457         pld->state = PL_PREVIEW_RUNONCE;
1458         
1459         /* apply the active pose */
1460         poselib_preview_apply(C, op);
1461         
1462         /* now, set the status to exit */
1463         pld->state = PL_PREVIEW_CONFIRM;
1464         
1465         /* cleanup */
1466         return poselib_preview_exit(C, op);
1467 }
1468
1469 void POSELIB_OT_browse_interactive (wmOperatorType *ot)
1470 {
1471         /* identifiers */
1472         ot->name= "PoseLib Browse Poses";
1473         ot->idname= "POSELIB_OT_browse_interactive";
1474         ot->description= "Interactively browse poses in 3D-View";
1475         
1476         /* api callbacks */
1477         ot->invoke= poselib_preview_invoke;
1478         ot->modal= poselib_preview_modal;
1479         ot->cancel= poselib_preview_cancel;
1480         ot->exec= poselib_preview_exec;
1481         ot->poll= ED_operator_posemode;
1482         
1483         /* flags */
1484         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO|OPTYPE_BLOCKING;
1485         
1486         /* properties */        
1487                 // TODO: make the pose_index into a proper enum instead of a cryptic int...
1488         ot->prop= RNA_def_int(ot->srna, "pose_index", -1, -2, INT_MAX, "Pose", "Index of the pose to apply (-2 for no change to pose, -1 for poselib active pose)", 0, INT_MAX);
1489                 // XXX: percentage vs factor?
1490         RNA_def_float_factor(ot->srna, "blend_factor", 1.0f, 0.0f, 1.0f, "Blend Factor", "Amount that the pose is applied on top of the existing poses", 0.0f, 1.0f);
1491 }