Code cleanup: use bools where possible
[blender.git] / source / blender / editors / object / object_constraint.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) 2001-2002 by NaN Holding BV.
19  * All rights reserved.
20  *
21  * The Original Code is: all of this file.
22  *
23  * Contributor(s): Joshua Leung, Blender Foundation
24  *
25  * ***** END GPL LICENSE BLOCK *****
26  */
27
28 /** \file blender/editors/object/object_constraint.c
29  *  \ingroup edobj
30  */
31
32
33 #include <stdio.h>
34 #include <string.h>
35
36 #include "MEM_guardedalloc.h"
37
38 #include "BLI_blenlib.h"
39 #include "BLI_math.h"
40 #include "BLI_dynstr.h"
41 #include "BLI_utildefines.h"
42
43 #include "BLF_translation.h"
44
45 #include "DNA_anim_types.h"
46 #include "DNA_constraint_types.h"
47 #include "DNA_curve_types.h"
48 #include "DNA_scene_types.h"
49 #include "DNA_text_types.h"
50 #include "DNA_object_types.h"
51
52 #include "BKE_action.h"
53 #include "BKE_armature.h"
54 #include "BKE_constraint.h"
55 #include "BKE_context.h"
56 #include "BKE_depsgraph.h"
57 #include "BKE_fcurve.h"
58 #include "BKE_global.h"
59 #include "BKE_main.h"
60 #include "BKE_object.h"
61 #include "BKE_report.h"
62 #include "BKE_tracking.h"
63 #include "BIK_api.h"
64
65 #ifdef WITH_PYTHON
66 #include "BPY_extern.h"
67 #endif
68
69 #include "WM_api.h"
70 #include "WM_types.h"
71
72 #include "RNA_access.h"
73 #include "RNA_define.h"
74 #include "RNA_enum_types.h"
75
76 #include "ED_object.h"
77 #include "ED_armature.h"
78 #include "ED_keyframing.h"
79 #include "ED_screen.h"
80
81 #include "UI_interface.h"
82 #include "UI_resources.h"
83
84 #include "object_intern.h"
85
86 /* -------------- Get Active Constraint Data ---------------------- */
87
88 /* if object in posemode, active bone constraints, else object constraints */
89 ListBase *get_active_constraints(Object *ob)
90 {
91         if (ob == NULL)
92                 return NULL;
93         
94         if (ob->mode & OB_MODE_POSE) {
95                 bPoseChannel *pchan;
96                 
97                 pchan = BKE_pose_channel_active(ob);
98                 if (pchan)
99                         return &pchan->constraints;
100         }
101         else 
102                 return &ob->constraints;
103         
104         return NULL;
105 }
106
107 /* Find the list that a given constraint belongs to, and/or also get the posechannel this is from (if applicable) */
108 ListBase *get_constraint_lb(Object *ob, bConstraint *con, bPoseChannel **pchan_r)
109 {
110         if (pchan_r)
111                 *pchan_r = NULL;
112         
113         if (ELEM(NULL, ob, con))
114                 return NULL;
115         
116         /* try object constraints first */
117         if ((BLI_findindex(&ob->constraints, con) != -1)) {
118                 return &ob->constraints;
119         }
120         
121         /* if armature, try pose bones too */
122         if (ob->pose) {
123                 bPoseChannel *pchan;
124                 
125                 /* try each bone in order 
126                  * NOTE: it's not possible to directly look up the active bone yet, so this will have to do
127                  */
128                 for (pchan = ob->pose->chanbase.first; pchan; pchan = pchan->next) {
129                         if ((BLI_findindex(&pchan->constraints, con) != -1)) {
130                                 
131                                 if (pchan_r)
132                                         *pchan_r = pchan;
133                                 
134                                 return &pchan->constraints;
135                         }
136                 }
137         }
138         
139         /* done */
140         return NULL;
141 }
142
143 /* single constraint */
144 bConstraint *get_active_constraint(Object *ob)
145 {
146         return BKE_constraints_get_active(get_active_constraints(ob));
147 }
148
149 /* -------------- Constraint Management (Add New, Remove, Rename) -------------------- */
150 #ifdef WITH_PYTHON
151 /* ------------- PyConstraints ------------------ */
152
153 /* this callback sets the text-file to be used for selected menu item */
154 static void validate_pyconstraint_cb(void *arg1, void *arg2)
155 {
156         bPythonConstraint *data = arg1;
157         Text *text = NULL;
158         int index = *((int *)arg2);
159         int i;
160         
161         /* exception for no script */
162         if (index) {
163                 /* innovative use of a for...loop to search */
164                 for (text = G.main->text.first, i = 1; text && index != i; i++, text = text->id.next) ;
165         }
166         data->text = text;
167 }
168
169 /* this returns a string for the list of usable pyconstraint script names */
170 static char *buildmenu_pyconstraints(Text *con_text, int *pyconindex)
171 {
172         DynStr *pupds = BLI_dynstr_new();
173         Text *text;
174         char *str;
175         char buf[64];
176         int i;
177         
178         /* add title first */
179         sprintf(buf, "Scripts: %%t|[None]%%x0|");
180         BLI_dynstr_append(pupds, buf);
181         
182         /* init active-index first */
183         if (con_text == NULL)
184                 *pyconindex = 0;
185         
186         /* loop through markers, adding them */
187         for (text = G.main->text.first, i = 1; text; i++, text = text->id.next) {
188                 /* this is important to ensure that right script is shown as active */
189                 if (text == con_text) *pyconindex = i;
190                 
191                 /* only include valid pyconstraint scripts */
192                 if (BPY_is_pyconstraint(text)) {
193                         BLI_dynstr_append(pupds, text->id.name + 2);
194                         
195                         sprintf(buf, "%%x%d", i);
196                         BLI_dynstr_append(pupds, buf);
197                         
198                         if (text->id.next)
199                                 BLI_dynstr_append(pupds, "|");
200                 }
201         }
202         
203         /* convert to normal MEM_malloc'd string */
204         str = BLI_dynstr_get_cstring(pupds);
205         BLI_dynstr_free(pupds);
206         
207         return str;
208 }
209 #endif /* WITH_PYTHON */
210
211 #if 0 // UNUSED, until pyconstraints are added back.
212 /* this callback gets called when the 'refresh' button of a pyconstraint gets pressed */
213 static void update_pyconstraint_cb(void *arg1, void *arg2)
214 {
215 #ifndef WITH_PYTHON
216         (void)arg1; /* unused */
217         (void)arg2; /* unused */
218 #else
219         Object *owner = (Object *)arg1;
220         bConstraint *con = (bConstraint *)arg2;
221         if (owner && con)
222                 BPY_pyconstraint_update(owner, con);
223 #endif
224 }
225 #endif // UNUSED
226
227 /* helper function for add_constriant - sets the last target for the active constraint */
228 static void set_constraint_nth_target(bConstraint *con, Object *target, const char subtarget[], int index)
229 {
230         bConstraintTypeInfo *cti = BKE_constraint_get_typeinfo(con);
231         ListBase targets = {NULL, NULL};
232         bConstraintTarget *ct;
233         int num_targets, i;
234         
235         if (cti && cti->get_constraint_targets) {
236                 cti->get_constraint_targets(con, &targets);
237                 num_targets = BLI_countlist(&targets);
238                 
239                 if (index < 0) {
240                         if (abs(index) < num_targets)
241                                 index = num_targets - abs(index);
242                         else
243                                 index = num_targets - 1;
244                 }
245                 else if (index >= num_targets) {
246                         index = num_targets - 1;
247                 }
248                 
249                 for (ct = targets.first, i = 0; ct; ct = ct->next, i++) {
250                         if (i == index) {
251                                 ct->tar = target;
252                                 BLI_strncpy(ct->subtarget, subtarget, sizeof(ct->subtarget));
253                                 break;
254                         }
255                 }
256                 
257                 if (cti->flush_constraint_targets)
258                         cti->flush_constraint_targets(con, &targets, 0);
259         }
260 }
261
262 /* ------------- Constraint Sanity Testing ------------------- */
263
264 /* checks validity of object pointers, and NULLs,
265  * if Bone doesnt exist it sets the CONSTRAINT_DISABLE flag.
266  */
267 static void test_constraints(Object *owner, bPoseChannel *pchan)
268 {
269         bConstraint *curcon;
270         ListBase *conlist = NULL;
271         int type;
272         
273         if (owner == NULL) return;
274         
275         /* Check parents */
276         if (pchan) {
277                 switch (owner->type) {
278                         case OB_ARMATURE:
279                                 type = CONSTRAINT_OBTYPE_BONE;
280                                 break;
281                         default:
282                                 type = CONSTRAINT_OBTYPE_OBJECT;
283                                 break;
284                 }
285         }
286         else
287                 type = CONSTRAINT_OBTYPE_OBJECT;
288         
289         /* Get the constraint list for this object */
290         switch (type) {
291                 case CONSTRAINT_OBTYPE_OBJECT:
292                         conlist = &owner->constraints;
293                         break;
294                 case CONSTRAINT_OBTYPE_BONE:
295                         conlist = &pchan->constraints;
296                         break;
297         }
298         
299         /* Check all constraints - is constraint valid? */
300         if (conlist) {
301                 for (curcon = conlist->first; curcon; curcon = curcon->next) {
302                         bConstraintTypeInfo *cti = BKE_constraint_get_typeinfo(curcon);
303                         ListBase targets = {NULL, NULL};
304                         bConstraintTarget *ct;
305                         
306                         /* clear disabled-flag first */
307                         curcon->flag &= ~CONSTRAINT_DISABLE;
308                         
309                         if (curcon->type == CONSTRAINT_TYPE_KINEMATIC) {
310                                 bKinematicConstraint *data = curcon->data;
311                                 
312                                 /* bad: we need a separate set of checks here as poletarget is 
313                                  *              optional... otherwise poletarget must exist too or else
314                                  *              the constraint is deemed invalid
315                                  */
316                                 /* default IK check ... */
317                                 if (BKE_object_exists_check(data->tar) == 0) {
318                                         data->tar = NULL;
319                                         curcon->flag |= CONSTRAINT_DISABLE;
320                                 }
321                                 else if (data->tar == owner) {
322                                         if (!BKE_armature_find_bone_name(BKE_armature_from_object(owner), data->subtarget)) {
323                                                 curcon->flag |= CONSTRAINT_DISABLE;
324                                         }
325                                 }
326                                 
327                                 if (data->poletar) {
328                                         if (BKE_object_exists_check(data->poletar) == 0) {
329                                                 data->poletar = NULL;
330                                                 curcon->flag |= CONSTRAINT_DISABLE;
331                                         }
332                                         else if (data->poletar == owner) {
333                                                 if (!BKE_armature_find_bone_name(BKE_armature_from_object(owner), data->polesubtarget)) {
334                                                         curcon->flag |= CONSTRAINT_DISABLE;
335                                                 }
336                                         }
337                                 }
338                                 /* ... can be overwritten here */
339                                 BIK_test_constraint(owner, curcon);
340                                 /* targets have already been checked for this */
341                                 continue;
342                         }
343                         else if (curcon->type == CONSTRAINT_TYPE_PIVOT) {
344                                 bPivotConstraint *data = curcon->data;
345                                 
346                                 /* target doesn't have to exist, but if it is non-null, it must exist! */
347                                 if (data->tar && BKE_object_exists_check(data->tar) == 0) {
348                                         data->tar = NULL;
349                                         curcon->flag |= CONSTRAINT_DISABLE;
350                                 }
351                                 else if (data->tar == owner) {
352                                         if (!BKE_armature_find_bone_name(BKE_armature_from_object(owner), data->subtarget)) {
353                                                 curcon->flag |= CONSTRAINT_DISABLE;
354                                         }
355                                 }
356                                 
357                                 /* targets have already been checked for this */
358                                 continue;
359                         }
360                         else if (curcon->type == CONSTRAINT_TYPE_ACTION) {
361                                 bActionConstraint *data = curcon->data;
362                                 
363                                 /* validate action */
364                                 if (data->act == NULL) {
365                                         /* must have action */
366                                         curcon->flag |= CONSTRAINT_DISABLE;
367                                 }
368                                 else if (data->act->idroot != ID_OB) {
369                                         /* only object-rooted actions can be used */
370                                         data->act = NULL;
371                                         curcon->flag |= CONSTRAINT_DISABLE;
372                                 }
373                         }
374                         else if (curcon->type == CONSTRAINT_TYPE_FOLLOWPATH) {
375                                 bFollowPathConstraint *data = curcon->data;
376                                 
377                                 /* don't allow track/up axes to be the same */
378                                 if (data->upflag == data->trackflag)
379                                         curcon->flag |= CONSTRAINT_DISABLE;
380                                 if (data->upflag + 3 == data->trackflag)
381                                         curcon->flag |= CONSTRAINT_DISABLE;
382                         }
383                         else if (curcon->type == CONSTRAINT_TYPE_TRACKTO) {
384                                 bTrackToConstraint *data = curcon->data;
385                                 
386                                 /* don't allow track/up axes to be the same */
387                                 if (data->reserved2 == data->reserved1)
388                                         curcon->flag |= CONSTRAINT_DISABLE;
389                                 if (data->reserved2 + 3 == data->reserved1)
390                                         curcon->flag |= CONSTRAINT_DISABLE;
391                         }
392                         else if (curcon->type == CONSTRAINT_TYPE_LOCKTRACK) {
393                                 bLockTrackConstraint *data = curcon->data;
394                                 
395                                 if (data->lockflag == data->trackflag)
396                                         curcon->flag |= CONSTRAINT_DISABLE;
397                                 if (data->lockflag + 3 == data->trackflag)
398                                         curcon->flag |= CONSTRAINT_DISABLE;
399                         }
400                         else if (curcon->type == CONSTRAINT_TYPE_SPLINEIK) {
401                                 bSplineIKConstraint *data = curcon->data;
402                                 
403                                 /* if the number of points does not match the amount required by the chain length,
404                                  * free the points array and request a rebind...
405                                  */
406                                 if ((data->points == NULL) || (data->numpoints != data->chainlen + 1)) {
407                                         /* free the points array */
408                                         if (data->points) {
409                                                 MEM_freeN(data->points);
410                                                 data->points = NULL;
411                                         }
412                                         
413                                         /* clear the bound flag, forcing a rebind next time this is evaluated */
414                                         data->flag &= ~CONSTRAINT_SPLINEIK_BOUND;
415                                 }
416                         }
417                         else if (curcon->type == CONSTRAINT_TYPE_FOLLOWTRACK) {
418                                 bFollowTrackConstraint *data = curcon->data;
419
420                                 if ((data->flag & CAMERASOLVER_ACTIVECLIP) == 0) {
421                                         if (data->clip != NULL && data->track[0]) {
422                                                 MovieTracking *tracking = &data->clip->tracking;
423                                                 MovieTrackingObject *tracking_object;
424                                                 
425                                                 if (data->object[0])
426                                                         tracking_object = BKE_tracking_object_get_named(tracking, data->object);
427                                                 else
428                                                         tracking_object = BKE_tracking_object_get_camera(tracking);
429                                                 
430                                                 if (!tracking_object) {
431                                                         curcon->flag |= CONSTRAINT_DISABLE;
432                                                 }
433                                                 else {
434                                                         if (!BKE_tracking_track_get_named(tracking, tracking_object, data->track))
435                                                                 curcon->flag |= CONSTRAINT_DISABLE;
436                                                 }
437                                         }
438                                         else {
439                                                 curcon->flag |= CONSTRAINT_DISABLE;
440                                         }
441                                 }
442                         }
443                         else if (curcon->type == CONSTRAINT_TYPE_CAMERASOLVER) {
444                                 bCameraSolverConstraint *data = curcon->data;
445                                 
446                                 if ((data->flag & CAMERASOLVER_ACTIVECLIP) == 0 && (data->clip == NULL))
447                                         curcon->flag |= CONSTRAINT_DISABLE;
448                         }
449                         else if (curcon->type == CONSTRAINT_TYPE_OBJECTSOLVER) {
450                                 bObjectSolverConstraint *data = curcon->data;
451                                 
452                                 if ((data->flag & CAMERASOLVER_ACTIVECLIP) == 0 && (data->clip == NULL))
453                                         curcon->flag |= CONSTRAINT_DISABLE;
454                         }
455                         
456                         /* Check targets for constraints */
457                         if (cti && cti->get_constraint_targets) {
458                                 cti->get_constraint_targets(curcon, &targets);
459                                 
460                                 /* disable and clear constraints targets that are incorrect */
461                                 for (ct = targets.first; ct; ct = ct->next) {
462                                         /* general validity checks (for those constraints that need this) */
463                                         if (BKE_object_exists_check(ct->tar) == 0) {
464                                                 /* object doesn't exist, but constraint requires target */
465                                                 ct->tar = NULL;
466                                                 curcon->flag |= CONSTRAINT_DISABLE;
467                                         }
468                                         else if (ct->tar == owner) {
469                                                 if (type == CONSTRAINT_OBTYPE_BONE) {
470                                                         if (!BKE_armature_find_bone_name(BKE_armature_from_object(owner), ct->subtarget)) {
471                                                                 /* bone must exist in armature... */
472                                                                 /* TODO: clear subtarget? */
473                                                                 curcon->flag |= CONSTRAINT_DISABLE;
474                                                         }
475                                                         else if (strcmp(pchan->name, ct->subtarget) == 0) {
476                                                                 /* cannot target self */
477                                                                 ct->subtarget[0] = '\0';
478                                                                 curcon->flag |= CONSTRAINT_DISABLE;
479                                                         }
480                                                 }
481                                                 else {
482                                                         /* cannot use self as target */
483                                                         ct->tar = NULL;
484                                                         curcon->flag |= CONSTRAINT_DISABLE;
485                                                 }
486                                         }
487                                         
488                                         /* target checks for specific constraints */
489                                         if (ELEM3(curcon->type, CONSTRAINT_TYPE_FOLLOWPATH, CONSTRAINT_TYPE_CLAMPTO, CONSTRAINT_TYPE_SPLINEIK)) {
490                                                 if (ct->tar) {
491                                                         if (ct->tar->type != OB_CURVE) {
492                                                                 ct->tar = NULL;
493                                                                 curcon->flag |= CONSTRAINT_DISABLE;
494                                                         }
495                                                         else {
496                                                                 Curve *cu = ct->tar->data;
497                                                                 
498                                                                 /* auto-set 'Path' setting on curve so this works  */
499                                                                 cu->flag |= CU_PATH;
500                                                         }
501                                                 }
502                                         }
503                                 }
504                                 
505                                 /* free any temporary targets */
506                                 if (cti->flush_constraint_targets)
507                                         cti->flush_constraint_targets(curcon, &targets, 0);
508                         }
509                 }
510         }
511 }
512
513 void object_test_constraints(Object *owner)
514 {
515         if (owner->constraints.first)
516                 test_constraints(owner, NULL);
517         
518         if (owner->type == OB_ARMATURE && owner->pose) {
519                 bPoseChannel *pchan;
520                 
521                 for (pchan = owner->pose->chanbase.first; pchan; pchan = pchan->next) {
522                         if (pchan->constraints.first)
523                                 test_constraints(owner, pchan);
524                 }
525         }
526 }
527
528
529 /************************ generic functions for operators using constraint names and data context *********************/
530
531 #define EDIT_CONSTRAINT_OWNER_OBJECT    0
532 #define EDIT_CONSTRAINT_OWNER_BONE      1
533
534 static EnumPropertyItem constraint_owner_items[] = {
535         {EDIT_CONSTRAINT_OWNER_OBJECT, "OBJECT", 0, "Object", "Edit a constraint on the active object"},
536         {EDIT_CONSTRAINT_OWNER_BONE, "BONE", 0, "Bone", "Edit a constraint on the active bone"},
537         {0, NULL, 0, NULL, NULL}};
538
539
540 static int edit_constraint_poll_generic(bContext *C, StructRNA *rna_type)
541 {
542         PointerRNA ptr = CTX_data_pointer_get_type(C, "constraint", rna_type);
543         Object *ob = (ptr.id.data) ? ptr.id.data : ED_object_active_context(C);
544
545         if (!ob || ob->id.lib) return 0;
546         if (ptr.id.data && ((ID *)ptr.id.data)->lib) return 0;
547
548         return 1;
549 }
550
551 static int edit_constraint_poll(bContext *C)
552 {
553         return edit_constraint_poll_generic(C, &RNA_Constraint);
554 }
555
556 static void edit_constraint_properties(wmOperatorType *ot)
557 {
558         RNA_def_string(ot->srna, "constraint", NULL, MAX_NAME, "Constraint", "Name of the constraint to edit");
559         RNA_def_enum(ot->srna, "owner", constraint_owner_items, 0, "Owner", "The owner of this constraint");
560 }
561
562 static int edit_constraint_invoke_properties(bContext *C, wmOperator *op)
563 {
564         PointerRNA ptr = CTX_data_pointer_get_type(C, "constraint", &RNA_Constraint);
565         Object *ob = (ptr.id.data) ? ptr.id.data : ED_object_active_context(C);
566         bConstraint *con;
567         ListBase *list;
568         
569         if (RNA_struct_property_is_set(op->ptr, "constraint") && RNA_struct_property_is_set(op->ptr, "owner"))
570                 return 1;
571         
572         if (ptr.data) {
573                 con = ptr.data;
574                 RNA_string_set(op->ptr, "constraint", con->name);
575                 
576                 list = get_constraint_lb(ob, con, NULL);
577                 
578                 if (&ob->constraints == list)
579                         RNA_enum_set(op->ptr, "owner", EDIT_CONSTRAINT_OWNER_OBJECT);
580                 else
581                         RNA_enum_set(op->ptr, "owner", EDIT_CONSTRAINT_OWNER_BONE);
582                 
583                 return 1;
584         }
585         
586         return 0;
587 }
588
589 static bConstraint *edit_constraint_property_get(wmOperator *op, Object *ob, int type)
590 {
591         char constraint_name[MAX_NAME];
592         int owner = RNA_enum_get(op->ptr, "owner");
593         bConstraint *con;
594         ListBase *list = NULL;
595         
596         RNA_string_get(op->ptr, "constraint", constraint_name);
597         
598         if (owner == EDIT_CONSTRAINT_OWNER_OBJECT) {
599                 list = &ob->constraints;
600         }
601         else if (owner == EDIT_CONSTRAINT_OWNER_BONE) {
602                 bPoseChannel *pchan = BKE_pose_channel_active(ob);
603                 if (pchan)
604                         list = &pchan->constraints;
605                 else {
606                         //if (G.debug & G_DEBUG)
607                         //printf("edit_constraint_property_get: No active bone for object '%s'\n", (ob) ? ob->id.name + 2 : "<None>");
608                         return NULL;
609                 }
610         }
611         else {
612                 //if (G.debug & G_DEBUG)
613                 //printf("edit_constraint_property_get: defaulting to getting list in the standard way\n");
614                 list = get_active_constraints(ob);
615         }
616         
617         con = BKE_constraints_findByName(list, constraint_name);
618         //if (G.debug & G_DEBUG)
619         //printf("constraint found = %p, %s\n", (void *)con, (con) ? con->name : "<Not found>");
620
621         if (con && (type != 0) && (con->type != type))
622                 con = NULL;
623         
624         return con;
625 }
626
627 /* ********************** CONSTRAINT-SPECIFIC STUFF ********************* */
628
629 /* ---------- Distance-Dependent Constraints ---------- */
630 /* StretchTo, Limit Distance */
631
632 static int stretchto_reset_exec(bContext *C, wmOperator *op)
633 {
634         Object *ob = ED_object_active_context(C);
635         bConstraint *con = edit_constraint_property_get(op, ob, CONSTRAINT_TYPE_STRETCHTO);
636         bStretchToConstraint *data = (con) ? (bStretchToConstraint *)con->data : NULL;
637         
638         /* despite 3 layers of checks, we may still not be able to find a constraint */
639         if (data == NULL)
640                 return OPERATOR_CANCELLED;
641         
642         /* just set original length to 0.0, which will cause a reset on next recalc */
643         data->orglength = 0.0f;
644         ED_object_constraint_update(ob);
645         
646         WM_event_add_notifier(C, NC_OBJECT | ND_CONSTRAINT, NULL);
647         return OPERATOR_FINISHED;
648 }
649
650 static int stretchto_reset_invoke(bContext *C, wmOperator *op, const wmEvent *UNUSED(event))
651 {
652         if (edit_constraint_invoke_properties(C, op))
653                 return stretchto_reset_exec(C, op);
654         else
655                 return OPERATOR_CANCELLED;
656 }
657
658 void CONSTRAINT_OT_stretchto_reset(wmOperatorType *ot)
659 {
660         /* identifiers */
661         ot->name = "Reset Original Length";
662         ot->idname = "CONSTRAINT_OT_stretchto_reset";
663         ot->description = "Reset original length of bone for Stretch To Constraint";
664         
665         /* callbacks */
666         ot->invoke = stretchto_reset_invoke;
667         ot->exec = stretchto_reset_exec;
668         ot->poll = edit_constraint_poll;
669         
670         /* flags */
671         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
672         
673         /* properties */
674         edit_constraint_properties(ot);
675 }
676
677
678 static int limitdistance_reset_exec(bContext *C, wmOperator *op)
679 {
680         Object *ob = ED_object_active_context(C);
681         bConstraint *con = edit_constraint_property_get(op, ob, CONSTRAINT_TYPE_DISTLIMIT);
682         bDistLimitConstraint *data = (con) ? (bDistLimitConstraint *)con->data : NULL;
683         
684         /* despite 3 layers of checks, we may still not be able to find a constraint */
685         if (data == NULL)
686                 return OPERATOR_CANCELLED;
687         
688         /* just set original length to 0.0, which will cause a reset on next recalc */
689         data->dist = 0.0f;
690         ED_object_constraint_update(ob);
691         
692         WM_event_add_notifier(C, NC_OBJECT | ND_CONSTRAINT, NULL);
693         return OPERATOR_FINISHED;
694 }
695
696 static int limitdistance_reset_invoke(bContext *C, wmOperator *op, const wmEvent *UNUSED(event))
697 {
698         if (edit_constraint_invoke_properties(C, op))
699                 return limitdistance_reset_exec(C, op);
700         else
701                 return OPERATOR_CANCELLED;
702 }
703
704 void CONSTRAINT_OT_limitdistance_reset(wmOperatorType *ot)
705 {
706         /* identifiers */
707         ot->name = "Reset Distance";
708         ot->idname = "CONSTRAINT_OT_limitdistance_reset";
709         ot->description = "Reset limiting distance for Limit Distance Constraint";
710         
711         /* callbacks */
712         ot->invoke = limitdistance_reset_invoke;
713         ot->exec = limitdistance_reset_exec;
714         ot->poll = edit_constraint_poll;
715         
716         /* flags */
717         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
718         
719         /* properties */
720         edit_constraint_properties(ot);
721 }
722
723 /* ------------- Child-Of Constraint ------------------ */
724
725 static void child_get_inverse_matrix(Scene *scene, Object *ob, bConstraint *con, float invmat[4][4], const int owner)
726 {
727         /* nullify inverse matrix first */
728         unit_m4(invmat);
729         
730         if (owner == EDIT_CONSTRAINT_OWNER_BONE) {
731                 bPoseChannel *pchan;
732                 /* try to find a pose channel - assume that this is the constraint owner */
733                 /* TODO: get from context instead? */
734                 if (ob && ob->pose && (pchan = BKE_pose_channel_active(ob))) {
735                         bConstraint *con_last;
736                         /* calculate/set inverse matrix:
737                          *  We just calculate all transform-stack eval up to but not including this constraint.
738                          *  This is because inverse should just inverse correct for just the constraint's influence
739                          *  when it gets applied; that is, at the time of application, we don't know anything about
740                          *  what follows.
741                          */
742                         float imat[4][4], tmat[4][4];
743                         float pmat[4][4];
744
745                         /* make sure we passed the correct constraint */
746                         BLI_assert(BLI_findindex(&pchan->constraints, con) != -1);
747
748                         /* 1. calculate posemat where inverse doesn't exist yet (inverse was cleared above),
749                          * to use as baseline ("pmat") to derive delta from. This extra calc saves users
750                          * from having pressing "Clear Inverse" first
751                          */
752                         BKE_pose_where_is(scene, ob);
753                         copy_m4_m4(pmat, pchan->pose_mat);
754
755                         /* 2. knock out constraints starting from this one */
756                         con_last = pchan->constraints.last;
757                         pchan->constraints.last = con->prev;
758
759                         if (con->prev) {
760                                 /* new end must not point to this one, else this chain cutting is useless */
761                                 con->prev->next = NULL;
762                         }
763                         else {
764                                 /* constraint was first */
765                                 pchan->constraints.first = NULL;
766                         }
767
768                         /* 3. solve pose without disabled constraints */
769                         BKE_pose_where_is(scene, ob);
770
771                         /* 4. determine effect of constraint by removing the newly calculated
772                          * pchan->pose_mat from the original pchan->pose_mat, thus determining
773                          * the effect of the constraint
774                          */
775                         invert_m4_m4(imat, pchan->pose_mat);
776                         mul_m4_m4m4(tmat, pmat, imat);
777                         invert_m4_m4(invmat, tmat);
778
779                         /* 5. restore constraints */
780                         pchan->constraints.last = con_last;
781
782                         if (con->prev) {
783                                 /* hook up prev to this one again */
784                                 con->prev->next = con;
785                         }
786                         else {
787                                 /* set as first again */
788                                 pchan->constraints.first = con;
789                         }
790
791                         /* 6. recalculate pose with new inv-mat applied */
792                         BKE_pose_where_is(scene, ob);
793                 }
794         }
795         if (owner == EDIT_CONSTRAINT_OWNER_OBJECT) {
796                 if (ob) {
797                         Object workob;
798
799                         /* make sure we passed the correct constraint */
800                         BLI_assert(BLI_findindex(&ob->constraints, con) != -1);
801
802                         /* use BKE_object_workob_calc_parent to find inverse - just like for normal parenting */
803                         BKE_object_workob_calc_parent(scene, ob, &workob);
804                         invert_m4_m4(invmat, workob.obmat);
805                 }
806         }
807 }
808
809 /* ChildOf Constraint - set inverse callback */
810 static int childof_set_inverse_exec(bContext *C, wmOperator *op)
811 {
812         Scene *scene = CTX_data_scene(C);
813         Object *ob = ED_object_active_context(C);
814         bConstraint *con = edit_constraint_property_get(op, ob, CONSTRAINT_TYPE_CHILDOF);
815         bChildOfConstraint *data = (con) ? (bChildOfConstraint *)con->data : NULL;
816         const int owner = RNA_enum_get(op->ptr, "owner");
817
818         /* despite 3 layers of checks, we may still not be able to find a constraint */
819         if (data == NULL) {
820                 printf("DEBUG: Child-Of Set Inverse - object = '%s'\n", (ob) ? ob->id.name + 2 : "<None>");
821                 BKE_report(op->reports, RPT_ERROR, "Could not find constraint data for Child-Of Set Inverse");
822                 return OPERATOR_CANCELLED;
823         }
824         
825         child_get_inverse_matrix(scene, ob, con, data->invmat, owner);
826
827         WM_event_add_notifier(C, NC_OBJECT | ND_CONSTRAINT, ob);
828         
829         return OPERATOR_FINISHED;
830 }
831
832 static int childof_set_inverse_invoke(bContext *C, wmOperator *op, const wmEvent *UNUSED(event))
833 {
834         if (edit_constraint_invoke_properties(C, op))
835                 return childof_set_inverse_exec(C, op);
836         else
837                 return OPERATOR_CANCELLED;
838 }
839
840 void CONSTRAINT_OT_childof_set_inverse(wmOperatorType *ot)
841 {
842         /* identifiers */
843         ot->name = "Set Inverse";
844         ot->idname = "CONSTRAINT_OT_childof_set_inverse";
845         ot->description = "Set inverse correction for ChildOf constraint";
846         
847         /* callbacks */
848         ot->invoke = childof_set_inverse_invoke;
849         ot->exec = childof_set_inverse_exec;
850         ot->poll = edit_constraint_poll;
851         
852         /* flags */
853         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
854         
855         /* properties */
856         edit_constraint_properties(ot);
857 }
858
859 /* ChildOf Constraint - clear inverse callback */
860 static int childof_clear_inverse_exec(bContext *C, wmOperator *op)
861 {
862         Object *ob = ED_object_active_context(C);
863         bConstraint *con = edit_constraint_property_get(op, ob, CONSTRAINT_TYPE_CHILDOF);
864         bChildOfConstraint *data = (con) ? (bChildOfConstraint *)con->data : NULL;
865         
866         if (data == NULL) {
867                 BKE_report(op->reports, RPT_ERROR, "Child Of constraint not found");
868                 return OPERATOR_CANCELLED;
869         }
870         
871         /* simply clear the matrix */
872         unit_m4(data->invmat);
873         
874         WM_event_add_notifier(C, NC_OBJECT | ND_CONSTRAINT, ob);
875         
876         return OPERATOR_FINISHED;
877 }
878
879 static int childof_clear_inverse_invoke(bContext *C, wmOperator *op, const wmEvent *UNUSED(event))
880 {
881         if (edit_constraint_invoke_properties(C, op))
882                 return childof_clear_inverse_exec(C, op);
883         else
884                 return OPERATOR_CANCELLED;
885 }
886
887 void CONSTRAINT_OT_childof_clear_inverse(wmOperatorType *ot)
888 {
889         /* identifiers */
890         ot->name = "Clear Inverse";
891         ot->idname = "CONSTRAINT_OT_childof_clear_inverse";
892         ot->description = "Clear inverse correction for ChildOf constraint";
893         
894         /* callbacks */
895         ot->invoke = childof_clear_inverse_invoke;
896         ot->exec = childof_clear_inverse_exec;
897         ot->poll = edit_constraint_poll;
898         
899         /* flags */
900         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
901         
902         /* properties */
903         edit_constraint_properties(ot);
904 }
905
906 /* --------------- Follow Path Constraint ------------------ */
907
908 static int followpath_path_animate_exec(bContext *C, wmOperator *op)
909 {
910         Object *ob = ED_object_active_context(C);
911         bConstraint *con = edit_constraint_property_get(op, ob, CONSTRAINT_TYPE_FOLLOWPATH);
912         bFollowPathConstraint *data = (con) ? (bFollowPathConstraint *)con->data : NULL;
913         
914         bAction *act = NULL;
915         FCurve *fcu = NULL;
916         int sfra = RNA_int_get(op->ptr, "frame_start");
917         int len  = RNA_int_get(op->ptr, "length");
918         float standardRange = 1.0;
919         
920         /* nearly impossible sanity check */
921         if (data == NULL) {
922                 BKE_report(op->reports, RPT_ERROR, "Follow Path constraint not found");
923                 return OPERATOR_CANCELLED;
924         }
925         
926         /* add F-Curve as appropriate */
927         if (data->tar) {
928                 Curve *cu = (Curve *)data->tar->data;
929                 
930                 if (ELEM(NULL, cu->adt, cu->adt->action) ||
931                     (list_find_fcurve(&cu->adt->action->curves, "eval_time", 0) == NULL))
932                 {
933                         /* create F-Curve for path animation */
934                         act = verify_adt_action(&cu->id, 1);
935                         fcu = verify_fcurve(act, NULL, NULL, "eval_time", 0, 1);
936                         
937                         /* standard vertical range - 1:1 = 100 frames */
938                         standardRange = 100.0f;
939                 }
940                 else {
941                         /* path anim exists already - abort for now as this may well be what was intended */
942                         BKE_report(op->reports, RPT_WARNING, "Path is already animated");
943                         return OPERATOR_CANCELLED;
944                 }
945         }
946         else {
947                 /* animate constraint's "fixed offset" */
948                 PointerRNA ptr;
949                 PropertyRNA *prop;
950                 char *path;
951                 
952                 /* get RNA pointer to constraint's "offset_factor" property - to build RNA path */
953                 RNA_pointer_create(&ob->id, &RNA_FollowPathConstraint, con, &ptr);
954                 prop = RNA_struct_find_property(&ptr, "offset_factor");
955                 
956                 path = RNA_path_from_ID_to_property(&ptr, prop);
957                 
958                 /* create F-Curve for constraint */
959                 act = verify_adt_action(&ob->id, 1);
960                 fcu = verify_fcurve(act, NULL, NULL, path, 0, 1);
961                 
962                 /* standard vertical range - 0.0 to 1.0 */
963                 standardRange = 1.0f;
964                 
965                 /* enable "Use Fixed Position" so that animating this has effect */
966                 data->followflag |= FOLLOWPATH_STATIC;
967                 
968                 /* path needs to be freed */
969                 if (path) 
970                         MEM_freeN(path);
971         }
972         
973         /* setup dummy 'generator' modifier here to get 1-1 correspondence still working
974          * and define basic slope of this curve based on the properties
975          */
976         if (!fcu->bezt && !fcu->fpt && !fcu->modifiers.first) {
977                 FModifier *fcm = add_fmodifier(&fcu->modifiers, FMODIFIER_TYPE_GENERATOR);
978                 FMod_Generator *gen = fcm->data;
979                 
980                 /* Assume that we have the following equation:
981                  *     y = Ax + B
982                  *         1    0       <-- coefficients array indices
983                  */
984                 float A = standardRange / (float)(len);
985                 float B = (float)(-sfra) * A;
986                 
987                 gen->coefficients[1] = A;
988                 gen->coefficients[0] = B;
989         }
990         
991         /* updates... */
992         WM_event_add_notifier(C, NC_OBJECT | ND_CONSTRAINT, ob);
993         return OPERATOR_FINISHED;
994 }
995
996 static int followpath_path_animate_invoke(bContext *C, wmOperator *op, const wmEvent *UNUSED(event))
997 {
998         /* hook up invoke properties for figuring out which constraint we're dealing with */
999         if (edit_constraint_invoke_properties(C, op)) {
1000                 return followpath_path_animate_exec(C, op);
1001         }
1002         else {
1003                 return OPERATOR_CANCELLED;
1004         }
1005 }
1006
1007 void CONSTRAINT_OT_followpath_path_animate(wmOperatorType *ot)
1008 {
1009         /* identifiers */
1010         ot->name = "Auto Animate Path";
1011         ot->idname = "CONSTRAINT_OT_followpath_path_animate";
1012         ot->description = "Add default animation for path used by constraint if it isn't animated already";
1013         
1014         /* callbacks */
1015         ot->invoke = followpath_path_animate_invoke;
1016         ot->exec = followpath_path_animate_exec;
1017         ot->poll = edit_constraint_poll;
1018         
1019         /* flags */
1020         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1021         
1022         /* props */
1023         edit_constraint_properties(ot);
1024         RNA_def_int(ot->srna, "frame_start", 1, MINAFRAME, MAXFRAME, "Start Frame", 
1025                     "First frame of path animation", MINAFRAME, MAXFRAME);
1026         RNA_def_int(ot->srna, "length", 100, 0, MAXFRAME, "Length", 
1027                     "Number of frames that path animation should take", 0, MAXFRAME);
1028 }
1029
1030 /* ------------- Object Solver Constraint ------------------ */
1031
1032 static int objectsolver_set_inverse_exec(bContext *C, wmOperator *op)
1033 {
1034         Scene *scene = CTX_data_scene(C);
1035         Object *ob = ED_object_active_context(C);
1036         bConstraint *con = edit_constraint_property_get(op, ob, CONSTRAINT_TYPE_OBJECTSOLVER);
1037         bObjectSolverConstraint *data = (con) ? (bObjectSolverConstraint *)con->data : NULL;
1038         const int owner = RNA_enum_get(op->ptr, "owner");
1039
1040         /* despite 3 layers of checks, we may still not be able to find a constraint */
1041         if (data == NULL) {
1042                 printf("DEBUG: Child-Of Set Inverse - object = '%s'\n", (ob) ? ob->id.name + 2 : "<None>");
1043                 BKE_report(op->reports, RPT_ERROR, "Could not find constraint data for Child-Of Set Inverse");
1044                 return OPERATOR_CANCELLED;
1045         }
1046
1047         child_get_inverse_matrix(scene, ob, con, data->invmat, owner);
1048
1049         WM_event_add_notifier(C, NC_OBJECT | ND_CONSTRAINT, ob);
1050
1051         return OPERATOR_FINISHED;
1052 }
1053
1054 static int objectsolver_set_inverse_invoke(bContext *C, wmOperator *op, const wmEvent *UNUSED(event))
1055 {
1056         if (edit_constraint_invoke_properties(C, op))
1057                 return objectsolver_set_inverse_exec(C, op);
1058         else
1059                 return OPERATOR_CANCELLED;
1060 }
1061
1062 void CONSTRAINT_OT_objectsolver_set_inverse(wmOperatorType *ot)
1063 {
1064         /* identifiers */
1065         ot->name = "Set Inverse";
1066         ot->idname = "CONSTRAINT_OT_objectsolver_set_inverse";
1067         ot->description = "Set inverse correction for ObjectSolver constraint";
1068         
1069         /* callbacks */
1070         ot->invoke = objectsolver_set_inverse_invoke;
1071         ot->exec = objectsolver_set_inverse_exec;
1072         ot->poll = edit_constraint_poll;
1073
1074         /* flags */
1075         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1076         
1077         /* properties */
1078         edit_constraint_properties(ot);
1079 }
1080
1081 static int objectsolver_clear_inverse_exec(bContext *C, wmOperator *op)
1082 {
1083         Object *ob = ED_object_active_context(C);
1084         bConstraint *con = edit_constraint_property_get(op, ob, CONSTRAINT_TYPE_OBJECTSOLVER);
1085         bObjectSolverConstraint *data = (con) ? (bObjectSolverConstraint *)con->data : NULL;
1086
1087         if (data == NULL) {
1088                 BKE_report(op->reports, RPT_ERROR, "Child Of constraint not found");
1089                 return OPERATOR_CANCELLED;
1090         }
1091
1092         /* simply clear the matrix */
1093         unit_m4(data->invmat);
1094
1095         WM_event_add_notifier(C, NC_OBJECT | ND_CONSTRAINT, ob);
1096
1097         return OPERATOR_FINISHED;
1098 }
1099
1100 static int objectsolver_clear_inverse_invoke(bContext *C, wmOperator *op, const wmEvent *UNUSED(event))
1101 {
1102         if (edit_constraint_invoke_properties(C, op))
1103                 return objectsolver_clear_inverse_exec(C, op);
1104         else
1105                 return OPERATOR_CANCELLED;
1106 }
1107
1108 void CONSTRAINT_OT_objectsolver_clear_inverse(wmOperatorType *ot)
1109 {
1110         /* identifiers */
1111         ot->name = "Clear Inverse";
1112         ot->idname = "CONSTRAINT_OT_objectsolver_clear_inverse";
1113         ot->description = "Clear inverse correction for ObjectSolver constraint";
1114         
1115         /* callbacks */
1116         ot->invoke = objectsolver_clear_inverse_invoke;
1117         ot->exec = objectsolver_clear_inverse_exec;
1118         ot->poll = edit_constraint_poll;
1119
1120         /* flags */
1121         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1122         
1123         /* properties */
1124         edit_constraint_properties(ot);
1125 }
1126
1127 /***************************** BUTTONS ****************************/
1128
1129 void ED_object_constraint_set_active(Object *ob, bConstraint *con)
1130 {       
1131         ListBase *lb = get_constraint_lb(ob, con, NULL);
1132         
1133         /* lets be nice and escape if its active already */
1134         /* NOTE: this assumes that the stack doesn't have other active ones set... */
1135         if ((lb && con) && (con->flag & CONSTRAINT_ACTIVE))
1136                 return;
1137         
1138         BKE_constraints_set_active(lb, con);
1139 }
1140
1141 void ED_object_constraint_update(Object *ob)
1142 {
1143         if (ob->pose) BKE_pose_update_constraint_flags(ob->pose);
1144
1145         object_test_constraints(ob);
1146
1147         if (ob->type == OB_ARMATURE) 
1148                 DAG_id_tag_update(&ob->id, OB_RECALC_DATA | OB_RECALC_OB);
1149         else 
1150                 DAG_id_tag_update(&ob->id, OB_RECALC_OB);
1151 }
1152
1153 void ED_object_constraint_dependency_update(Main *bmain, Object *ob)
1154 {
1155         ED_object_constraint_update(ob);
1156
1157         if (ob->pose) ob->pose->flag |= POSE_RECALC;    // checks & sorts pose channels
1158         DAG_relations_tag_update(bmain);
1159 }
1160
1161 static int constraint_poll(bContext *C)
1162 {
1163         PointerRNA ptr = CTX_data_pointer_get_type(C, "constraint", &RNA_Constraint);
1164         return (ptr.id.data && ptr.data);
1165 }
1166
1167
1168 static int constraint_delete_exec(bContext *C, wmOperator *UNUSED(op))
1169 {
1170         PointerRNA ptr = CTX_data_pointer_get_type(C, "constraint", &RNA_Constraint);
1171         Object *ob = ptr.id.data;
1172         bConstraint *con = ptr.data;
1173         ListBase *lb = get_constraint_lb(ob, con, NULL);
1174         const bool is_ik = ELEM(con->type, CONSTRAINT_TYPE_KINEMATIC, CONSTRAINT_TYPE_SPLINEIK);
1175
1176         /* free the constraint */
1177         if (BKE_remove_constraint(lb, con)) {
1178                 /* there's no active constraint now, so make sure this is the case */
1179                 BKE_constraints_set_active(lb, NULL);
1180                 
1181                 ED_object_constraint_update(ob); /* needed to set the flags on posebones correctly */
1182                 
1183                 /* ITASC needs to be rebuilt once a constraint is removed [#26920] */
1184                 if (is_ik) {
1185                         BIK_clear_data(ob->pose);
1186                 }
1187                 
1188                 /* notifiers */
1189                 WM_event_add_notifier(C, NC_OBJECT | ND_CONSTRAINT | NA_REMOVED, ob);
1190                 
1191                 return OPERATOR_FINISHED;
1192         }
1193         else {
1194                 /* couldn't remove due to some invalid data */
1195                 return OPERATOR_CANCELLED;
1196         }
1197 }
1198
1199 void CONSTRAINT_OT_delete(wmOperatorType *ot)
1200 {
1201         /* identifiers */
1202         ot->name = "Delete Constraint";
1203         ot->idname = "CONSTRAINT_OT_delete";
1204         ot->description = "Remove constraint from constraint stack";
1205         
1206         /* callbacks */
1207         ot->exec = constraint_delete_exec;
1208         ot->poll = constraint_poll;
1209         
1210         /* flags */
1211         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1212 }
1213
1214
1215 static int constraint_move_down_exec(bContext *C, wmOperator *op)
1216 {
1217         Object *ob = ED_object_active_context(C);
1218         bConstraint *con = edit_constraint_property_get(op, ob, 0);
1219         
1220         if (con && con->next) {
1221                 ListBase *conlist = get_constraint_lb(ob, con, NULL);
1222                 bConstraint *nextCon = con->next;
1223                 
1224                 /* insert the nominated constraint after the one that used to be after it */
1225                 BLI_remlink(conlist, con);
1226                 BLI_insertlinkafter(conlist, nextCon, con);
1227                 
1228                 WM_event_add_notifier(C, NC_OBJECT | ND_CONSTRAINT, ob);
1229                 
1230                 return OPERATOR_FINISHED;
1231         }
1232         
1233         return OPERATOR_CANCELLED;
1234 }
1235
1236 static int constraint_move_down_invoke(bContext *C, wmOperator *op, const wmEvent *UNUSED(event))
1237 {
1238         if (edit_constraint_invoke_properties(C, op))
1239                 return constraint_move_down_exec(C, op);
1240         else
1241                 return OPERATOR_CANCELLED;
1242 }
1243
1244 void CONSTRAINT_OT_move_down(wmOperatorType *ot)
1245 {
1246         /* identifiers */
1247         ot->name = "Move Constraint Down";
1248         ot->idname = "CONSTRAINT_OT_move_down";
1249         ot->description = "Move constraint down in constraint stack";
1250         
1251         /* callbacks */
1252         ot->invoke = constraint_move_down_invoke;
1253         ot->exec = constraint_move_down_exec;
1254         ot->poll = edit_constraint_poll;
1255         
1256         /* flags */
1257         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1258         
1259         /* properties */
1260         edit_constraint_properties(ot);
1261 }
1262
1263
1264 static int constraint_move_up_exec(bContext *C, wmOperator *op)
1265 {
1266         Object *ob = ED_object_active_context(C);
1267         bConstraint *con = edit_constraint_property_get(op, ob, 0);
1268         
1269         if (con && con->prev) {
1270                 ListBase *conlist = get_constraint_lb(ob, con, NULL);
1271                 bConstraint *prevCon = con->prev;
1272                 
1273                 /* insert the nominated constraint before the one that used to be before it */
1274                 BLI_remlink(conlist, con);
1275                 BLI_insertlinkbefore(conlist, prevCon, con);
1276                 
1277                 WM_event_add_notifier(C, NC_OBJECT | ND_CONSTRAINT, ob);
1278                 
1279                 return OPERATOR_FINISHED;
1280         }
1281         
1282         return OPERATOR_CANCELLED;
1283 }
1284
1285 static int constraint_move_up_invoke(bContext *C, wmOperator *op, const wmEvent *UNUSED(event))
1286 {
1287         if (edit_constraint_invoke_properties(C, op))
1288                 return constraint_move_up_exec(C, op);
1289         else
1290                 return OPERATOR_CANCELLED;
1291 }
1292
1293 void CONSTRAINT_OT_move_up(wmOperatorType *ot)
1294 {
1295         /* identifiers */
1296         ot->name = "Move Constraint Up";
1297         ot->idname = "CONSTRAINT_OT_move_up";
1298         ot->description = "Move constraint up in constraint stack";
1299         
1300         /* callbacks */
1301         ot->exec = constraint_move_up_exec;
1302         ot->invoke = constraint_move_up_invoke;
1303         ot->poll = edit_constraint_poll;
1304         
1305         /* flags */
1306         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1307         edit_constraint_properties(ot);
1308 }
1309
1310 /***************************** OPERATORS ****************************/
1311
1312 /************************ remove constraint operators *********************/
1313
1314 static int pose_constraints_clear_exec(bContext *C, wmOperator *UNUSED(op))
1315 {
1316         Main *bmain = CTX_data_main(C);
1317         Object *ob = BKE_object_pose_armature_get(CTX_data_active_object(C));
1318         
1319         /* free constraints for all selected bones */
1320         CTX_DATA_BEGIN (C, bPoseChannel *, pchan, selected_pose_bones)
1321         {
1322                 BKE_free_constraints(&pchan->constraints);
1323                 pchan->constflag &= ~(PCHAN_HAS_IK | PCHAN_HAS_SPLINEIK | PCHAN_HAS_CONST);
1324         }
1325         CTX_DATA_END;
1326         
1327         /* force depsgraph to get recalculated since relationships removed */
1328         DAG_relations_tag_update(bmain);
1329         
1330         /* note, calling BIK_clear_data() isn't needed here */
1331
1332         /* do updates */
1333         DAG_id_tag_update(&ob->id, OB_RECALC_DATA);
1334         WM_event_add_notifier(C, NC_OBJECT | ND_CONSTRAINT | NA_REMOVED, ob);
1335         
1336         return OPERATOR_FINISHED;
1337 }
1338
1339 void POSE_OT_constraints_clear(wmOperatorType *ot)
1340 {
1341         /* identifiers */
1342         ot->name = "Clear Pose Constraints";
1343         ot->idname = "POSE_OT_constraints_clear";
1344         ot->description = "Clear all the constraints for the selected bones";
1345         
1346         /* callbacks */
1347         ot->exec = pose_constraints_clear_exec;
1348         ot->poll = ED_operator_posemode_exclusive; // XXX - do we want to ensure there are selected bones too?
1349 }
1350
1351
1352 static int object_constraints_clear_exec(bContext *C, wmOperator *UNUSED(op))
1353 {
1354         Main *bmain = CTX_data_main(C);
1355         
1356         /* do freeing */
1357         CTX_DATA_BEGIN (C, Object *, ob, selected_editable_objects)
1358         {
1359                 BKE_free_constraints(&ob->constraints);
1360                 DAG_id_tag_update(&ob->id, OB_RECALC_OB);
1361         }
1362         CTX_DATA_END;
1363         
1364         /* force depsgraph to get recalculated since relationships removed */
1365         DAG_relations_tag_update(bmain);
1366         
1367         /* do updates */
1368         WM_event_add_notifier(C, NC_OBJECT | ND_CONSTRAINT | NA_REMOVED, NULL);
1369         
1370         return OPERATOR_FINISHED;
1371 }
1372
1373 void OBJECT_OT_constraints_clear(wmOperatorType *ot)
1374 {
1375         /* identifiers */
1376         ot->name = "Clear Object Constraints";
1377         ot->idname = "OBJECT_OT_constraints_clear";
1378         ot->description = "Clear all the constraints for the active Object only";
1379         
1380         /* callbacks */
1381         ot->exec = object_constraints_clear_exec;
1382         ot->poll = ED_operator_object_active_editable;
1383 }
1384
1385 /************************ copy all constraints operators *********************/
1386
1387 static int pose_constraint_copy_exec(bContext *C, wmOperator *op)
1388 {
1389         Main *bmain = CTX_data_main(C);
1390         bPoseChannel *pchan = CTX_data_active_pose_bone(C);
1391         
1392         /* don't do anything if bone doesn't exist or doesn't have any constraints */
1393         if (ELEM(NULL, pchan, pchan->constraints.first)) {
1394                 BKE_report(op->reports, RPT_ERROR, "No active bone with constraints for copying");
1395                 return OPERATOR_CANCELLED;
1396         }
1397         
1398         /* copy all constraints from active posebone to all selected posebones */
1399         CTX_DATA_BEGIN (C, bPoseChannel *, chan, selected_pose_bones)
1400         {
1401                 /* if we're not handling the object we're copying from, copy all constraints over */
1402                 if (pchan != chan) {
1403                         BKE_copy_constraints(&chan->constraints, &pchan->constraints, TRUE);
1404                         /* update flags (need to add here, not just copy) */
1405                         chan->constflag |= pchan->constflag;
1406                 }
1407         }
1408         CTX_DATA_END;
1409         
1410         /* force depsgraph to get recalculated since new relationships added */
1411         DAG_relations_tag_update(bmain);
1412
1413         WM_event_add_notifier(C, NC_OBJECT | ND_CONSTRAINT, NULL);
1414         
1415         return OPERATOR_FINISHED;
1416 }
1417
1418 void POSE_OT_constraints_copy(wmOperatorType *ot)
1419 {
1420         /* identifiers */
1421         ot->name = "Copy Constraints to Selected Bones";
1422         ot->idname = "POSE_OT_constraints_copy";
1423         ot->description = "Copy constraints to other selected bones";
1424         
1425         /* api callbacks */
1426         ot->exec = pose_constraint_copy_exec;
1427         ot->poll = ED_operator_posemode_exclusive;
1428
1429         /* flags */
1430         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1431 }
1432
1433 static int object_constraint_copy_exec(bContext *C, wmOperator *UNUSED(op))
1434 {
1435         Main *bmain = CTX_data_main(C);
1436         Object *obact = ED_object_active_context(C);
1437         
1438         /* copy all constraints from active object to all selected objects */
1439         CTX_DATA_BEGIN (C, Object *, ob, selected_editable_objects)
1440         {
1441                 /* if we're not handling the object we're copying from, copy all constraints over */
1442                 if (obact != ob) {
1443                         BKE_copy_constraints(&ob->constraints, &obact->constraints, TRUE);
1444                         DAG_id_tag_update(&ob->id, OB_RECALC_DATA);
1445                 }
1446         }
1447         CTX_DATA_END;
1448         
1449         /* force depsgraph to get recalculated since new relationships added */
1450         DAG_relations_tag_update(bmain);
1451         
1452         /* notifiers for updates */
1453         WM_event_add_notifier(C, NC_OBJECT | ND_CONSTRAINT | NA_ADDED, NULL);
1454         
1455         return OPERATOR_FINISHED;
1456 }
1457
1458 void OBJECT_OT_constraints_copy(wmOperatorType *ot)
1459 {
1460         /* identifiers */
1461         ot->name = "Copy Constraints to Selected Objects";
1462         ot->idname = "OBJECT_OT_constraints_copy";
1463         ot->description = "Copy constraints to other selected objects";
1464         
1465         /* api callbacks */
1466         ot->exec = object_constraint_copy_exec;
1467         ot->poll = ED_operator_object_active_editable;
1468
1469         /* flags */
1470         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1471 }
1472
1473 /************************ add constraint operators *********************/
1474
1475 /* get the Object and/or PoseChannel to use as target */
1476 static short get_new_constraint_target(bContext *C, int con_type, Object **tar_ob, bPoseChannel **tar_pchan, short add)
1477 {
1478         Object *obact = ED_object_active_context(C);
1479         bPoseChannel *pchanact = BKE_pose_channel_active(obact);
1480         short only_curve = 0, only_mesh = 0, only_ob = 0;
1481         short found = 0;
1482         
1483         /* clear tar_ob and tar_pchan fields before use 
1484          *      - assume for now that both always exist...
1485          */
1486         *tar_ob = NULL;
1487         *tar_pchan = NULL;
1488         
1489         /* check if constraint type doesn't requires a target
1490          *      - if so, no need to get any targets 
1491          */
1492         switch (con_type) {
1493                 /* no-target constraints --------------------------- */
1494                 /* null constraint - shouldn't even be added! */
1495                 case CONSTRAINT_TYPE_NULL:
1496                 /* limit constraints - no targets needed */
1497                 case CONSTRAINT_TYPE_LOCLIMIT:
1498                 case CONSTRAINT_TYPE_ROTLIMIT:
1499                 case CONSTRAINT_TYPE_SIZELIMIT:
1500                 case CONSTRAINT_TYPE_SAMEVOL:
1501                         return 0;
1502                         
1503                 /* restricted target-type constraints -------------- */
1504                 /* NOTE: for these, we cannot try to add a target object if no valid ones are found, since that doesn't work */
1505                 /* curve-based constraints - set the only_curve and only_ob flags */
1506                 case CONSTRAINT_TYPE_CLAMPTO:
1507                 case CONSTRAINT_TYPE_FOLLOWPATH:
1508                 case CONSTRAINT_TYPE_SPLINEIK:
1509                         only_curve = 1;
1510                         only_ob = 1;
1511                         add = 0;
1512                         break;
1513                         
1514                 /* mesh only? */
1515                 case CONSTRAINT_TYPE_SHRINKWRAP:
1516                         only_mesh = 1;
1517                         only_ob = 1;
1518                         add = 0;
1519                         break;
1520                         
1521                 /* object only - add here is ok? */
1522                 case CONSTRAINT_TYPE_RIGIDBODYJOINT:
1523                         only_ob = 1;
1524                         break;
1525         }
1526         
1527         /* if the active Object is Armature, and we can search for bones, do so... */
1528         if ((obact->type == OB_ARMATURE) && (only_ob == 0)) {
1529                 /* search in list of selected Pose-Channels for target */
1530                 CTX_DATA_BEGIN (C, bPoseChannel *, pchan, selected_pose_bones)
1531                 {
1532                         /* just use the first one that we encounter, as long as it is not the active one */
1533                         if (pchan != pchanact) {
1534                                 *tar_ob = obact;
1535                                 *tar_pchan = pchan;
1536                                 found = 1;
1537                                 
1538                                 break;
1539                         }
1540                 }
1541                 CTX_DATA_END;
1542         }
1543         
1544         /* if not yet found, try selected Objects... */
1545         if (found == 0) {
1546                 /* search in selected objects context */
1547                 CTX_DATA_BEGIN (C, Object *, ob, selected_objects)
1548                 {
1549                         /* just use the first object we encounter (that isn't the active object) 
1550                          * and which fulfills the criteria for the object-target that we've got 
1551                          */
1552                         if ((ob != obact) &&
1553                             ((!only_curve) || (ob->type == OB_CURVE)) &&
1554                             ((!only_mesh) || (ob->type == OB_MESH)))
1555                         {
1556                                 /* set target */
1557                                 *tar_ob = ob;
1558                                 found = 1;
1559                                 
1560                                 /* perform some special operations on the target */
1561                                 if (only_curve) {
1562                                         /* Curve-Path option must be enabled for follow-path constraints to be able to work */
1563                                         Curve *cu = (Curve *)ob->data;
1564                                         cu->flag |= CU_PATH;
1565                                 }
1566                                 
1567                                 break;
1568                         }
1569                 }
1570                 CTX_DATA_END;
1571         }
1572         
1573         /* if still not found, add a new empty to act as a target (if allowed) */
1574         if ((found == 0) && (add)) {
1575                 Main *bmain = CTX_data_main(C);
1576                 Scene *scene = CTX_data_scene(C);
1577                 Base *base = BASACT, *newbase = NULL;
1578                 Object *obt;
1579                 
1580                 /* add new target object */
1581                 obt = BKE_object_add(bmain, scene, OB_EMPTY);
1582                 
1583                 /* set layers OK */
1584                 newbase = BASACT;
1585                 newbase->lay = base->lay;
1586                 obt->lay = newbase->lay;
1587                 
1588                 /* transform cent to global coords for loc */
1589                 if (pchanact) {
1590                         /* since by default, IK targets the tip of the last bone, use the tip of the active PoseChannel 
1591                          * if adding a target for an IK Constraint
1592                          */
1593                         if (con_type == CONSTRAINT_TYPE_KINEMATIC)
1594                                 mul_v3_m4v3(obt->loc, obact->obmat, pchanact->pose_tail);
1595                         else
1596                                 mul_v3_m4v3(obt->loc, obact->obmat, pchanact->pose_head);
1597                 }
1598                 else {
1599                         copy_v3_v3(obt->loc, obact->obmat[3]);
1600                 }
1601
1602                 /* restore, BKE_object_add sets active */
1603                 BASACT = base;
1604                 base->flag |= SELECT;
1605                 
1606                 /* make our new target the new object */
1607                 *tar_ob = obt;
1608                 found = 1;
1609         }
1610         
1611         /* return whether there's any target */
1612         return found;
1613 }
1614
1615 /* used by add constraint operators to add the constraint required */
1616 static int constraint_add_exec(bContext *C, wmOperator *op, Object *ob, ListBase *list, int type, const bool setTarget)
1617 {
1618         Main *bmain = CTX_data_main(C);
1619         bPoseChannel *pchan;
1620         bConstraint *con;
1621         
1622         if (list == &ob->constraints) {
1623                 pchan = NULL;
1624         }
1625         else {
1626                 pchan = BKE_pose_channel_active(ob);
1627                 
1628                 /* ensure not to confuse object/pose adding */
1629                 if (pchan == NULL) {
1630                         BKE_report(op->reports, RPT_ERROR, "No active pose bone to add a constraint to");
1631                         return OPERATOR_CANCELLED;
1632                 }
1633         }
1634         /* check if constraint to be added is valid for the given constraints stack */
1635         if (type == CONSTRAINT_TYPE_NULL) {
1636                 return OPERATOR_CANCELLED;
1637         }
1638         if ((type == CONSTRAINT_TYPE_RIGIDBODYJOINT) && (list != &ob->constraints)) {
1639                 BKE_report(op->reports, RPT_ERROR, "Rigid Body Joint constraint can only be added to objects");
1640                 return OPERATOR_CANCELLED;
1641         }
1642         if ((type == CONSTRAINT_TYPE_KINEMATIC) && ((!pchan) || (list != &pchan->constraints))) {
1643                 BKE_report(op->reports, RPT_ERROR, "IK constraint can only be added to bones");
1644                 return OPERATOR_CANCELLED;
1645         }
1646         if ((type == CONSTRAINT_TYPE_SPLINEIK) && ((!pchan) || (list != &pchan->constraints))) {
1647                 BKE_report(op->reports, RPT_ERROR, "Spline IK constraint can only be added to bones");
1648                 return OPERATOR_CANCELLED;
1649         }
1650         
1651         /* create a new constraint of the type requried, and add it to the active/given constraints list */
1652         if (pchan)
1653                 con = BKE_add_pose_constraint(ob, pchan, NULL, type);
1654         else
1655                 con = BKE_add_ob_constraint(ob, NULL, type);
1656         
1657         /* get the first selected object/bone, and make that the target
1658          *      - apart from the buttons-window add buttons, we shouldn't add in this way
1659          */
1660         if (setTarget) {
1661                 Object *tar_ob = NULL;
1662                 bPoseChannel *tar_pchan = NULL;
1663                 
1664                 /* get the target objects, adding them as need be */
1665                 if (get_new_constraint_target(C, type, &tar_ob, &tar_pchan, 1)) {
1666                         /* method of setting target depends on the type of target we've got 
1667                          *      - by default, just set the first target (distinction here is only for multiple-targeted constraints)
1668                          */
1669                         if (tar_pchan)
1670                                 set_constraint_nth_target(con, tar_ob, tar_pchan->name, 0);
1671                         else
1672                                 set_constraint_nth_target(con, tar_ob, "", 0);
1673                 }
1674         }
1675         
1676         /* do type-specific tweaking to the constraint settings  */
1677         switch (type) {
1678                 case CONSTRAINT_TYPE_PYTHON: /* FIXME: this code is not really valid anymore */
1679                 {
1680 #ifdef WITH_PYTHON
1681                         char *menustr;
1682                         int scriptint = 0;
1683                         /* popup a list of usable scripts */
1684                         menustr = buildmenu_pyconstraints(NULL, &scriptint);
1685                         /* XXX scriptint = pupmenu(menustr); */
1686                         MEM_freeN(menustr);
1687
1688                         /* only add constraint if a script was chosen */
1689                         if (scriptint) {
1690                                 /* add constraint */
1691                                 validate_pyconstraint_cb(con->data, &scriptint);
1692                                 
1693                                 /* make sure target allowance is set correctly */
1694                                 BPY_pyconstraint_update(ob, con);
1695                         }
1696 #endif
1697                         break;
1698                 }
1699
1700                 default:
1701                         break;
1702         }
1703         
1704         /* make sure all settings are valid - similar to above checks, but sometimes can be wrong */
1705         object_test_constraints(ob);
1706
1707         if (pchan)
1708                 BKE_pose_update_constraint_flags(ob->pose);
1709
1710
1711         /* force depsgraph to get recalculated since new relationships added */
1712         DAG_relations_tag_update(bmain);
1713         
1714         if ((ob->type == OB_ARMATURE) && (pchan)) {
1715                 ob->pose->flag |= POSE_RECALC;  /* sort pose channels */
1716                 DAG_id_tag_update(&ob->id, OB_RECALC_DATA | OB_RECALC_OB);
1717         }
1718         else
1719                 DAG_id_tag_update(&ob->id, OB_RECALC_OB);
1720         
1721         /* notifiers for updates */
1722         WM_event_add_notifier(C, NC_OBJECT | ND_CONSTRAINT | NA_ADDED, ob);
1723         
1724         return OPERATOR_FINISHED;
1725 }
1726
1727 /* ------------------ */
1728
1729 /* dummy operator callback */
1730 static int object_constraint_add_exec(bContext *C, wmOperator *op)
1731 {
1732         Object *ob = ED_object_active_context(C);
1733         int type = RNA_enum_get(op->ptr, "type");
1734         short with_targets = 0;
1735         
1736         if (!ob) {
1737                 BKE_report(op->reports, RPT_ERROR, "No active object to add constraint to");
1738                 return OPERATOR_CANCELLED;
1739         }
1740                 
1741         /* hack: set constraint targets from selected objects in context is allowed when
1742          *              operator name included 'with_targets', since the menu doesn't allow multiple properties
1743          */
1744         if (strstr(op->idname, "with_targets"))
1745                 with_targets = 1;
1746
1747         return constraint_add_exec(C, op, ob, &ob->constraints, type, with_targets);
1748 }
1749
1750 /* dummy operator callback */
1751 static int pose_constraint_add_exec(bContext *C, wmOperator *op)
1752 {
1753         Object *ob = BKE_object_pose_armature_get(ED_object_active_context(C));
1754         int type = RNA_enum_get(op->ptr, "type");
1755         short with_targets = 0;
1756         
1757         if (!ob) {
1758                 BKE_report(op->reports, RPT_ERROR, "No active object to add constraint to");
1759                 return OPERATOR_CANCELLED;
1760         }
1761                 
1762         /* hack: set constraint targets from selected objects in context is allowed when
1763          *              operator name included 'with_targets', since the menu doesn't allow multiple properties
1764          */
1765         if (strstr(op->idname, "with_targets"))
1766                 with_targets = 1;
1767         
1768         return constraint_add_exec(C, op, ob, get_active_constraints(ob), type, with_targets);
1769 }
1770
1771 /* ------------------ */
1772
1773 void OBJECT_OT_constraint_add(wmOperatorType *ot)
1774 {
1775         /* identifiers */
1776         ot->name = "Add Constraint";
1777         ot->description = "Add a constraint to the active object";
1778         ot->idname = "OBJECT_OT_constraint_add";
1779         
1780         /* api callbacks */
1781         ot->invoke = WM_menu_invoke;
1782         ot->exec = object_constraint_add_exec;
1783         ot->poll = ED_operator_object_active_editable;
1784         
1785         /* flags */
1786         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1787         
1788         /* properties */
1789         ot->prop = RNA_def_enum(ot->srna, "type", constraint_type_items, 0, "Type", "");
1790 }
1791
1792 void OBJECT_OT_constraint_add_with_targets(wmOperatorType *ot)
1793 {
1794         /* identifiers */
1795         ot->name = "Add Constraint (with Targets)";
1796         ot->description = "Add a constraint to the active object, with target (where applicable) set to the selected Objects/Bones";
1797         ot->idname = "OBJECT_OT_constraint_add_with_targets";
1798         
1799         /* api callbacks */
1800         ot->invoke = WM_menu_invoke;
1801         ot->exec = object_constraint_add_exec;
1802         ot->poll = ED_operator_object_active_editable;
1803         
1804         /* flags */
1805         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1806         
1807         /* properties */
1808         ot->prop = RNA_def_enum(ot->srna, "type", constraint_type_items, 0, "Type", "");
1809 }
1810
1811 void POSE_OT_constraint_add(wmOperatorType *ot)
1812 {
1813         /* identifiers */
1814         ot->name = "Add Constraint";
1815         ot->description = "Add a constraint to the active bone";
1816         ot->idname = "POSE_OT_constraint_add";
1817         
1818         /* api callbacks */
1819         ot->invoke = WM_menu_invoke;
1820         ot->exec = pose_constraint_add_exec;
1821         ot->poll = ED_operator_posemode_exclusive;
1822         
1823         /* flags */
1824         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1825         
1826         /* properties */
1827         ot->prop = RNA_def_enum(ot->srna, "type", constraint_type_items, 0, "Type", "");
1828 }
1829
1830 void POSE_OT_constraint_add_with_targets(wmOperatorType *ot)
1831 {
1832         /* identifiers */
1833         ot->name = "Add Constraint (with Targets)";
1834         ot->description = "Add a constraint to the active bone, with target (where applicable) set to the selected Objects/Bones";
1835         ot->idname = "POSE_OT_constraint_add_with_targets";
1836         
1837         /* api callbacks */
1838         ot->invoke = WM_menu_invoke;
1839         ot->exec = pose_constraint_add_exec;
1840         ot->poll = ED_operator_posemode_exclusive;
1841         
1842         /* flags */
1843         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1844         
1845         /* properties */
1846         ot->prop = RNA_def_enum(ot->srna, "type", constraint_type_items, 0, "Type", "");
1847 }
1848
1849 /************************ IK Constraint operators *********************/
1850 /* NOTE: only for Pose-Channels */
1851 // TODO: should these be here, or back in editors/armature/poseobject.c again?
1852
1853 /* present menu with options + validation for targets to use */
1854 static int pose_ik_add_invoke(bContext *C, wmOperator *op, const wmEvent *UNUSED(event))
1855 {
1856         Object *ob = BKE_object_pose_armature_get(CTX_data_active_object(C));
1857         bPoseChannel *pchan = BKE_pose_channel_active(ob);
1858         bConstraint *con = NULL;
1859         
1860         uiPopupMenu *pup;
1861         uiLayout *layout;
1862         Object *tar_ob = NULL;
1863         bPoseChannel *tar_pchan = NULL;
1864         
1865         /* must have active bone */
1866         if (ELEM(NULL, ob, pchan)) {
1867                 BKE_report(op->reports, RPT_ERROR, "Must have an active bone to add IK constraint to");
1868                 return OPERATOR_CANCELLED;
1869         }
1870         
1871         /* bone must not have any constraints already */
1872         for (con = pchan->constraints.first; con; con = con->next) {
1873                 if (con->type == CONSTRAINT_TYPE_KINEMATIC) break;
1874         }
1875         if (con) {
1876                 BKE_report(op->reports, RPT_ERROR, "Bone already has an IK constraint");
1877                 return OPERATOR_CANCELLED;
1878         }
1879         
1880         /* prepare popup menu to choose targetting options */
1881         pup = uiPupMenuBegin(C, IFACE_("Add IK"), ICON_NONE);
1882         layout = uiPupMenuLayout(pup);
1883         
1884         /* the type of targets we'll set determines the menu entries to show... */
1885         if (get_new_constraint_target(C, CONSTRAINT_TYPE_KINEMATIC, &tar_ob, &tar_pchan, 0)) {
1886                 /* bone target, or object target? 
1887                  *      - the only thing that matters is that we want a target...
1888                  */
1889                 if (tar_pchan)
1890                         uiItemBooleanO(layout, IFACE_("To Active Bone"), ICON_NONE, "POSE_OT_ik_add", "with_targets", 1);
1891                 else
1892                         uiItemBooleanO(layout, IFACE_("To Active Object"), ICON_NONE, "POSE_OT_ik_add", "with_targets", 1);
1893         }
1894         else {
1895                 /* we have a choice of adding to a new empty, or not setting any target (targetless IK) */
1896                 uiItemBooleanO(layout, IFACE_("To New Empty Object"), ICON_NONE, "POSE_OT_ik_add", "with_targets", 1);
1897                 uiItemBooleanO(layout, IFACE_("Without Targets"), ICON_NONE, "POSE_OT_ik_add", "with_targets", 0);
1898         }
1899         
1900         /* finish building the menu, and process it (should result in calling self again) */
1901         uiPupMenuEnd(C, pup);
1902         
1903         return OPERATOR_CANCELLED;
1904 }
1905
1906 /* call constraint_add_exec() to add the IK constraint */
1907 static int pose_ik_add_exec(bContext *C, wmOperator *op)
1908 {
1909         Object *ob = CTX_data_active_object(C);
1910         const bool with_targets = RNA_boolean_get(op->ptr, "with_targets");
1911         
1912         /* add the constraint - all necessary checks should have been done by the invoke() callback already... */
1913         return constraint_add_exec(C, op, ob, get_active_constraints(ob), CONSTRAINT_TYPE_KINEMATIC, with_targets);
1914 }
1915
1916 void POSE_OT_ik_add(wmOperatorType *ot)
1917 {
1918         /* identifiers */
1919         ot->name = "Add IK to Bone";
1920         ot->description = "Add IK Constraint to the active Bone";
1921         ot->idname = "POSE_OT_ik_add";
1922         
1923         /* api callbacks */
1924         ot->invoke = pose_ik_add_invoke;
1925         ot->exec = pose_ik_add_exec;
1926         ot->poll = ED_operator_posemode_exclusive;
1927         
1928         /* flags */
1929         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1930         
1931         /* properties */
1932         RNA_def_boolean(ot->srna, "with_targets", 1, "With Targets", "Assign IK Constraint with targets derived from the select bones/objects");
1933 }
1934
1935 /* ------------------ */
1936
1937 /* remove IK constraints from selected bones */
1938 static int pose_ik_clear_exec(bContext *C, wmOperator *UNUSED(op))
1939 {
1940         Object *ob = BKE_object_pose_armature_get(CTX_data_active_object(C));
1941         
1942         /* only remove IK Constraints */
1943         CTX_DATA_BEGIN (C, bPoseChannel *, pchan, selected_pose_bones)
1944         {
1945                 bConstraint *con, *next;
1946                 
1947                 /* TODO: should we be checking if these contraints were local before we try and remove them? */
1948                 for (con = pchan->constraints.first; con; con = next) {
1949                         next = con->next;
1950                         if (con->type == CONSTRAINT_TYPE_KINEMATIC) {
1951                                 BKE_remove_constraint(&pchan->constraints, con);
1952                         }
1953                 }
1954                 pchan->constflag &= ~(PCHAN_HAS_IK | PCHAN_HAS_TARGET);
1955         }
1956         CTX_DATA_END;
1957         
1958         /* refresh depsgraph */
1959         DAG_id_tag_update(&ob->id, OB_RECALC_DATA);
1960
1961         /* note, notifier might evolve */
1962         WM_event_add_notifier(C, NC_OBJECT | ND_CONSTRAINT | NA_REMOVED, ob);
1963         
1964         return OPERATOR_FINISHED;
1965 }
1966
1967 void POSE_OT_ik_clear(wmOperatorType *ot)
1968 {
1969         /* identifiers */
1970         ot->name = "Remove IK";
1971         ot->description = "Remove all IK Constraints from selected bones";
1972         ot->idname = "POSE_OT_ik_clear";
1973         
1974         /* api callbacks */
1975         ot->exec = pose_ik_clear_exec;
1976         ot->poll = ED_operator_posemode_exclusive;
1977         
1978         /* flags */
1979         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1980 }
1981