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