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