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