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