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