Merge of itasc branch. Project files, scons and cmake should be working. Makefile...
[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., 59 Temple Place - Suite 330, Boston, MA  02111-1307, 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_arithb.h"
37 #include "BLI_dynstr.h"
38
39 #include "DNA_action_types.h"
40 #include "DNA_armature_types.h"
41 #include "DNA_constraint_types.h"
42 #include "DNA_curve_types.h"
43 #include "DNA_object_types.h"
44 #include "DNA_scene_types.h"
45 #include "DNA_screen_types.h"
46 #include "DNA_text_types.h"
47 #include "DNA_view3d_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_utildefines.h"
59 #include "BIK_api.h"
60
61 #ifndef DISABLE_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 #include "RNA_types.h"
72
73 #include "ED_object.h"
74 #include "ED_screen.h"
75
76 #include "UI_interface.h"
77
78 #include "object_intern.h"
79
80 /* -------------- Get Active Constraint Data ---------------------- */
81
82 /* if object in posemode, active bone constraints, else object constraints */
83 ListBase *get_active_constraints (Object *ob)
84 {
85         if (ob == NULL)
86                 return NULL;
87
88         if (ob->mode & OB_MODE_POSE) {
89                 bPoseChannel *pchan;
90                 
91                 pchan = get_active_posechannel(ob);
92                 if (pchan)
93                         return &pchan->constraints;
94         }
95         else 
96                 return &ob->constraints;
97
98         return NULL;
99 }
100
101 /* single constraint */
102 bConstraint *get_active_constraint (Object *ob)
103 {
104         ListBase *lb= get_active_constraints(ob);
105
106         if (lb) {
107                 bConstraint *con;
108                 
109                 for (con= lb->first; con; con=con->next) {
110                         if (con->flag & CONSTRAINT_ACTIVE)
111                                 return con;
112                 }
113         }
114         
115         return NULL;
116 }
117 /* -------------- Constraint Management (Add New, Remove, Rename) -------------------- */
118 /* ------------- PyConstraints ------------------ */
119
120 /* this callback sets the text-file to be used for selected menu item */
121 void validate_pyconstraint_cb (void *arg1, void *arg2)
122 {
123         bPythonConstraint *data = arg1;
124         Text *text= NULL;
125         int index = *((int *)arg2);
126         int i;
127         
128         /* exception for no script */
129         if (index) {
130                 /* innovative use of a for...loop to search */
131                 for (text=G.main->text.first, i=1; text && index!=i; i++, text=text->id.next);
132         }
133         data->text = text;
134 }
135
136 #ifndef DISABLE_PYTHON
137 /* this returns a string for the list of usable pyconstraint script names */
138 char *buildmenu_pyconstraints (Text *con_text, int *pyconindex)
139 {
140         DynStr *pupds= BLI_dynstr_new();
141         Text *text;
142         char *str;
143         char buf[64];
144         int i;
145         
146         /* add title first */
147         sprintf(buf, "Scripts: %%t|[None]%%x0|");
148         BLI_dynstr_append(pupds, buf);
149         
150         /* init active-index first */
151         if (con_text == NULL)
152                 *pyconindex= 0;
153         
154         /* loop through markers, adding them */
155         for (text=G.main->text.first, i=1; text; i++, text=text->id.next) {
156                 /* this is important to ensure that right script is shown as active */
157                 if (text == con_text) *pyconindex = i;
158                 
159                 /* only include valid pyconstraint scripts */
160                 if (BPY_is_pyconstraint(text)) {
161                         BLI_dynstr_append(pupds, text->id.name+2);
162                         
163                         sprintf(buf, "%%x%d", i);
164                         BLI_dynstr_append(pupds, buf);
165                         
166                         if (text->id.next)
167                                 BLI_dynstr_append(pupds, "|");
168                 }
169         }
170         
171         /* convert to normal MEM_malloc'd string */
172         str= BLI_dynstr_get_cstring(pupds);
173         BLI_dynstr_free(pupds);
174         
175         return str;
176 }
177 #endif /* DISABLE_PYTHON */
178
179 /* this callback gets called when the 'refresh' button of a pyconstraint gets pressed */
180 void update_pyconstraint_cb (void *arg1, void *arg2)
181 {
182         Object *owner= (Object *)arg1;
183         bConstraint *con= (bConstraint *)arg2;
184 #ifndef DISABLE_PYTHON
185         if (owner && con)
186                 BPY_pyconstraint_update(owner, con);
187 #endif
188 }
189
190 /* Creates a new constraint, initialises its data, and returns it */
191 bConstraint *add_new_constraint (short type)
192 {
193         bConstraint *con;
194         bConstraintTypeInfo *cti;
195
196         con = MEM_callocN(sizeof(bConstraint), "Constraint");
197         
198         /* Set up a generic constraint datablock */
199         con->type = type;
200         con->flag |= CONSTRAINT_EXPAND;
201         con->enforce = 1.0f;
202         
203         /* Load the data for it */
204         cti = constraint_get_typeinfo(con);
205         if (cti) {
206                 con->data = MEM_callocN(cti->size, cti->structName);
207                 
208                 /* only constraints that change any settings need this */
209                 if (cti->new_data)
210                         cti->new_data(con->data);
211                         
212                 /* set the name based on the type of constraint */
213                 strcpy(con->name, cti->name); 
214         }
215         else
216                 strcpy(con->name, "Const");
217         
218         return con;
219 }
220
221 /* Adds the given constraint to the Object-level set of constraints for the given Object */
222 void add_constraint_to_object (bConstraint *con, Object *ob)
223 {
224         ListBase *list;
225         list = &ob->constraints;
226         
227         if (list) {
228                 unique_constraint_name(con, list);
229                 BLI_addtail(list, con);
230                 
231                 if (proxylocked_constraints_owner(ob, NULL))
232                         con->flag |= CONSTRAINT_PROXY_LOCAL;
233                 
234                 con->flag |= CONSTRAINT_ACTIVE;
235                 for (con= con->prev; con; con= con->prev)
236                         con->flag &= ~CONSTRAINT_ACTIVE;
237         }
238 }
239
240 /* helper function for add_constriant - sets the last target for the active constraint */
241 static void set_constraint_nth_target (bConstraint *con, Object *target, char subtarget[], int index)
242 {
243         bConstraintTypeInfo *cti= constraint_get_typeinfo(con);
244         ListBase targets = {NULL, NULL};
245         bConstraintTarget *ct;
246         int num_targets, i;
247         
248         if (cti && cti->get_constraint_targets) {
249                 cti->get_constraint_targets(con, &targets);
250                 num_targets= BLI_countlist(&targets);
251                 
252                 if (index < 0) {
253                         if (abs(index) < num_targets)
254                                 index= num_targets - abs(index);
255                         else
256                                 index= num_targets - 1;
257                 }
258                 else if (index >= num_targets) {
259                         index= num_targets - 1;
260                 }
261                 
262                 for (ct=targets.first, i=0; ct; ct= ct->next, i++) {
263                         if (i == index) {
264                                 ct->tar= target;
265                                 strcpy(ct->subtarget, subtarget);
266                                 break;
267                         }
268                 }
269                 
270                 if (cti->flush_constraint_targets)
271                         cti->flush_constraint_targets(con, &targets, 0);
272         }
273 }
274
275 /* ------------- Constraint Sanity Testing ------------------- */
276
277 /* checks validity of object pointers, and NULLs,
278  * if Bone doesnt exist it sets the CONSTRAINT_DISABLE flag 
279  */
280 static void test_constraints (Object *owner, const char substring[])
281 {
282         bConstraint *curcon;
283         ListBase *conlist= NULL;
284         int type;
285         
286         if (owner==NULL) return;
287         
288         /* Check parents */
289         if (strlen(substring)) {
290                 switch (owner->type) {
291                         case OB_ARMATURE:
292                                 type = CONSTRAINT_OBTYPE_BONE;
293                                 break;
294                         default:
295                                 type = CONSTRAINT_OBTYPE_OBJECT;
296                                 break;
297                 }
298         }
299         else
300                 type = CONSTRAINT_OBTYPE_OBJECT;
301         
302         /* Get the constraint list for this object */
303         switch (type) {
304                 case CONSTRAINT_OBTYPE_OBJECT:
305                         conlist = &owner->constraints;
306                         break;
307                 case CONSTRAINT_OBTYPE_BONE:
308                         {
309                                 Bone *bone;
310                                 bPoseChannel *chan;
311                                 
312                                 bone = get_named_bone( ((bArmature *)owner->data), substring );
313                                 chan = get_pose_channel(owner->pose, substring);
314                                 if (bone && chan) {
315                                         conlist = &chan->constraints;
316                                 }
317                         }
318                         break;
319         }
320         
321         /* Check all constraints - is constraint valid? */
322         if (conlist) {
323                 for (curcon = conlist->first; curcon; curcon=curcon->next) {
324                         bConstraintTypeInfo *cti= constraint_get_typeinfo(curcon);
325                         ListBase targets = {NULL, NULL};
326                         bConstraintTarget *ct;
327                         
328                         /* clear disabled-flag first */
329                         curcon->flag &= ~CONSTRAINT_DISABLE;
330
331                         if (curcon->type == CONSTRAINT_TYPE_KINEMATIC) {
332                                 bKinematicConstraint *data = curcon->data;
333                                 
334                                 /* bad: we need a separate set of checks here as poletarget is 
335                                  *              optional... otherwise poletarget must exist too or else
336                                  *              the constraint is deemed invalid
337                                  */
338                                 /* default IK check ... */
339                                 if (exist_object(data->tar) == 0) {
340                                         data->tar = NULL;
341                                         curcon->flag |= CONSTRAINT_DISABLE;
342                                 }
343                                 else if (data->tar == owner) {
344                                         if (!get_named_bone(get_armature(owner), data->subtarget)) {
345                                                 curcon->flag |= CONSTRAINT_DISABLE;
346                                         }
347                                 }
348                                 
349                                 if (data->poletar) {
350                                         if (exist_object(data->poletar) == 0) {
351                                                 data->poletar = NULL;
352                                                 curcon->flag |= CONSTRAINT_DISABLE;
353                                         }
354                                         else if (data->poletar == owner) {
355                                                 if (!get_named_bone(get_armature(owner), data->polesubtarget)) {
356                                                         curcon->flag |= CONSTRAINT_DISABLE;
357                                                 }
358                                         }
359                                 }
360                                 /* ... can be overwritten here */
361                                 BIK_test_constraint(owner, curcon);
362                                 /* targets have already been checked for this */
363                                 continue;
364                         }
365                         else if (curcon->type == CONSTRAINT_TYPE_ACTION) {
366                                 bActionConstraint *data = curcon->data;
367                                 
368                                 /* validate action */
369                                 if (data->act == NULL) 
370                                         curcon->flag |= CONSTRAINT_DISABLE;
371                         }
372                         else if (curcon->type == CONSTRAINT_TYPE_FOLLOWPATH) {
373                                 bFollowPathConstraint *data = curcon->data;
374                                 
375                                 /* don't allow track/up axes to be the same */
376                                 if (data->upflag==data->trackflag)
377                                         curcon->flag |= CONSTRAINT_DISABLE;
378                                 if (data->upflag+3==data->trackflag)
379                                         curcon->flag |= CONSTRAINT_DISABLE;
380                         }
381                         else if (curcon->type == CONSTRAINT_TYPE_TRACKTO) {
382                                 bTrackToConstraint *data = curcon->data;
383                                 
384                                 /* don't allow track/up axes to be the same */
385                                 if (data->reserved2==data->reserved1)
386                                         curcon->flag |= CONSTRAINT_DISABLE;
387                                 if (data->reserved2+3==data->reserved1)
388                                         curcon->flag |= CONSTRAINT_DISABLE;
389                         }
390                         else if (curcon->type == CONSTRAINT_TYPE_LOCKTRACK) {
391                                 bLockTrackConstraint *data = curcon->data;
392                                 
393                                 if (data->lockflag==data->trackflag)
394                                         curcon->flag |= CONSTRAINT_DISABLE;
395                                 if (data->lockflag+3==data->trackflag)
396                                         curcon->flag |= CONSTRAINT_DISABLE;
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 (ELEM(curcon->type, CONSTRAINT_TYPE_FOLLOWPATH, CONSTRAINT_TYPE_CLAMPTO)) {
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 static void test_bonelist_constraints (Object *owner, ListBase *list)
442 {
443         Bone *bone;
444
445         for (bone = list->first; bone; bone = bone->next) {
446                 test_constraints(owner, bone->name);
447                 test_bonelist_constraints(owner, &bone->childbase);
448         }
449 }
450
451 void object_test_constraints (Object *owner)
452 {
453         test_constraints(owner, "");
454
455         if (owner->type==OB_ARMATURE) {
456                 bArmature *arm= get_armature(owner);
457                 
458                 if (arm)
459                         test_bonelist_constraints(owner, &arm->bonebase);
460         }
461 }
462
463 /* ********************** CONSTRAINT-SPECIFIC STUFF ********************* */
464
465 /* ---------- Distance-Dependent Constraints ---------- */
466 /* StretchTo, Limit Distance */
467
468 static int stretchto_poll(bContext *C)
469 {
470         PointerRNA ptr= CTX_data_pointer_get_type(C, "constraint", &RNA_StretchToConstraint);
471         return (ptr.id.data && ptr.data);
472 }
473
474 static int stretchto_reset_exec (bContext *C, wmOperator *op)
475 {
476         PointerRNA ptr= CTX_data_pointer_get_type(C, "constraint", &RNA_StretchToConstraint);
477         
478         /* just set original length to 0.0, which will cause a reset on next recalc */
479         RNA_float_set(&ptr, "original_length", 0.0f);
480         
481         WM_event_add_notifier(C, NC_OBJECT|ND_CONSTRAINT, NULL);
482         return OPERATOR_FINISHED;
483 }
484
485 void CONSTRAINT_OT_stretchto_reset (wmOperatorType *ot)
486 {
487         /* identifiers */
488         ot->name= "Reset Original Length";
489         ot->idname= "CONSTRAINT_OT_stretchto_reset";
490         ot->description= "Reset original length of bone for Stretch To Constraint.";
491         
492         ot->exec= stretchto_reset_exec;
493         ot->poll= stretchto_poll;
494         
495         /* flags */
496         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
497 }
498
499
500 static int limitdistance_reset_exec (bContext *C, wmOperator *op)
501 {
502         PointerRNA ptr= CTX_data_pointer_get_type(C, "constraint", &RNA_LimitDistanceConstraint);
503         
504         /* just set distance to 0.0, which will cause a reset on next recalc */
505         RNA_float_set(&ptr, "distance", 0.0f);
506         
507         WM_event_add_notifier(C, NC_OBJECT|ND_CONSTRAINT, NULL);
508         return OPERATOR_FINISHED;
509 }
510
511 static int limitdistance_poll(bContext *C)
512 {
513         PointerRNA ptr= CTX_data_pointer_get_type(C, "constraint", &RNA_LimitDistanceConstraint);
514         return (ptr.id.data && ptr.data);
515 }
516
517 void CONSTRAINT_OT_limitdistance_reset (wmOperatorType *ot)
518 {
519         /* identifiers */
520         ot->name= "Reset Distance";
521         ot->idname= "CONSTRAINT_OT_limitdistance_reset";
522         ot->description= "Reset limiting distance for Limit Distance Constraint.";
523         
524         ot->exec= limitdistance_reset_exec;
525         ot->poll= limitdistance_poll;
526         
527         /* flags */
528         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
529 }
530
531 /* ------------- Child-Of Constraint ------------------ */
532
533 static int childof_poll(bContext *C)
534 {
535         PointerRNA ptr= CTX_data_pointer_get_type(C, "constraint", &RNA_ChildOfConstraint);
536         return (ptr.id.data && ptr.data);
537 }
538
539 /* ChildOf Constraint - set inverse callback */
540 static int childof_set_inverse_exec (bContext *C, wmOperator *op)
541 {
542         PointerRNA ptr= CTX_data_pointer_get_type(C, "constraint", &RNA_ChildOfConstraint);
543         Scene *scene= CTX_data_scene(C);
544         Object *ob= ptr.id.data;
545         bConstraint *con= ptr.data;
546         bChildOfConstraint *data= (bChildOfConstraint *)con->data;
547         bPoseChannel *pchan= NULL;
548
549         /* try to find a pose channel */
550         // TODO: get from context instead?
551         if (ob && ob->pose)
552                 pchan= get_active_posechannel(ob);
553         
554         /* calculate/set inverse matrix */
555         if (pchan) {
556                 float pmat[4][4], cinf;
557                 float imat[4][4], tmat[4][4];
558                 
559                 /* make copy of pchan's original pose-mat (for use later) */
560                 Mat4CpyMat4(pmat, pchan->pose_mat);
561                 
562                 /* disable constraint for pose to be solved without it */
563                 cinf= con->enforce;
564                 con->enforce= 0.0f;
565                 
566                 /* solve pose without constraint */
567                 where_is_pose(scene, ob);
568                 
569                 /* determine effect of constraint by removing the newly calculated 
570                  * pchan->pose_mat from the original pchan->pose_mat, thus determining 
571                  * the effect of the constraint
572                  */
573                 Mat4Invert(imat, pchan->pose_mat);
574                 Mat4MulMat4(tmat, imat, pmat);
575                 Mat4Invert(data->invmat, tmat);
576                 
577                 /* recalculate pose with new inv-mat */
578                 con->enforce= cinf;
579                 where_is_pose(scene, ob);
580         }
581         else if (ob) {
582                 Object workob;
583                 /* use what_does_parent to find inverse - just like for normal parenting.
584                  * NOTE: what_does_parent uses a static workob defined in object.c 
585                  */
586                 what_does_parent(scene, ob, &workob);
587                 Mat4Invert(data->invmat, workob.obmat);
588         }
589         else
590                 Mat4One(data->invmat);
591                 
592         WM_event_add_notifier(C, NC_OBJECT|ND_CONSTRAINT, ob);
593                 
594         return OPERATOR_FINISHED;
595 }
596
597 void CONSTRAINT_OT_childof_set_inverse (wmOperatorType *ot)
598 {
599         /* identifiers */
600         ot->name= "Set Inverse";
601         ot->idname= "CONSTRAINT_OT_childof_set_inverse";
602         ot->description= "Set inverse correction for ChildOf constraint.";
603         
604         ot->exec= childof_set_inverse_exec;
605         ot->poll= childof_poll;
606         
607         /* flags */
608         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
609 }
610
611 /* ChildOf Constraint - clear inverse callback */
612 static int childof_clear_inverse_exec (bContext *C, wmOperator *op)
613 {
614         PointerRNA ptr= CTX_data_pointer_get_type(C, "constraint", &RNA_ChildOfConstraint);
615         Object *ob= ptr.id.data;
616         bConstraint *con= ptr.data;
617         bChildOfConstraint *data= (bChildOfConstraint *)con->data;
618         
619         /* simply clear the matrix */
620         Mat4One(data->invmat);
621         
622         WM_event_add_notifier(C, NC_OBJECT|ND_CONSTRAINT, ob);
623         
624         return OPERATOR_FINISHED;
625 }
626
627 void CONSTRAINT_OT_childof_clear_inverse (wmOperatorType *ot)
628 {
629         /* identifiers */
630         ot->name= "Clear Inverse";
631         ot->idname= "CONSTRAINT_OT_childof_clear_inverse";
632         ot->description= "Clear inverse correction for ChildOf constraint.";
633         
634         ot->exec= childof_clear_inverse_exec;
635         ot->poll= childof_poll;
636         
637         /* flags */
638         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
639 }
640
641 /***************************** BUTTONS ****************************/
642
643 /* Rename the given constraint, con already has the new name */
644 void ED_object_constraint_rename(Object *ob, bConstraint *con, char *oldname)
645 {
646         bConstraint *tcon;
647         ListBase *conlist= NULL;
648         int from_object= 0;
649         
650         /* get context by searching for con (primitive...) */
651         for (tcon= ob->constraints.first; tcon; tcon= tcon->next) {
652                 if (tcon==con)
653                         break;
654         }
655         
656         if (tcon) {
657                 conlist= &ob->constraints;
658                 from_object= 1;
659         }
660         else if (ob->pose) {
661                 bPoseChannel *pchan;
662                 
663                 for (pchan=ob->pose->chanbase.first; pchan; pchan=pchan->next) {
664                         for (tcon= pchan->constraints.first; tcon; tcon= tcon->next) {
665                                 if (tcon==con)
666                                         break;
667                         }
668                         if (tcon) 
669                                 break;
670                 }
671                 
672                 if (tcon) {
673                         conlist= &pchan->constraints;
674                 }
675         }
676         
677         if (conlist==NULL) {
678                 printf("rename constraint failed\n");   /* should not happen in UI */
679                 return;
680         }
681         
682         /* first make sure it's a unique name within context */
683         unique_constraint_name(con, conlist);
684 }
685
686
687
688
689 void ED_object_constraint_set_active(Object *ob, bConstraint *con)
690 {
691         ListBase *lb;
692         bConstraint *origcon= con;
693         
694         /* lets be nice and escape if its active already */
695         if(con && (con->flag & CONSTRAINT_ACTIVE))
696                 return ;
697         
698         lb= get_active_constraints(ob);
699         if(lb == NULL)
700                 return;
701         
702         for(con= lb->first; con; con= con->next) {
703                 if(con==origcon) con->flag |= CONSTRAINT_ACTIVE;
704                 else con->flag &= ~CONSTRAINT_ACTIVE;
705         }
706 }
707
708 void ED_object_constraint_update(Object *ob)
709 {
710
711         if(ob->pose) update_pose_constraint_flags(ob->pose);
712
713         object_test_constraints(ob);
714
715         if(ob->type==OB_ARMATURE) DAG_id_flush_update(&ob->id, OB_RECALC_DATA|OB_RECALC_OB);
716         else DAG_id_flush_update(&ob->id, OB_RECALC_OB);
717 }
718
719 void ED_object_constraint_dependency_update(Scene *scene, Object *ob)
720 {
721         ED_object_constraint_update(ob);
722
723         if(ob->pose) ob->pose->flag |= POSE_RECALC;     // checks & sorts pose channels
724     DAG_scene_sort(scene);
725 }
726
727 static int constraint_poll(bContext *C)
728 {
729         PointerRNA ptr= CTX_data_pointer_get_type(C, "constraint", &RNA_Constraint);
730         return (ptr.id.data && ptr.data);
731 }
732
733 static int constraint_delete_exec (bContext *C, wmOperator *op)
734 {
735         PointerRNA ptr= CTX_data_pointer_get_type(C, "constraint", &RNA_Constraint);
736         Object *ob= ptr.id.data;
737         bConstraint *con= ptr.data;
738         ListBase *lb;
739         
740         /* remove constraint itself */
741         lb= get_active_constraints(ob);
742         if (BLI_findindex(lb, con) == -1)
743                 /* abnormal situation which happens on bone constraint when the armature is not in pose mode */
744                 return OPERATOR_CANCELLED;
745
746         free_constraint_data(con);
747         BLI_freelinkN(lb, con);
748         
749         ED_object_constraint_set_active(ob, NULL);
750         WM_event_add_notifier(C, NC_OBJECT|ND_CONSTRAINT, ob);
751
752         return OPERATOR_FINISHED;
753 }
754
755 void CONSTRAINT_OT_delete (wmOperatorType *ot)
756 {
757         /* identifiers */
758         ot->name= "Delete Constraint";
759         ot->idname= "CONSTRAINT_OT_delete";
760         ot->description= "Remove constraitn from constraint stack.";
761         
762         /* callbacks */
763         ot->exec= constraint_delete_exec;
764         ot->poll= constraint_poll;
765         
766         /* flags */
767         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO; 
768 }
769
770 static int constraint_move_down_exec (bContext *C, wmOperator *op)
771 {
772         PointerRNA ptr= CTX_data_pointer_get_type(C, "constraint", &RNA_Constraint);
773         Object *ob= ptr.id.data;
774         bConstraint *con= ptr.data;
775         
776         if (con->next) {
777                 ListBase *conlist= get_active_constraints(ob);
778                 bConstraint *nextCon= con->next;
779                 
780                 /* insert the nominated constraint after the one that used to be after it */
781                 BLI_remlink(conlist, con);
782                 BLI_insertlinkafter(conlist, nextCon, con);
783                 
784                 WM_event_add_notifier(C, NC_OBJECT|ND_CONSTRAINT, ob);
785                 
786                 return OPERATOR_FINISHED;
787         }
788         
789         return OPERATOR_CANCELLED;
790 }
791
792 void CONSTRAINT_OT_move_down (wmOperatorType *ot)
793 {
794         /* identifiers */
795         ot->name= "Move Constraint Down";
796         ot->idname= "CONSTRAINT_OT_move_down";
797         ot->description= "Move constraint down constraint stack.";
798         
799         /* callbacks */
800         ot->exec= constraint_move_down_exec;
801         ot->poll= constraint_poll;
802         
803         /* flags */
804         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO; 
805 }
806
807
808 static int constraint_move_up_exec (bContext *C, wmOperator *op)
809 {
810         PointerRNA ptr= CTX_data_pointer_get_type(C, "constraint", &RNA_Constraint);
811         Object *ob= ptr.id.data;
812         bConstraint *con= ptr.data;
813         
814         if (con->prev) {
815                 ListBase *conlist= get_active_constraints(ob);
816                 bConstraint *prevCon= con->prev;
817                 
818                 /* insert the nominated constraint before the one that used to be before it */
819                 BLI_remlink(conlist, con);
820                 BLI_insertlinkbefore(conlist, prevCon, con);
821                 
822                 WM_event_add_notifier(C, NC_OBJECT|ND_CONSTRAINT, ob);
823                 
824                 return OPERATOR_FINISHED;
825         }
826         
827         return OPERATOR_CANCELLED;
828 }
829
830 void CONSTRAINT_OT_move_up (wmOperatorType *ot)
831 {
832         /* identifiers */
833         ot->name= "Move Constraint Up";
834         ot->idname= "CONSTRAINT_OT_move_up";
835         ot->description= "Move constraint up constraint stack.";
836         
837         /* callbacks */
838         ot->exec= constraint_move_up_exec;
839         ot->poll= constraint_poll;
840         
841         /* flags */
842         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO; 
843 }
844
845 /***************************** OPERATORS ****************************/
846
847 /************************ remove constraint operators *********************/
848
849 static int pose_constraints_clear_exec(bContext *C, wmOperator *op)
850 {
851         Object *ob= CTX_data_active_object(C);
852         Scene *scene= CTX_data_scene(C);
853         
854         /* free constraints for all selected bones */
855         CTX_DATA_BEGIN(C, bPoseChannel*, pchan, selected_pchans)
856         {
857                 free_constraints(&pchan->constraints);
858                 pchan->constflag &= ~(PCHAN_HAS_IK|PCHAN_HAS_CONST);
859         }
860         CTX_DATA_END;
861         
862         /* force depsgraph to get recalculated since relationships removed */
863         DAG_scene_sort(scene);          /* sort order of objects */     
864         
865         /* do updates */
866         DAG_id_flush_update(&ob->id, OB_RECALC_DATA);
867         WM_event_add_notifier(C, NC_OBJECT|ND_CONSTRAINT, ob);
868         
869         return OPERATOR_FINISHED;
870 }
871
872 void POSE_OT_constraints_clear(wmOperatorType *ot)
873 {
874         /* identifiers */
875         ot->name = "Clear Constraints";
876         ot->idname= "POSE_OT_constraints_clear";
877         ot->description= "Clear all the constraints for the selected bones.";
878         
879         /* callbacks */
880         ot->exec= pose_constraints_clear_exec;
881         ot->poll= ED_operator_posemode; // XXX - do we want to ensure there are selected bones too?
882 }
883
884
885 static int object_constraints_clear_exec(bContext *C, wmOperator *op)
886 {
887         Object *ob= CTX_data_active_object(C);
888         Scene *scene= CTX_data_scene(C);
889         
890         /* do freeing */
891         // TODO: we should free constraints for all selected objects instead (to be more consistent with bones)
892         free_constraints(&ob->constraints);
893         
894         /* force depsgraph to get recalculated since relationships removed */
895         DAG_scene_sort(scene);          /* sort order of objects */     
896         
897         /* do updates */
898         DAG_id_flush_update(&ob->id, OB_RECALC_OB);
899         WM_event_add_notifier(C, NC_OBJECT|ND_CONSTRAINT, ob);
900         
901         return OPERATOR_FINISHED;
902 }
903
904 void OBJECT_OT_constraints_clear(wmOperatorType *ot)
905 {
906         /* identifiers */
907         ot->name = "Clear Constraints";
908         ot->idname= "OBJECT_OT_constraints_clear";
909         ot->description= "Clear all the constraints for the active Object only.";
910         
911         /* callbacks */
912         ot->exec= object_constraints_clear_exec;
913         ot->poll= ED_operator_object_active;
914 }
915
916 /************************ add constraint operators *********************/
917
918 /* get the Object and/or PoseChannel to use as target */
919 static short get_new_constraint_target(bContext *C, int con_type, Object **tar_ob, bPoseChannel **tar_pchan, short add)
920 {
921         Object *obact= CTX_data_active_object(C);
922         bPoseChannel *pchanact= get_active_posechannel(obact);
923         short only_curve= 0, only_mesh= 0, only_ob= 0;
924         short found= 0;
925         
926         /* clear tar_ob and tar_pchan fields before use 
927          *      - assume for now that both always exist...
928          */
929         *tar_ob= NULL;
930         *tar_pchan= NULL;
931         
932         /* check if constraint type doesn't requires a target
933          *      - if so, no need to get any targets 
934          */
935         switch (con_type) {
936                 /* no-target constraints --------------------------- */
937                         /* null constraint - shouldn't even be added! */
938                 case CONSTRAINT_TYPE_NULL:
939                         /* limit constraints - no targets needed */
940                 case CONSTRAINT_TYPE_LOCLIMIT:
941                 case CONSTRAINT_TYPE_ROTLIMIT:
942                 case CONSTRAINT_TYPE_SIZELIMIT:
943                         return 0;
944                         
945                 /* restricted target-type constraints -------------- */
946                 /* NOTE: for these, we cannot try to add a target object if no valid ones are found, since that doesn't work */
947                         /* curve-based constraints - set the only_curve and only_ob flags */
948                 case CONSTRAINT_TYPE_CLAMPTO:
949                 case CONSTRAINT_TYPE_FOLLOWPATH:
950                         only_curve= 1;
951                         only_ob= 1;
952                         add= 0;
953                         break;
954                         
955                         /* mesh only? */
956                 case CONSTRAINT_TYPE_SHRINKWRAP:
957                         only_mesh= 1;
958                         only_ob= 1;
959                         add= 0;
960                         break;
961                         
962                         /* object only - add here is ok? */
963                 case CONSTRAINT_TYPE_RIGIDBODYJOINT:
964                         only_ob= 1;
965                         break;
966         }
967         
968         /* if the active Object is Armature, and we can search for bones, do so... */
969         if ((obact->type == OB_ARMATURE) && (only_ob == 0)) {
970                 /* search in list of selected Pose-Channels for target */
971                 CTX_DATA_BEGIN(C, bPoseChannel*, pchan, selected_pchans) 
972                 {
973                         /* just use the first one that we encounter, as long as it is not the active one */
974                         if (pchan != pchanact) {
975                                 *tar_ob= obact;
976                                 *tar_pchan= pchan;
977                                 found= 1;
978                                 
979                                 break;
980                         }
981                 }
982                 CTX_DATA_END;
983         }
984         
985         /* if not yet found, try selected Objects... */
986         if (found == 0) {
987                 /* search in selected objects context */
988                 CTX_DATA_BEGIN(C, Object*, ob, selected_objects) 
989                 {
990                         /* just use the first object we encounter (that isn't the active object) 
991                          * and which fulfills the criteria for the object-target that we've got 
992                          */
993                         if ( (ob != obact) &&
994                                  ((!only_curve) || (ob->type == OB_CURVE)) && 
995                                  ((!only_mesh) || (ob->type == OB_MESH)) )
996                         {
997                                 /* set target */
998                                 *tar_ob= ob;
999                                 found= 1;
1000                                 
1001                                 /* perform some special operations on the target */
1002                                 if (only_curve) {
1003                                         /* Curve-Path option must be enabled for follow-path constraints to be able to work */
1004                                         Curve *cu= (Curve *)ob->data;
1005                                         cu->flag |= CU_PATH;
1006                                 }
1007                                 
1008                                 break;
1009                         }
1010                 }
1011                 CTX_DATA_END;
1012         }
1013         
1014         /* if still not found, add a new empty to act as a target (if allowed) */
1015         if ((found == 0) && (add)) {
1016                 Scene *scene= CTX_data_scene(C);
1017                 Base *base= BASACT, *newbase=NULL;
1018                 Object *obt;
1019                 
1020                 /* add new target object */
1021                 obt= add_object(scene, OB_EMPTY);
1022                 
1023                 /* set layers OK */
1024                 newbase= BASACT;
1025                 newbase->lay= base->lay;
1026                 obt->lay= newbase->lay;
1027                 
1028                 /* transform cent to global coords for loc */
1029                 if (pchanact) {
1030                         /* since by default, IK targets the tip of the last bone, use the tip of the active PoseChannel 
1031                          * if adding a target for an IK Constraint
1032                          */
1033                         if (con_type == CONSTRAINT_TYPE_KINEMATIC)
1034                                 VecMat4MulVecfl(obt->loc, obact->obmat, pchanact->pose_tail);
1035                         else
1036                                 VecMat4MulVecfl(obt->loc, obact->obmat, pchanact->pose_head);
1037                 }
1038                 else
1039                         VECCOPY(obt->loc, obact->obmat[3]);
1040                 
1041                 /* restore, add_object sets active */
1042                 BASACT= base;
1043                 base->flag |= SELECT;
1044                 
1045                 /* make our new target the new object */
1046                 *tar_ob= obt;
1047                 found= 1;
1048         }
1049         
1050         /* return whether there's any target */
1051         return found;
1052 }
1053
1054 /* used by add constraint operators to add the constraint required */
1055 static int constraint_add_exec(bContext *C, wmOperator *op, Object *ob, ListBase *list, int type, short setTarget)
1056 {
1057         Scene *scene= CTX_data_scene(C);
1058         bPoseChannel *pchan= get_active_posechannel(ob);
1059         bConstraint *con;
1060         
1061         /* check if constraint to be added is valid for the given constraints stack */
1062         if (type == CONSTRAINT_TYPE_NULL) {
1063                 return OPERATOR_CANCELLED;
1064         }
1065         if ( (type == CONSTRAINT_TYPE_RIGIDBODYJOINT) && (list != &ob->constraints) ) {
1066                 BKE_report(op->reports, RPT_ERROR, "Rigid Body Joint Constraint can only be added to Objects.");
1067                 return OPERATOR_CANCELLED;
1068         }
1069         if ( (type == CONSTRAINT_TYPE_KINEMATIC) && ((!pchan) || (list != &pchan->constraints)) ) {
1070                 BKE_report(op->reports, RPT_ERROR, "IK Constraint can only be added to Bones.");
1071                 return OPERATOR_CANCELLED;
1072         }
1073         
1074         /* create a new constraint of the type requried, and add it to the active/given constraints list */
1075         con = add_new_constraint(type);
1076         
1077         if (list) {
1078                 bConstraint *coniter; 
1079                 
1080                 /* add new constraint to end of list of constraints before ensuring that it has a unique name 
1081                  * (otherwise unique-naming code will fail, since it assumes element exists in list)
1082                  */
1083                 BLI_addtail(list, con);
1084                 unique_constraint_name(con, list);
1085                 
1086                 /* if the target list is a list on some PoseChannel belonging to a proxy-protected 
1087                  * Armature layer, we must tag newly added constraints with a flag which allows them
1088                  * to persist after proxy syncing has been done
1089                  */
1090                 if (proxylocked_constraints_owner(ob, pchan))
1091                         con->flag |= CONSTRAINT_PROXY_LOCAL;
1092                 
1093                 /* make this constraint the active one 
1094                  *      - since constraint was added at end of stack, we can just go 
1095                  *        through deactivating all previous ones
1096                  */
1097                 con->flag |= CONSTRAINT_ACTIVE;
1098                 for (coniter= con->prev; coniter; coniter= coniter->prev)
1099                         coniter->flag &= ~CONSTRAINT_ACTIVE;
1100         }
1101         
1102         /* get the first selected object/bone, and make that the target
1103          *      - apart from the buttons-window add buttons, we shouldn't add in this way
1104          */
1105         if (setTarget) {
1106                 Object *tar_ob= NULL;
1107                 bPoseChannel *tar_pchan= NULL;
1108                 
1109                 /* get the target objects, adding them as need be */
1110                 if (get_new_constraint_target(C, type, &tar_ob, &tar_pchan, 1)) {
1111                         /* method of setting target depends on the type of target we've got 
1112                          *      - by default, just set the first target (distinction here is only for multiple-targetted constraints)
1113                          */
1114                         if (tar_pchan)
1115                                 set_constraint_nth_target(con, tar_ob, tar_pchan->name, 0);
1116                         else
1117                                 set_constraint_nth_target(con, tar_ob, "", 0);
1118                 }
1119         }
1120         
1121         /* do type-specific tweaking to the constraint settings  */
1122         switch (type) {
1123                 case CONSTRAINT_TYPE_CHILDOF:
1124                 {
1125                         /* if this constraint is being added to a posechannel, make sure
1126                          * the constraint gets evaluated in pose-space */
1127                         if (ob->mode & OB_MODE_POSE) {
1128                                 con->ownspace = CONSTRAINT_SPACE_POSE;
1129                                 con->flag |= CONSTRAINT_SPACEONCE;
1130                         }
1131                 }
1132                         break;
1133                         
1134                 case CONSTRAINT_TYPE_PYTHON: // FIXME: this code is not really valid anymore
1135                 {
1136                         char *menustr;
1137                         int scriptint= 0;
1138 #ifndef DISABLE_PYTHON
1139                         /* popup a list of usable scripts */
1140                         menustr = buildmenu_pyconstraints(NULL, &scriptint);
1141                         // XXX scriptint = pupmenu(menustr);
1142                         MEM_freeN(menustr);
1143                         
1144                         /* only add constraint if a script was chosen */
1145                         if (scriptint) {
1146                                 /* add constraint */
1147                                 validate_pyconstraint_cb(con->data, &scriptint);
1148                                 
1149                                 /* make sure target allowance is set correctly */
1150                                 BPY_pyconstraint_update(ob, con);
1151                         }
1152 #endif
1153                 }
1154                 default:
1155                         break;
1156         }
1157         
1158         /* make sure all settings are valid - similar to above checks, but sometimes can be wrong */
1159         object_test_constraints(ob);
1160         
1161         if (ob->pose)
1162                 update_pose_constraint_flags(ob->pose);
1163         
1164         
1165         /* force depsgraph to get recalculated since new relationships added */
1166         DAG_scene_sort(scene);          /* sort order of objects */
1167         
1168         if ((ob->type==OB_ARMATURE) && (pchan)) {
1169                 ob->pose->flag |= POSE_RECALC;  /* sort pose channels */
1170                 DAG_id_flush_update(&ob->id, OB_RECALC_DATA|OB_RECALC_OB);
1171         }
1172         else
1173                 DAG_id_flush_update(&ob->id, OB_RECALC_DATA);
1174         
1175         /* notifiers for updates */
1176         WM_event_add_notifier(C, NC_OBJECT|ND_CONSTRAINT|NA_ADDED, ob);
1177         
1178         return OPERATOR_FINISHED;
1179 }
1180
1181 /* ------------------ */
1182
1183 /* dummy operator callback */
1184 static int object_constraint_add_exec(bContext *C, wmOperator *op)
1185 {
1186         ScrArea *sa= CTX_wm_area(C);
1187         Object *ob;
1188         int type= RNA_enum_get(op->ptr, "type");
1189         short with_targets= 0;
1190         
1191         /* get active object from context */
1192         if (sa->spacetype == SPACE_BUTS)
1193                 ob= CTX_data_pointer_get_type(C, "object", &RNA_Object).data;
1194         else
1195                 ob= CTX_data_active_object(C);
1196         
1197         if (!ob) {
1198                 BKE_report(op->reports, RPT_ERROR, "No active object to add constraint to.");
1199                 return OPERATOR_CANCELLED;
1200         }
1201                 
1202         /* hack: set constraint targets from selected objects in context is allowed when
1203          *              operator name included 'with_targets', since the menu doesn't allow multiple properties
1204          */
1205         if (strstr(op->idname, "with_targets"))
1206                 with_targets= 1;
1207
1208         return constraint_add_exec(C, op, ob, &ob->constraints, type, with_targets);
1209 }
1210
1211 /* dummy operator callback */
1212 static int pose_constraint_add_exec(bContext *C, wmOperator *op)
1213 {
1214         ScrArea *sa= CTX_wm_area(C);
1215         Object *ob;
1216         int type= RNA_enum_get(op->ptr, "type");
1217         short with_targets= 0;
1218         
1219         /* get active object from context */
1220         if (sa->spacetype == SPACE_BUTS)
1221                 ob= CTX_data_pointer_get_type(C, "object", &RNA_Object).data;
1222         else
1223                 ob= CTX_data_active_object(C);
1224         
1225         if (!ob) {
1226                 BKE_report(op->reports, RPT_ERROR, "No active object to add constraint to.");
1227                 return OPERATOR_CANCELLED;
1228         }
1229                 
1230         /* hack: set constraint targets from selected objects in context is allowed when
1231          *              operator name included 'with_targets', since the menu doesn't allow multiple properties
1232          */
1233         if (strstr(op->idname, "with_targets"))
1234                 with_targets= 1;
1235         
1236         return constraint_add_exec(C, op, ob, get_active_constraints(ob), type, with_targets);
1237 }
1238
1239 /* ------------------ */
1240
1241 void OBJECT_OT_constraint_add(wmOperatorType *ot)
1242 {
1243         /* identifiers */
1244         ot->name= "Add Constraint";
1245         ot->description = "Add a constraint to the active object.";
1246         ot->idname= "OBJECT_OT_constraint_add";
1247         
1248         /* api callbacks */
1249         ot->invoke= WM_menu_invoke;
1250         ot->exec= object_constraint_add_exec;
1251         ot->poll= ED_operator_object_active;
1252         
1253         /* flags */
1254         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
1255         
1256         /* properties */
1257         RNA_def_enum(ot->srna, "type", constraint_type_items, 0, "Type", "");
1258 }
1259
1260 void OBJECT_OT_constraint_add_with_targets(wmOperatorType *ot)
1261 {
1262         /* identifiers */
1263         ot->name= "Add Constraint (with Targets)";
1264         ot->description = "Add a constraint to the active object, with target (where applicable) set to the selected Objects/Bones.";
1265         ot->idname= "OBJECT_OT_constraint_add_with_targets";
1266         
1267         /* api callbacks */
1268         ot->invoke= WM_menu_invoke;
1269         ot->exec= object_constraint_add_exec;
1270         ot->poll= ED_operator_object_active;
1271         
1272         /* flags */
1273         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
1274         
1275         /* properties */
1276         RNA_def_enum(ot->srna, "type", constraint_type_items, 0, "Type", "");
1277 }
1278
1279 void POSE_OT_constraint_add(wmOperatorType *ot)
1280 {
1281         /* identifiers */
1282         ot->name= "Add Constraint";
1283         ot->description = "Add a constraint to the active bone.";
1284         ot->idname= "POSE_OT_constraint_add";
1285         
1286         /* api callbacks */
1287         ot->invoke= WM_menu_invoke;
1288         ot->exec= pose_constraint_add_exec;
1289         ot->poll= ED_operator_posemode;
1290         
1291         /* flags */
1292         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
1293         
1294         /* properties */
1295         RNA_def_enum(ot->srna, "type", constraint_type_items, 0, "Type", "");
1296 }
1297
1298 void POSE_OT_constraint_add_with_targets(wmOperatorType *ot)
1299 {
1300         /* identifiers */
1301         ot->name= "Add Constraint (with Targets)";
1302         ot->description = "Add a constraint to the active bone, with target (where applicable) set to the selected Objects/Bones.";
1303         ot->idname= "POSE_OT_constraint_add_with_targets";
1304         
1305         /* api callbacks */
1306         ot->invoke= WM_menu_invoke;
1307         ot->exec= pose_constraint_add_exec;
1308         ot->poll= ED_operator_posemode;
1309         
1310         /* flags */
1311         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
1312         
1313         /* properties */
1314         RNA_def_enum(ot->srna, "type", constraint_type_items, 0, "Type", "");
1315 }
1316
1317 /************************ IK Constraint operators *********************/
1318 /* NOTE: only for Pose-Channels */
1319 // TODO: should these be here, or back in editors/armature/poseobject.c again?
1320
1321 /* present menu with options + validation for targets to use */
1322 static int pose_ik_add_invoke(bContext *C, wmOperator *op, wmEvent *evt)
1323 {
1324         Object *ob= CTX_data_active_object(C);
1325         bPoseChannel *pchan= get_active_posechannel(ob);
1326         bConstraint *con= NULL;
1327         
1328         uiPopupMenu *pup;
1329         uiLayout *layout;
1330         Object *tar_ob= NULL;
1331         bPoseChannel *tar_pchan= NULL;
1332         
1333         /* must have active bone */
1334         if (ELEM(NULL, ob, pchan)) {
1335                 BKE_report(op->reports, RPT_ERROR, "Must have active bone to add IK Constraint to.");
1336                 return OPERATOR_CANCELLED;
1337         }
1338         
1339         /* bone must not have any constraints already */
1340         for (con= pchan->constraints.first; con; con= con->next) {
1341                 if (con->type==CONSTRAINT_TYPE_KINEMATIC) break;
1342         }
1343         if (con) {
1344                 BKE_report(op->reports, RPT_ERROR, "Bone already has IK Constraint.");
1345                 return OPERATOR_CANCELLED;
1346         }
1347         
1348         /* prepare popup menu to choose targetting options */
1349         pup= uiPupMenuBegin(C, "Add IK", 0);
1350         layout= uiPupMenuLayout(pup);
1351         
1352         /* the type of targets we'll set determines the menu entries to show... */
1353         if (get_new_constraint_target(C, CONSTRAINT_TYPE_KINEMATIC, &tar_ob, &tar_pchan, 0)) {
1354                 /* bone target, or object target? 
1355                  *      - the only thing that matters is that we want a target...
1356                  */
1357                 if (tar_pchan)
1358                         uiItemBooleanO(layout, "To Active Bone", 0, "POSE_OT_ik_add", "with_targets", 1);
1359                 else
1360                         uiItemBooleanO(layout, "To Active Object", 0, "POSE_OT_ik_add", "with_targets", 1);
1361         }
1362         else {
1363                 /* we have a choice of adding to a new empty, or not setting any target (targetless IK) */
1364                 uiItemBooleanO(layout, "To New Empty Object", 0, "POSE_OT_ik_add", "with_targets", 1);
1365                 uiItemBooleanO(layout, "Without Targets", 0, "POSE_OT_ik_add", "with_targets", 0);
1366         }
1367         
1368         /* finish building the menu, and process it (should result in calling self again) */
1369         uiPupMenuEnd(C, pup);
1370         
1371         return OPERATOR_CANCELLED;
1372 }
1373
1374 /* call constraint_add_exec() to add the IK constraint */
1375 static int pose_ik_add_exec(bContext *C, wmOperator *op)
1376 {
1377         Object *ob= CTX_data_active_object(C);
1378         int with_targets= RNA_boolean_get(op->ptr, "with_targets");
1379         
1380         /* add the constraint - all necessary checks should have been done by the invoke() callback already... */
1381         return constraint_add_exec(C, op, ob, get_active_constraints(ob), CONSTRAINT_TYPE_KINEMATIC, with_targets);
1382 }
1383
1384 void POSE_OT_ik_add(wmOperatorType *ot)
1385 {
1386         /* identifiers */
1387         ot->name= "Add IK to Bone";
1388         ot->description= "Add IK Constraint to the active Bone.";
1389         ot->idname= "POSE_OT_ik_add";
1390         
1391         /* api callbacks */
1392         ot->invoke= pose_ik_add_invoke;
1393         ot->exec= pose_ik_add_exec;
1394         ot->poll= ED_operator_posemode;
1395         
1396         /* flags */
1397         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
1398         
1399         /* properties */
1400         RNA_def_boolean(ot->srna, "with_targets", 1, "With Targets", "Assign IK Constraint with targets derived from the select bones/objects");
1401 }
1402
1403 /* ------------------ */
1404
1405 /* remove IK constraints from selected bones */
1406 static int pose_ik_clear_exec(bContext *C, wmOperator *op)
1407 {
1408         Object *ob= CTX_data_active_object(C);
1409         
1410         /* only remove IK Constraints */
1411         CTX_DATA_BEGIN(C, bPoseChannel*, pchan, selected_pchans) 
1412         {
1413                 bConstraint *con, *next;
1414                 
1415                 // TODO: should we be checking if these contraints were local before we try and remove them?
1416                 for (con= pchan->constraints.first; con; con= next) {
1417                         next= con->next;
1418                         if (con->type==CONSTRAINT_TYPE_KINEMATIC) {
1419                                 free_constraint_data(con);
1420                                 BLI_freelinkN(&pchan->constraints, con);
1421                         }
1422                 }
1423                 pchan->constflag &= ~(PCHAN_HAS_IK|PCHAN_HAS_TARGET);
1424         }
1425         CTX_DATA_END;
1426         
1427         /* */
1428         DAG_id_flush_update(&ob->id, OB_RECALC_DATA);
1429
1430         /* note, notifier might evolve */
1431         WM_event_add_notifier(C, NC_OBJECT|ND_CONSTRAINT|NA_REMOVED, ob);
1432         
1433         return OPERATOR_FINISHED;
1434 }
1435
1436 void POSE_OT_ik_clear(wmOperatorType *ot)
1437 {
1438         /* identifiers */
1439         ot->name= "Remove IK";
1440         ot->description= "Remove all IK Constraints from selected bones.";
1441         ot->idname= "POSE_OT_ik_clear";
1442         
1443         /* api callbacks */
1444         ot->exec= pose_ik_clear_exec;
1445         ot->poll= ED_operator_posemode;
1446         
1447         /* flags */
1448         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
1449 }
1450