2.5: Objects
[blender.git] / source / blender / editors / object / editconstraint.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
60 #ifndef DISABLE_PYTHON
61 #include "BPY_extern.h"
62 #endif
63
64 #include "WM_api.h"
65 #include "WM_types.h"
66
67 #include "RNA_access.h"
68 #include "RNA_define.h"
69 #include "RNA_enum_types.h"
70
71 #include "ED_object.h"
72 #include "ED_screen.h"
73
74 #include "object_intern.h"
75
76 /* XXX */
77 static void BIF_undo_push() {}
78 static void error() {}
79 static int okee() {return 0;}
80 static int pupmenu() {return 0;}
81
82 /* -------------- Get Active Constraint Data ---------------------- */
83
84 /* if object in posemode, active bone constraints, else object constraints */
85 ListBase *get_active_constraints (Object *ob)
86 {
87         if (ob == NULL)
88                 return NULL;
89
90         if (ob->flag & OB_POSEMODE) {
91                 bPoseChannel *pchan;
92                 
93                 pchan = get_active_posechannel(ob);
94                 if (pchan)
95                         return &pchan->constraints;
96         }
97         else 
98                 return &ob->constraints;
99
100         return NULL;
101 }
102
103 /* single constraint */
104 bConstraint *get_active_constraint (Object *ob)
105 {
106         ListBase *lb= get_active_constraints(ob);
107
108         if (lb) {
109                 bConstraint *con;
110                 
111                 for (con= lb->first; con; con=con->next) {
112                         if (con->flag & CONSTRAINT_ACTIVE)
113                                 return con;
114                 }
115         }
116         
117         return NULL;
118 }
119 /* -------------- Constraint Management (Add New, Remove, Rename) -------------------- */
120 /* ------------- PyConstraints ------------------ */
121
122 /* this callback sets the text-file to be used for selected menu item */
123 void validate_pyconstraint_cb (void *arg1, void *arg2)
124 {
125         bPythonConstraint *data = arg1;
126         Text *text= NULL;
127         int index = *((int *)arg2);
128         int i;
129         
130         /* exception for no script */
131         if (index) {
132                 /* innovative use of a for...loop to search */
133                 for (text=G.main->text.first, i=1; text && index!=i; i++, text=text->id.next);
134         }
135         data->text = text;
136 }
137
138 #ifndef DISABLE_PYTHON
139 /* this returns a string for the list of usable pyconstraint script names */
140 char *buildmenu_pyconstraints (Text *con_text, int *pyconindex)
141 {
142         DynStr *pupds= BLI_dynstr_new();
143         Text *text;
144         char *str;
145         char buf[64];
146         int i;
147         
148         /* add title first */
149         sprintf(buf, "Scripts: %%t|[None]%%x0|");
150         BLI_dynstr_append(pupds, buf);
151         
152         /* init active-index first */
153         if (con_text == NULL)
154                 *pyconindex= 0;
155         
156         /* loop through markers, adding them */
157         for (text=G.main->text.first, i=1; text; i++, text=text->id.next) {
158                 /* this is important to ensure that right script is shown as active */
159                 if (text == con_text) *pyconindex = i;
160                 
161                 /* only include valid pyconstraint scripts */
162                 if (BPY_is_pyconstraint(text)) {
163                         BLI_dynstr_append(pupds, text->id.name+2);
164                         
165                         sprintf(buf, "%%x%d", i);
166                         BLI_dynstr_append(pupds, buf);
167                         
168                         if (text->id.next)
169                                 BLI_dynstr_append(pupds, "|");
170                 }
171         }
172         
173         /* convert to normal MEM_malloc'd string */
174         str= BLI_dynstr_get_cstring(pupds);
175         BLI_dynstr_free(pupds);
176         
177         return str;
178 }
179 #endif /* DISABLE_PYTHON */
180
181 /* this callback gets called when the 'refresh' button of a pyconstraint gets pressed */
182 void update_pyconstraint_cb (void *arg1, void *arg2)
183 {
184         Object *owner= (Object *)arg1;
185         bConstraint *con= (bConstraint *)arg2;
186 #ifndef DISABLE_PYTHON
187         if (owner && con)
188                 BPY_pyconstraint_update(owner, con);
189 #endif
190 }
191
192 /* Creates a new constraint, initialises its data, and returns it */
193 bConstraint *add_new_constraint (short type)
194 {
195         bConstraint *con;
196         bConstraintTypeInfo *cti;
197
198         con = MEM_callocN(sizeof(bConstraint), "Constraint");
199         
200         /* Set up a generic constraint datablock */
201         con->type = type;
202         con->flag |= CONSTRAINT_EXPAND;
203         con->enforce = 1.0F;
204         strcpy(con->name, "Const");
205         
206         /* Load the data for it */
207         cti = constraint_get_typeinfo(con);
208         if (cti) {
209                 con->data = MEM_callocN(cti->size, cti->structName);
210                 
211                 /* only constraints that change any settings need this */
212                 if (cti->new_data)
213                         cti->new_data(con->data);
214         }
215         
216         return con;
217 }
218
219 /* Adds the given constraint to the Object-level set of constraints for the given Object */
220 void add_constraint_to_object (bConstraint *con, Object *ob)
221 {
222         ListBase *list;
223         list = &ob->constraints;
224         
225         if (list) {
226                 unique_constraint_name(con, list);
227                 BLI_addtail(list, con);
228                 
229                 if (proxylocked_constraints_owner(ob, NULL))
230                         con->flag |= CONSTRAINT_PROXY_LOCAL;
231                 
232                 con->flag |= CONSTRAINT_ACTIVE;
233                 for (con= con->prev; con; con= con->prev)
234                         con->flag &= ~CONSTRAINT_ACTIVE;
235         }
236 }
237
238 /* helper function for add_constriant - sets the last target for the active constraint */
239 static void set_constraint_nth_target (bConstraint *con, Object *target, char subtarget[], int index)
240 {
241         bConstraintTypeInfo *cti= constraint_get_typeinfo(con);
242         ListBase targets = {NULL, NULL};
243         bConstraintTarget *ct;
244         int num_targets, i;
245         
246         if (cti && cti->get_constraint_targets) {
247                 cti->get_constraint_targets(con, &targets);
248                 num_targets= BLI_countlist(&targets);
249                 
250                 if (index < 0) {
251                         if (abs(index) < num_targets)
252                                 index= num_targets - abs(index);
253                         else
254                                 index= num_targets - 1;
255                 }
256                 else if (index >= num_targets) {
257                         index= num_targets - 1;
258                 }
259                 
260                 for (ct=targets.first, i=0; ct; ct= ct->next, i++) {
261                         if (i == index) {
262                                 ct->tar= target;
263                                 strcpy(ct->subtarget, subtarget);
264                                 break;
265                         }
266                 }
267                 
268                 if (cti->flush_constraint_targets)
269                         cti->flush_constraint_targets(con, &targets, 0);
270         }
271 }
272
273 /* context: active object in posemode, active channel, optional selected channel */
274 void add_constraint (Scene *scene, View3D *v3d, short only_IK)
275 {
276         Object *ob= OBACT, *obsel=NULL;
277         bPoseChannel *pchanact=NULL, *pchansel=NULL;
278         bConstraint *con=NULL;
279         Base *base;
280         short nr;
281         
282         /* paranoia checks */
283         if ((ob==NULL) || (ob==scene->obedit)) 
284                 return;
285
286         if ((ob->pose) && (ob->flag & OB_POSEMODE)) {
287                 bArmature *arm= ob->data;
288                 
289                 /* find active channel */
290                 pchanact= get_active_posechannel(ob);
291                 if (pchanact==NULL) 
292                         return;
293                 
294                 /* find selected bone */
295                 for (pchansel=ob->pose->chanbase.first; pchansel; pchansel=pchansel->next) {
296                         if (pchansel != pchanact) {
297                                 if (pchansel->bone->flag & BONE_SELECTED)  {
298                                         if (pchansel->bone->layer & arm->layer)
299                                                 break;
300                                 }
301                         }
302                 }
303         }
304         
305         /* find selected object */
306         for (base= FIRSTBASE; base; base= base->next) {
307                 if ((TESTBASE(v3d, base)) && (base->object!=ob)) 
308                         obsel= base->object;
309         }
310         
311         /* the only_IK caller has checked for posemode! */
312         if (only_IK) {
313                 for (con= pchanact->constraints.first; con; con= con->next) {
314                         if (con->type==CONSTRAINT_TYPE_KINEMATIC) break;
315                 }
316                 if (con) {
317                         error("Pose Channel already has IK");
318                         return;
319                 }
320                 
321                 if (pchansel)
322                         nr= pupmenu("Add IK Constraint%t|To Active Bone%x10");
323                 else if (obsel)
324                         nr= pupmenu("Add IK Constraint%t|To Active Object%x10");
325                 else 
326                         nr= pupmenu("Add IK Constraint%t|To New Empty Object%x10|Without Target%x11");
327         }
328         else {
329                 if (pchanact) {
330                         if (pchansel)
331                                 nr= pupmenu("Add Constraint to Active Bone%t|Child Of%x19|Transformation%x20|%l|Copy Location%x1|Copy Rotation%x2|Copy Scale%x8|%l|Limit Location%x13|Limit Rotation%x14|Limit Scale%x15|Limit Distance%x21|%l|Track To%x3|Floor%x4|Locked Track%x5|Stretch To%x7|%l|Action%x16|Script%x18");
332                         else if ((obsel) && (obsel->type==OB_CURVE))
333                                 nr= pupmenu("Add Constraint to Active Object%t|Child Of%x19|Transformation%x20|%l|Copy Location%x1|Copy Rotation%x2|Copy Scale%x8|%l|Limit Location%x13|Limit Rotation%x14|Limit Scale%x15|Limit Distance%x21|%l|Track To%x3|Floor%x4|Locked Track%x5|Follow Path%x6|Clamp To%x17|Stretch To%x7|%l|Action%x16|Script%x18");
334                         else if ((obsel) && (obsel->type==OB_MESH))
335                                 nr= pupmenu("Add Constraint to Active Object%t|Child Of%x19|Transformation%x20|%l|Copy Location%x1|Copy Rotation%x2|Copy Scale%x8|%l|Limit Location%x13|Limit Rotation%x14|Limit Scale%x15|Limit Distance%x21|%l|Track To%x3|Floor%x4|Locked Track%x5|Shrinkwrap%x22|Stretch To%x7|%l|Action%x16|Script%x18");
336                         else if (obsel)
337                                 nr= pupmenu("Add Constraint to Active Object%t|Child Of%x19|Transformation%x20|%l|Copy Location%x1|Copy Rotation%x2|Copy Scale%x8|%l|Limit Location%x13|Limit Rotation%x14|Limit Scale%x15|Limit Distance%x21|%l|Track To%x3|Floor%x4|Locked Track%x5|Stretch To%x7|%l|Action%x16|Script%x18");
338                         else
339                                 nr= pupmenu("Add Constraint to New Empty Object%t|Child Of%x19|Transformation%x20|%l|Copy Location%x1|Copy Rotation%x2|Copy Scale%x8|%l|Limit Location%x13|Limit Rotation%x14|Limit Scale%x15|Limit Distance%x21|%l|Track To%x3|Floor%x4|Locked Track%x5|Stretch To%x7|%l|Action%x16|Script%x18");
340                 }
341                 else {
342                         if ((obsel) && (obsel->type==OB_CURVE))
343                                 nr= pupmenu("Add Constraint to Active Object%t|Child Of%x19|Transformation%x20|%l|Copy Location%x1|Copy Rotation%x2|Copy Scale%x8|%l|Limit Location%x13|Limit Rotation%x14|Limit Scale%x15|Limit Distance%x21|%l|Track To%x3|Floor%x4|Locked Track%x5|Follow Path%x6|Clamp To%x17|%l|Action%x16|Script%x18");
344                         else if ((obsel) && (obsel->type==OB_MESH))
345                                 nr= pupmenu("Add Constraint to Active Object%t|Child Of%x19|Transformation%x20|%l|Copy Location%x1|Copy Rotation%x2|Copy Scale%x8|%l|Limit Location%x13|Limit Rotation%x14|Limit Scale%x15|Limit Distance%x21|%l|Track To%x3|Floor%x4|Locked Track%x5|Shrinkwrap%x22|%l|Action%x16|Script%x18");
346                         else if (obsel)
347                                 nr= pupmenu("Add Constraint to Active Object%t|Child Of%x19|Transformation%x20|%l|Copy Location%x1|Copy Rotation%x2|Copy Scale%x8|%l|Limit Location%x13|Limit Rotation%x14|Limit Scale%x15|Limit Distance%x21|%l|Track To%x3|Floor%x4|Locked Track%x5|%l|Action%x16|Script%x18");
348                         else
349                                 nr= pupmenu("Add Constraint to New Empty Object%t|Child Of%x19|Transformation%x20|%l|Copy Location%x1|Copy Rotation%x2|Copy Scale%x8|%l|Limit Location%x13|Limit Rotation%x14|Limit Scale%x15|Limit Distance%x21|%l|Track To%x3|Floor%x4|Locked Track%x5|%l|Action%x16|Script%x18");
350                 }
351         }
352         
353         if (nr < 1) return;
354         
355         /* handle IK separate */
356         if (nr==10 || nr==11) {
357                 /* ik - prevent weird chains... */
358                 if (pchansel) {
359                         bPoseChannel *pchan= pchanact;
360                         while (pchan) {
361                                 if (pchan==pchansel) break;
362                                 pchan= pchan->parent;
363                         }
364                         if (pchan) {
365                                 error("IK root cannot be linked to IK tip");
366                                 return;
367                         }
368                         
369                         pchan= pchansel;
370                         while (pchan) {
371                                 if (pchan==pchanact) break;
372                                 pchan= pchan->parent;
373                         }
374                         if (pchan) {
375                                 error("IK tip cannot be linked to IK root");
376                                 return;
377                         }               
378                 }
379                 
380                 con = add_new_constraint(CONSTRAINT_TYPE_KINEMATIC);
381                 BLI_addtail(&pchanact->constraints, con);
382                 unique_constraint_name(con, &pchanact->constraints);
383                 pchanact->constflag |= PCHAN_HAS_IK;    /* for draw, but also for detecting while pose solving */
384                 if (nr==11) 
385                         pchanact->constflag |= PCHAN_HAS_TARGET;
386                 if (proxylocked_constraints_owner(ob, pchanact))
387                         con->flag |= CONSTRAINT_PROXY_LOCAL;
388         }
389         else {
390                 /* normal constraints - add data */
391                 if (nr==1) con = add_new_constraint(CONSTRAINT_TYPE_LOCLIKE);
392                 else if (nr==2) con = add_new_constraint(CONSTRAINT_TYPE_ROTLIKE);
393                 else if (nr==3) con = add_new_constraint(CONSTRAINT_TYPE_TRACKTO);
394                 else if (nr==4) con = add_new_constraint(CONSTRAINT_TYPE_MINMAX);
395                 else if (nr==5) con = add_new_constraint(CONSTRAINT_TYPE_LOCKTRACK);
396                 else if (nr==6) {
397                         Curve *cu= obsel->data;
398                         cu->flag |= CU_PATH;
399                         con = add_new_constraint(CONSTRAINT_TYPE_FOLLOWPATH);
400                 }
401                 else if (nr==7) con = add_new_constraint(CONSTRAINT_TYPE_STRETCHTO);
402                 else if (nr==8) con = add_new_constraint(CONSTRAINT_TYPE_SIZELIKE);
403                 else if (nr==13) con = add_new_constraint(CONSTRAINT_TYPE_LOCLIMIT);
404                 else if (nr==14) con = add_new_constraint(CONSTRAINT_TYPE_ROTLIMIT);
405                 else if (nr==15) con = add_new_constraint(CONSTRAINT_TYPE_SIZELIMIT);
406                 else if (nr==16) {
407                         /* TODO: add a popup-menu to display list of available actions to use (like for pyconstraints) */
408                         con = add_new_constraint(CONSTRAINT_TYPE_ACTION);
409                 }
410                 else if (nr==17) {
411                         Curve *cu= obsel->data;
412                         cu->flag |= CU_PATH;
413                         con = add_new_constraint(CONSTRAINT_TYPE_CLAMPTO);
414                 }
415                 else if (nr==18) {      
416                         char *menustr;
417                         int scriptint= 0;
418 #ifndef DISABLE_PYTHON
419                         /* popup a list of usable scripts */
420                         menustr = buildmenu_pyconstraints(NULL, &scriptint);
421                         scriptint = pupmenu(menustr);
422                         MEM_freeN(menustr);
423                         
424                         /* only add constraint if a script was chosen */
425                         if (scriptint) {
426                                 /* add constraint */
427                                 con = add_new_constraint(CONSTRAINT_TYPE_PYTHON);
428                                 validate_pyconstraint_cb(con->data, &scriptint);
429                                 
430                                 /* make sure target allowance is set correctly */
431                                 BPY_pyconstraint_update(ob, con);
432                         }
433 #endif
434                 }
435                 else if (nr==19) {
436                         con = add_new_constraint(CONSTRAINT_TYPE_CHILDOF);
437                 
438                         /* if this constraint is being added to a posechannel, make sure
439                          * the constraint gets evaluated in pose-space
440                          */
441                         if (pchanact) {
442                                 con->ownspace = CONSTRAINT_SPACE_POSE;
443                                 con->flag |= CONSTRAINT_SPACEONCE;
444                         }
445                 }
446                 else if (nr==20) con = add_new_constraint(CONSTRAINT_TYPE_TRANSFORM);
447                 else if (nr==21) con = add_new_constraint(CONSTRAINT_TYPE_DISTLIMIT);
448                 else if (nr==22) con = add_new_constraint(CONSTRAINT_TYPE_SHRINKWRAP);
449                 
450                 if (con==NULL) return;  /* paranoia */
451                 
452                 if (pchanact) {
453                         BLI_addtail(&pchanact->constraints, con);
454                         unique_constraint_name(con, &pchanact->constraints);
455                         pchanact->constflag |= PCHAN_HAS_CONST; /* for draw */
456                         if (proxylocked_constraints_owner(ob, pchanact))
457                                 con->flag |= CONSTRAINT_PROXY_LOCAL;
458                 }
459                 else {
460                         BLI_addtail(&ob->constraints, con);
461                         unique_constraint_name(con, &ob->constraints);
462                         if (proxylocked_constraints_owner(ob, NULL))
463                                 con->flag |= CONSTRAINT_PROXY_LOCAL;
464                 }
465         }
466         
467         /* set the target */
468         if (pchansel) {
469                 set_constraint_nth_target(con, ob, pchansel->name, 0);
470         }
471         else if (obsel) {
472                 set_constraint_nth_target(con, obsel, "", 0);
473         }
474         else if (ELEM4(nr, 11, 13, 14, 15)==0) {        /* add new empty as target */
475                 Base *base= BASACT, *newbase;
476                 Object *obt;
477                 
478                 obt= add_object(scene, OB_EMPTY);
479                 /* set layers OK */
480                 newbase= BASACT;
481                 newbase->lay= base->lay;
482                 obt->lay= newbase->lay;
483                 
484                 /* transform cent to global coords for loc */
485                 if (pchanact) {
486                         if (only_IK)
487                                 VecMat4MulVecfl(obt->loc, ob->obmat, pchanact->pose_tail);
488                         else
489                                 VecMat4MulVecfl(obt->loc, ob->obmat, pchanact->pose_head);
490                 }
491                 else
492                         VECCOPY(obt->loc, ob->obmat[3]);
493                 
494                 set_constraint_nth_target(con, obt, "", 0);
495                 
496                 /* restore, add_object sets active */
497                 BASACT= base;
498                 base->flag |= SELECT;
499         }
500         
501         /* active flag */
502         con->flag |= CONSTRAINT_ACTIVE;
503         for (con= con->prev; con; con= con->prev)
504                 con->flag &= ~CONSTRAINT_ACTIVE;
505
506         DAG_scene_sort(scene);          // sort order of objects
507         
508         if (pchanact) {
509                 ob->pose->flag |= POSE_RECALC;  // sort pose channels
510                 DAG_object_flush_update(scene, ob, OB_RECALC_DATA);     // and all its relations
511         }
512         else
513                 DAG_object_flush_update(scene, ob, OB_RECALC_OB);       // and all its relations
514
515         if (only_IK)
516                 BIF_undo_push("Add IK Constraint");
517         else
518                 BIF_undo_push("Add Constraint");
519
520 }
521
522 /* Remove all constraints from the active object */
523 void ob_clear_constraints (Scene *scene)
524 {
525         Object *ob= OBACT;
526         
527         /* paranoia checks */
528         if ((ob==NULL) || (ob==scene->obedit) || (ob->flag & OB_POSEMODE)) 
529                 return;
530         
531         /* get user permission */
532         if (okee("Clear Constraints")==0) 
533                 return;
534         
535         /* do freeing */
536         free_constraints(&ob->constraints);
537         
538         /* do updates */
539         DAG_object_flush_update(scene, ob, OB_RECALC_OB);
540         
541         BIF_undo_push("Clear Constraint(s)");
542 }
543
544 /* ------------- Constraint Sanity Testing ------------------- */
545
546 /* checks validity of object pointers, and NULLs,
547  * if Bone doesnt exist it sets the CONSTRAINT_DISABLE flag 
548  */
549 static void test_constraints (Object *owner, const char substring[])
550 {
551         bConstraint *curcon;
552         ListBase *conlist= NULL;
553         int type;
554         
555         if (owner==NULL) return;
556         
557         /* Check parents */
558         if (strlen(substring)) {
559                 switch (owner->type) {
560                         case OB_ARMATURE:
561                                 type = CONSTRAINT_OBTYPE_BONE;
562                                 break;
563                         default:
564                                 type = CONSTRAINT_OBTYPE_OBJECT;
565                                 break;
566                 }
567         }
568         else
569                 type = CONSTRAINT_OBTYPE_OBJECT;
570         
571         /* Get the constraint list for this object */
572         switch (type) {
573                 case CONSTRAINT_OBTYPE_OBJECT:
574                         conlist = &owner->constraints;
575                         break;
576                 case CONSTRAINT_OBTYPE_BONE:
577                         {
578                                 Bone *bone;
579                                 bPoseChannel *chan;
580                                 
581                                 bone = get_named_bone( ((bArmature *)owner->data), substring );
582                                 chan = get_pose_channel(owner->pose, substring);
583                                 if (bone && chan) {
584                                         conlist = &chan->constraints;
585                                 }
586                         }
587                         break;
588         }
589         
590         /* Check all constraints - is constraint valid? */
591         if (conlist) {
592                 for (curcon = conlist->first; curcon; curcon=curcon->next) {
593                         bConstraintTypeInfo *cti= constraint_get_typeinfo(curcon);
594                         ListBase targets = {NULL, NULL};
595                         bConstraintTarget *ct;
596                         
597                         /* clear disabled-flag first */
598                         curcon->flag &= ~CONSTRAINT_DISABLE;
599
600                         if (curcon->type == CONSTRAINT_TYPE_KINEMATIC) {
601                                 bKinematicConstraint *data = curcon->data;
602                                 
603                                 /* bad: we need a separate set of checks here as poletarget is 
604                                  *              optional... otherwise poletarget must exist too or else
605                                  *              the constraint is deemed invalid
606                                  */
607                                 if (exist_object(data->tar) == 0) {
608                                         data->tar = NULL;
609                                         curcon->flag |= CONSTRAINT_DISABLE;
610                                 }
611                                 else if (data->tar == owner) {
612                                         if (!get_named_bone(get_armature(owner), data->subtarget)) {
613                                                 curcon->flag |= CONSTRAINT_DISABLE;
614                                         }
615                                 }
616                                 
617                                 if (data->poletar) {
618                                         if (exist_object(data->poletar) == 0) {
619                                                 data->poletar = NULL;
620                                                 curcon->flag |= CONSTRAINT_DISABLE;
621                                         }
622                                         else if (data->poletar == owner) {
623                                                 if (!get_named_bone(get_armature(owner), data->polesubtarget)) {
624                                                         curcon->flag |= CONSTRAINT_DISABLE;
625                                                 }
626                                         }
627                                 }
628                                 
629                                 /* targets have already been checked for this */
630                                 continue;
631                         }
632                         else if (curcon->type == CONSTRAINT_TYPE_ACTION) {
633                                 bActionConstraint *data = curcon->data;
634                                 
635                                 /* validate action */
636                                 if (data->act == NULL) 
637                                         curcon->flag |= CONSTRAINT_DISABLE;
638                         }
639                         else if (curcon->type == CONSTRAINT_TYPE_FOLLOWPATH) {
640                                 bFollowPathConstraint *data = curcon->data;
641                                 
642                                 /* don't allow track/up axes to be the same */
643                                 if (data->upflag==data->trackflag)
644                                         curcon->flag |= CONSTRAINT_DISABLE;
645                                 if (data->upflag+3==data->trackflag)
646                                         curcon->flag |= CONSTRAINT_DISABLE;
647                         }
648                         else if (curcon->type == CONSTRAINT_TYPE_TRACKTO) {
649                                 bTrackToConstraint *data = curcon->data;
650                                 
651                                 /* don't allow track/up axes to be the same */
652                                 if (data->reserved2==data->reserved1)
653                                         curcon->flag |= CONSTRAINT_DISABLE;
654                                 if (data->reserved2+3==data->reserved1)
655                                         curcon->flag |= CONSTRAINT_DISABLE;
656                         }
657                         else if (curcon->type == CONSTRAINT_TYPE_LOCKTRACK) {
658                                 bLockTrackConstraint *data = curcon->data;
659                                 
660                                 if (data->lockflag==data->trackflag)
661                                         curcon->flag |= CONSTRAINT_DISABLE;
662                                 if (data->lockflag+3==data->trackflag)
663                                         curcon->flag |= CONSTRAINT_DISABLE;
664                         }
665                         
666                         /* Check targets for constraints */
667                         if (cti && cti->get_constraint_targets) {
668                                 cti->get_constraint_targets(curcon, &targets);
669                                 
670                                 /* disable and clear constraints targets that are incorrect */
671                                 for (ct= targets.first; ct; ct= ct->next) {
672                                         /* general validity checks (for those constraints that need this) */
673                                         if (exist_object(ct->tar) == 0) {
674                                                 ct->tar = NULL;
675                                                 curcon->flag |= CONSTRAINT_DISABLE;
676                                         }
677                                         else if (ct->tar == owner) {
678                                                 if (!get_named_bone(get_armature(owner), ct->subtarget)) {
679                                                         curcon->flag |= CONSTRAINT_DISABLE;
680                                                 }
681                                         }
682                                         
683                                         /* target checks for specific constraints */
684                                         if (ELEM(curcon->type, CONSTRAINT_TYPE_FOLLOWPATH, CONSTRAINT_TYPE_CLAMPTO)) {
685                                                 if (ct->tar) {
686                                                         if (ct->tar->type != OB_CURVE) {
687                                                                 ct->tar= NULL;
688                                                                 curcon->flag |= CONSTRAINT_DISABLE;
689                                                         }
690                                                         else {
691                                                                 Curve *cu= ct->tar->data;
692                                                                 
693                                                                 /* auto-set 'Path' setting on curve so this works  */
694                                                                 cu->flag |= CU_PATH;
695                                                         }
696                                                 }                                               
697                                         }
698                                 }       
699                                 
700                                 /* free any temporary targets */
701                                 if (cti->flush_constraint_targets)
702                                         cti->flush_constraint_targets(curcon, &targets, 0);
703                         }
704                 }
705         }
706 }
707
708 static void test_bonelist_constraints (Object *owner, ListBase *list)
709 {
710         Bone *bone;
711
712         for (bone = list->first; bone; bone = bone->next) {
713                 test_constraints(owner, bone->name);
714                 test_bonelist_constraints(owner, &bone->childbase);
715         }
716 }
717
718 void object_test_constraints (Object *owner)
719 {
720         test_constraints(owner, "");
721
722         if (owner->type==OB_ARMATURE) {
723                 bArmature *arm= get_armature(owner);
724                 
725                 if (arm)
726                         test_bonelist_constraints(owner, &arm->bonebase);
727         }
728 }
729
730 /* ********************** CONSTRAINT-SPECIFIC STUFF ********************* */
731
732 /* ------------- Child-Of Constraint ------------------ */
733
734 /* ChildOf Constraint - set inverse callback */
735 static int childof_set_inverse_exec (bContext *C, wmOperator *op)
736 {
737         PointerRNA ptr= CTX_data_pointer_get_type(C, "constraint", &RNA_ChildOfConstraint);
738         Scene *scene= CTX_data_scene(C);
739         Object *ob= ptr.id.data;
740         bConstraint *con= ptr.data;
741         bChildOfConstraint *data= (bChildOfConstraint *)con->data;
742         bPoseChannel *pchan= NULL;
743
744         /* try to find a pose channel */
745         // TODO: get from context instead?
746         if (ob && ob->pose)
747                 pchan= get_active_posechannel(ob);
748         
749         /* calculate/set inverse matrix */
750         if (pchan) {
751                 float pmat[4][4], cinf;
752                 float imat[4][4], tmat[4][4];
753                 
754                 /* make copy of pchan's original pose-mat (for use later) */
755                 Mat4CpyMat4(pmat, pchan->pose_mat);
756                 
757                 /* disable constraint for pose to be solved without it */
758                 cinf= con->enforce;
759                 con->enforce= 0.0f;
760                 
761                 /* solve pose without constraint */
762                 where_is_pose(scene, ob);
763                 
764                 /* determine effect of constraint by removing the newly calculated 
765                  * pchan->pose_mat from the original pchan->pose_mat, thus determining 
766                  * the effect of the constraint
767                  */
768                 Mat4Invert(imat, pchan->pose_mat);
769                 Mat4MulMat4(tmat, imat, pmat);
770                 Mat4Invert(data->invmat, tmat);
771                 
772                 /* recalculate pose with new inv-mat */
773                 con->enforce= cinf;
774                 where_is_pose(scene, ob);
775         }
776         else if (ob) {
777                 Object workob;
778                 /* use what_does_parent to find inverse - just like for normal parenting.
779                  * NOTE: what_does_parent uses a static workob defined in object.c 
780                  */
781                 what_does_parent(scene, ob, &workob);
782                 Mat4Invert(data->invmat, workob.obmat);
783         }
784         else
785                 Mat4One(data->invmat);
786                 
787         WM_event_add_notifier(C, NC_OBJECT|ND_CONSTRAINT, ob);
788                 
789         return OPERATOR_FINISHED;
790 }
791
792 void CONSTRAINT_OT_childof_set_inverse (wmOperatorType *ot)
793 {
794         /* identifiers */
795         ot->name= "Set Inverse";
796         ot->idname= "CONSTRAINT_OT_childof_set_inverse";
797         ot->description= "Set inverse correction for ChildOf constraint.";
798         
799         ot->exec= childof_set_inverse_exec;
800         
801         /* flags */
802         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
803 }
804
805
806 /* ChildOf Constraint - clear inverse callback */
807 static int childof_clear_inverse_exec (bContext *C, wmOperator *op)
808 {
809         PointerRNA ptr= CTX_data_pointer_get_type(C, "constraint", &RNA_ChildOfConstraint);
810         Object *ob= ptr.id.data;
811         bConstraint *con= ptr.data;
812         bChildOfConstraint *data= (bChildOfConstraint *)con->data;
813         
814         /* simply clear the matrix */
815         Mat4One(data->invmat);
816         
817         WM_event_add_notifier(C, NC_OBJECT|ND_CONSTRAINT, ob);
818         
819         return OPERATOR_FINISHED;
820 }
821
822 void CONSTRAINT_OT_childof_clear_inverse (wmOperatorType *ot)
823 {
824         /* identifiers */
825         ot->name= "Clear Inverse";
826         ot->idname= "CONSTRAINT_OT_childof_clear_inverse";
827         ot->description= "Clear inverse correction for ChildOf constraint.";
828         
829         ot->exec= childof_clear_inverse_exec;
830         
831         /* flags */
832         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
833 }
834
835 /***************************** BUTTONS ****************************/
836
837 /* Rename the given constraint, con already has the new name */
838 void ED_object_constraint_rename(Object *ob, bConstraint *con, char *oldname)
839 {
840         bConstraint *tcon;
841         ListBase *conlist= NULL;
842         int from_object= 0;
843         
844         /* get context by searching for con (primitive...) */
845         for (tcon= ob->constraints.first; tcon; tcon= tcon->next) {
846                 if (tcon==con)
847                         break;
848         }
849         
850         if (tcon) {
851                 conlist= &ob->constraints;
852                 from_object= 1;
853         }
854         else if (ob->pose) {
855                 bPoseChannel *pchan;
856                 
857                 for (pchan=ob->pose->chanbase.first; pchan; pchan=pchan->next) {
858                         for (tcon= pchan->constraints.first; tcon; tcon= tcon->next) {
859                                 if (tcon==con)
860                                         break;
861                         }
862                         if (tcon) 
863                                 break;
864                 }
865                 
866                 if (tcon) {
867                         conlist= &pchan->constraints;
868                 }
869         }
870         
871         if (conlist==NULL) {
872                 printf("rename constraint failed\n");   /* should not happen in UI */
873                 return;
874         }
875         
876         /* first make sure it's a unique name within context */
877         unique_constraint_name(con, conlist);
878 }
879
880
881
882
883 void ED_object_constraint_set_active(Object *ob, bConstraint *con)
884 {
885         ListBase *lb;
886         bConstraint *origcon= con;
887         
888         /* lets be nice and escape if its active already */
889         if(con && (con->flag & CONSTRAINT_ACTIVE))
890                 return ;
891         
892         lb= get_active_constraints(ob);
893         if(lb == NULL)
894                 return;
895         
896         for(con= lb->first; con; con= con->next) {
897                 if(con==origcon) con->flag |= CONSTRAINT_ACTIVE;
898                 else con->flag &= ~CONSTRAINT_ACTIVE;
899         }
900 }
901
902 static int constraint_delete_exec (bContext *C, wmOperator *op)
903 {
904         PointerRNA ptr= CTX_data_pointer_get_type(C, "constraint", &RNA_Constraint);
905         Object *ob= ptr.id.data;
906         bConstraint *con= ptr.data;
907         ListBase *lb;
908         
909         /* remove constraint itself */
910         lb= get_active_constraints(ob);
911         free_constraint_data(con);
912         BLI_freelinkN(lb, con);
913         
914         ED_object_constraint_set_active(ob, NULL);
915         WM_event_add_notifier(C, NC_OBJECT|ND_CONSTRAINT, ob);
916
917         return OPERATOR_FINISHED;
918 }
919
920 void CONSTRAINT_OT_delete (wmOperatorType *ot)
921 {
922         /* identifiers */
923         ot->name= "Delete Constraint";
924         ot->idname= "CONSTRAINT_OT_delete";
925         ot->description= "Remove constraitn from constraint stack.";
926         
927         /* callbacks */
928         ot->exec= constraint_delete_exec;
929         
930         /* flags */
931         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO; 
932 }
933
934 static int constraint_move_down_exec (bContext *C, wmOperator *op)
935 {
936         PointerRNA ptr= CTX_data_pointer_get_type(C, "constraint", &RNA_Constraint);
937         Object *ob= ptr.id.data;
938         bConstraint *con= ptr.data;
939         
940         if (con->next) {
941                 ListBase *conlist= get_active_constraints(ob);
942                 bConstraint *nextCon= con->next;
943                 
944                 /* insert the nominated constraint after the one that used to be after it */
945                 BLI_remlink(conlist, con);
946                 BLI_insertlinkafter(conlist, nextCon, con);
947                 
948                 WM_event_add_notifier(C, NC_OBJECT|ND_CONSTRAINT, ob);
949                 
950                 return OPERATOR_FINISHED;
951         }
952         
953         return OPERATOR_CANCELLED;
954 }
955
956 void CONSTRAINT_OT_move_down (wmOperatorType *ot)
957 {
958         /* identifiers */
959         ot->name= "Move Constraint Down";
960         ot->idname= "CONSTRAINT_OT_move_down";
961         ot->description= "Move constraint down constraint stack.";
962         
963         /* callbacks */
964         ot->exec= constraint_move_down_exec;
965         
966         /* flags */
967         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO; 
968 }
969
970
971 static int constraint_move_up_exec (bContext *C, wmOperator *op)
972 {
973         PointerRNA ptr= CTX_data_pointer_get_type(C, "constraint", &RNA_Constraint);
974         Object *ob= ptr.id.data;
975         bConstraint *con= ptr.data;
976         
977         if (con->prev) {
978                 ListBase *conlist= get_active_constraints(ob);
979                 bConstraint *prevCon= con->prev;
980                 
981                 /* insert the nominated constraint before the one that used to be before it */
982                 BLI_remlink(conlist, con);
983                 BLI_insertlinkbefore(conlist, prevCon, con);
984                 
985                 WM_event_add_notifier(C, NC_OBJECT|ND_CONSTRAINT, ob);
986                 
987                 return OPERATOR_FINISHED;
988         }
989         
990         return OPERATOR_CANCELLED;
991 }
992
993 void CONSTRAINT_OT_move_up (wmOperatorType *ot)
994 {
995         /* identifiers */
996         ot->name= "Move Constraint Up";
997         ot->idname= "CONSTRAINT_OT_move_up";
998         ot->description= "Move constraint up constraint stack.";
999         
1000         /* callbacks */
1001         ot->exec= constraint_move_up_exec;
1002         
1003         /* flags */
1004         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO; 
1005 }
1006
1007 /***************************** OPERATORS ****************************/
1008
1009 /************************ add constraint operator *********************/
1010
1011 static int constraint_add_exec(bContext *C, wmOperator *op, ListBase *list)
1012 {
1013         Scene *scene= CTX_data_scene(C);
1014     Object *ob = CTX_data_active_object(C);
1015         bConstraint *con, *coniter;
1016         bPoseChannel *pchan= get_active_posechannel(ob);
1017         int type= RNA_enum_get(op->ptr, "type");
1018
1019         con = add_new_constraint(type);
1020
1021         if(list) {
1022                 unique_constraint_name(con, list);
1023                 BLI_addtail(list, con);
1024                 
1025                 if(proxylocked_constraints_owner(ob, pchan))
1026                         con->flag |= CONSTRAINT_PROXY_LOCAL;
1027                 
1028                 con->flag |= CONSTRAINT_ACTIVE;
1029                 for(coniter= con->prev; coniter; coniter= coniter->prev)
1030                         coniter->flag &= ~CONSTRAINT_ACTIVE;
1031         }
1032         
1033         switch(type) {
1034                 case CONSTRAINT_TYPE_CHILDOF:
1035                         {
1036                                 /* if this constraint is being added to a posechannel, make sure
1037                                  * the constraint gets evaluated in pose-space */
1038                                 if(ob->flag & OB_POSEMODE) {
1039                                         con->ownspace = CONSTRAINT_SPACE_POSE;
1040                                         con->flag |= CONSTRAINT_SPACEONCE;
1041                                 }
1042                         }
1043                         break;
1044                 case CONSTRAINT_TYPE_RIGIDBODYJOINT:
1045                         {
1046                                 bRigidBodyJointConstraint *data;
1047                                 
1048                                 /* set selected first object as target - moved from new_constraint_data */
1049                                 data = (bRigidBodyJointConstraint*)con->data;
1050                                 
1051                                 CTX_DATA_BEGIN(C, Object*, selob, selected_objects) {
1052                                         if(selob != ob) {
1053                                                 data->tar= selob;
1054                                                 break;
1055                                         }
1056                                 }
1057                                 CTX_DATA_END;
1058                         }
1059                         break;
1060                 default:
1061                         break;
1062         }
1063
1064         object_test_constraints(ob);
1065         
1066         if(ob->pose)
1067                 update_pose_constraint_flags(ob->pose);
1068         
1069         if(ob->type==OB_ARMATURE)
1070                 DAG_object_flush_update(scene, ob, OB_RECALC_DATA|OB_RECALC_OB);
1071         else
1072                 DAG_object_flush_update(scene, ob, OB_RECALC_DATA);
1073
1074         WM_event_add_notifier(C, NC_OBJECT|ND_CONSTRAINT, ob);
1075         
1076         return OPERATOR_FINISHED;
1077 }
1078
1079 static int object_constraint_add_exec(bContext *C, wmOperator *op)
1080 {
1081         Object *ob= CTX_data_pointer_get_type(C, "object", &RNA_Object).data;
1082
1083         if(!ob)
1084                 return OPERATOR_CANCELLED;
1085
1086         return constraint_add_exec(C, op, &ob->constraints);
1087 }
1088
1089 static int pose_constraint_add_exec(bContext *C, wmOperator *op)
1090 {
1091         Object *ob= CTX_data_pointer_get_type(C, "object", &RNA_Object).data;
1092
1093         if(!ob)
1094                 return OPERATOR_CANCELLED;;
1095         
1096         return constraint_add_exec(C, op, get_active_constraints(ob));
1097 }
1098
1099 void OBJECT_OT_constraint_add(wmOperatorType *ot)
1100 {
1101         /* identifiers */
1102         ot->name= "Add Constraint";
1103         ot->description = "Add a constraint to the active object.";
1104         ot->idname= "OBJECT_OT_constraint_add";
1105         
1106         /* api callbacks */
1107         ot->invoke= WM_menu_invoke;
1108         ot->exec= object_constraint_add_exec;
1109         ot->poll= ED_operator_object_active;
1110         
1111         /* flags */
1112         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
1113         
1114         /* properties */
1115         RNA_def_enum(ot->srna, "type", constraint_type_items, 0, "Type", "");
1116 }
1117
1118 void POSE_OT_constraint_add(wmOperatorType *ot)
1119 {
1120         /* identifiers */
1121         ot->name= "Add Constraint";
1122         ot->description = "Add a constraint to the active bone.";
1123         ot->idname= "POSE_OT_constraint_add";
1124         
1125         /* api callbacks */
1126         ot->invoke= WM_menu_invoke;
1127         ot->exec= pose_constraint_add_exec;
1128         ot->poll= ED_operator_posemode;
1129         
1130         /* flags */
1131         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
1132         
1133         /* properties */
1134         RNA_def_enum(ot->srna, "type", constraint_type_items, 0, "Type", "");
1135 }
1136