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