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