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