=bmesh= merge from trunk at r36529
[blender.git] / source / blender / blenkernel / intern / constraint.c
1 /*
2  * $Id$
3  *
4  * ***** BEGIN GPL LICENSE BLOCK *****
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License
8  * as published by the Free Software Foundation; either version 2
9  * of the License, or (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software Foundation,
18  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19  *
20  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
21  * All rights reserved.
22  *
23  * The Original Code is: all of this file.
24  *
25  * Contributor(s): 2007, Joshua Leung, major recode
26  *
27  * ***** END GPL LICENSE BLOCK *****
28  */
29
30 /** \file blender/blenkernel/intern/constraint.c
31  *  \ingroup bke
32  */
33
34
35 #include <stdio.h> 
36 #include <stddef.h>
37 #include <string.h>
38 #include <math.h>
39 #include <float.h>
40
41 #include "MEM_guardedalloc.h"
42
43 #include "BLI_blenlib.h"
44 #include "BLI_listbase.h"
45 #include "BLI_math.h"
46 #include "BLI_editVert.h"
47 #include "BLI_cellalloc.h"
48 #include "BLI_utildefines.h"
49
50 #include "DNA_armature_types.h"
51 #include "DNA_constraint_types.h"
52 #include "DNA_modifier_types.h"
53 #include "DNA_object_types.h"
54 #include "DNA_action_types.h"
55 #include "DNA_curve_types.h"
56 #include "DNA_mesh_types.h"
57 #include "DNA_meshdata_types.h"
58 #include "DNA_lattice_types.h"
59 #include "DNA_scene_types.h"
60 #include "DNA_text_types.h"
61 #include "DNA_windowmanager_types.h"
62
63
64 #include "BKE_action.h"
65 #include "BKE_anim.h" /* for the curve calculation part */
66 #include "BKE_armature.h"
67 #include "BKE_blender.h"
68 #include "BKE_constraint.h"
69 #include "BKE_displist.h"
70 #include "BKE_deform.h"
71 #include "BKE_DerivedMesh.h"    /* for geometry targets */
72 #include "BKE_cdderivedmesh.h" /* for geometry targets */
73 #include "BKE_object.h"
74 #include "BKE_ipo.h"
75 #include "BKE_global.h"
76 #include "BKE_library.h"
77 #include "BKE_idprop.h"
78 #include "BKE_mesh.h"
79 #include "BKE_shrinkwrap.h"
80 #include "BKE_mesh.h"
81 #include "BKE_tessmesh.h"
82
83 #ifdef WITH_PYTHON
84 #include "BPY_extern.h"
85 #endif
86
87 #ifndef M_PI
88 #define M_PI            3.14159265358979323846
89 #endif
90
91
92
93 /* ************************ Constraints - General Utilities *************************** */
94 /* These functions here don't act on any specific constraints, and are therefore should/will
95  * not require any of the special function-pointers afforded by the relevant constraint 
96  * type-info structs.
97  */
98
99 /* -------------- Naming -------------- */
100
101 /* Find the first available, non-duplicate name for a given constraint */
102 void unique_constraint_name (bConstraint *con, ListBase *list)
103 {
104         BLI_uniquename(list, con, "Const", '.', offsetof(bConstraint, name), sizeof(con->name));
105 }
106
107 /* ----------------- Evaluation Loop Preparation --------------- */
108
109 /* package an object/bone for use in constraint evaluation */
110 /* This function MEM_calloc's a bConstraintOb struct, that will need to be freed after evaluation */
111 bConstraintOb *constraints_make_evalob (Scene *scene, Object *ob, void *subdata, short datatype)
112 {
113         bConstraintOb *cob;
114         
115         /* create regardless of whether we have any data! */
116         cob= MEM_callocN(sizeof(bConstraintOb), "bConstraintOb");
117         
118         /* for system time, part of deglobalization, code nicer later with local time (ton) */
119         cob->scene= scene;
120         
121         /* based on type of available data */
122         switch (datatype) {
123                 case CONSTRAINT_OBTYPE_OBJECT:
124                 {
125                         /* disregard subdata... calloc should set other values right */
126                         if (ob) {
127                                 cob->ob = ob;
128                                 cob->type = datatype;
129                                 cob->rotOrder = EULER_ORDER_DEFAULT; // TODO: when objects have rotation order too, use that
130                                 copy_m4_m4(cob->matrix, ob->obmat);
131                         }
132                         else
133                                 unit_m4(cob->matrix);
134                         
135                         copy_m4_m4(cob->startmat, cob->matrix);
136                 }
137                         break;
138                 case CONSTRAINT_OBTYPE_BONE:
139                 {
140                         /* only set if we have valid bone, otherwise default */
141                         if (ob && subdata) {
142                                 cob->ob = ob;
143                                 cob->pchan = (bPoseChannel *)subdata;
144                                 cob->type = datatype;
145                                 
146                                 if (cob->pchan->rotmode > 0) {
147                                         /* should be some type of Euler order */
148                                         cob->rotOrder= cob->pchan->rotmode; 
149                                 }
150                                 else {
151                                         /* Quats, so eulers should just use default order */
152                                         cob->rotOrder= EULER_ORDER_DEFAULT;
153                                 }
154                                 
155                                 /* matrix in world-space */
156                                 mul_m4_m4m4(cob->matrix, cob->pchan->pose_mat, ob->obmat);
157                         }
158                         else
159                                 unit_m4(cob->matrix);
160                                 
161                         copy_m4_m4(cob->startmat, cob->matrix);
162                 }
163                         break;
164                         
165                 default: /* other types not yet handled */
166                         unit_m4(cob->matrix);
167                         unit_m4(cob->startmat);
168                         break;
169         }
170         
171         return cob;
172 }
173
174 /* cleanup after constraint evaluation */
175 void constraints_clear_evalob (bConstraintOb *cob)
176 {
177         float delta[4][4], imat[4][4];
178         
179         /* prevent crashes */
180         if (cob == NULL) 
181                 return;
182         
183         /* calculate delta of constraints evaluation */
184         invert_m4_m4(imat, cob->startmat);
185         mul_m4_m4m4(delta, imat, cob->matrix);
186         
187         /* copy matrices back to source */
188         switch (cob->type) {
189                 case CONSTRAINT_OBTYPE_OBJECT:
190                 {
191                         /* cob->ob might not exist! */
192                         if (cob->ob) {
193                                 /* copy new ob-matrix back to owner */
194                                 copy_m4_m4(cob->ob->obmat, cob->matrix);
195                                 
196                                 /* copy inverse of delta back to owner */
197                                 invert_m4_m4(cob->ob->constinv, delta);
198                         }
199                 }
200                         break;
201                 case CONSTRAINT_OBTYPE_BONE:
202                 {
203                         /* cob->ob or cob->pchan might not exist */
204                         if (cob->ob && cob->pchan) {
205                                 /* copy new pose-matrix back to owner */
206                                 mul_m4_m4m4(cob->pchan->pose_mat, cob->matrix, cob->ob->imat);
207                                 
208                                 /* copy inverse of delta back to owner */
209                                 invert_m4_m4(cob->pchan->constinv, delta);
210                         }
211                 }
212                         break;
213         }
214         
215         /* free tempolary struct */
216         MEM_freeN(cob);
217 }
218
219 /* -------------- Space-Conversion API -------------- */
220
221 /* This function is responsible for the correct transformations/conversions 
222  * of a matrix from one space to another for constraint evaluation.
223  * For now, this is only implemented for Objects and PoseChannels.
224  */
225 void constraint_mat_convertspace (Object *ob, bPoseChannel *pchan, float mat[][4], short from, short to)
226 {
227         float tempmat[4][4];
228         float diff_mat[4][4];
229         float imat[4][4];
230         
231         /* prevent crashes in these unlikely events  */
232         if (ob==NULL || mat==NULL) return;
233         /* optimise trick - check if need to do anything */
234         if (from == to) return;
235         
236         /* are we dealing with pose-channels or objects */
237         if (pchan) {
238                 /* pose channels */
239                 switch (from) {
240                         case CONSTRAINT_SPACE_WORLD: /* ---------- FROM WORLDSPACE ---------- */
241                         {
242                                 /* world to pose */
243                                 invert_m4_m4(imat, ob->obmat);
244                                 copy_m4_m4(tempmat, mat);
245                                 mul_m4_m4m4(mat, tempmat, imat);
246                                 
247                                 /* use pose-space as stepping stone for other spaces... */
248                                 if (ELEM(to, CONSTRAINT_SPACE_LOCAL, CONSTRAINT_SPACE_PARLOCAL)) {
249                                         /* call self with slightly different values */
250                                         constraint_mat_convertspace(ob, pchan, mat, CONSTRAINT_SPACE_POSE, to);
251                                 }
252                         }
253                                 break;
254                         case CONSTRAINT_SPACE_POSE:     /* ---------- FROM POSESPACE ---------- */
255                         {
256                                 /* pose to world */
257                                 if (to == CONSTRAINT_SPACE_WORLD) {
258                                         copy_m4_m4(tempmat, mat);
259                                         mul_m4_m4m4(mat, tempmat, ob->obmat);
260                                 }
261                                 /* pose to local */
262                                 else if (to == CONSTRAINT_SPACE_LOCAL) {
263                                         if (pchan->bone) {
264                                                 if (pchan->parent) {
265                                                         float offs_bone[4][4];
266                                                                 
267                                                         /* construct offs_bone the same way it is done in armature.c */
268                                                         copy_m4_m3(offs_bone, pchan->bone->bone_mat);
269                                                         copy_v3_v3(offs_bone[3], pchan->bone->head);
270                                                         offs_bone[3][1]+= pchan->bone->parent->length;
271                                                         
272                                                         if (pchan->bone->flag & BONE_HINGE) {
273                                                                 /* pose_mat = par_pose-space_location * chan_mat */
274                                                                 float tmat[4][4];
275                                                                 
276                                                                 /* the rotation of the parent restposition */
277                                                                 copy_m4_m4(tmat, pchan->bone->parent->arm_mat);
278                                                                 
279                                                                 /* the location of actual parent transform */
280                                                                 copy_v3_v3(tmat[3], offs_bone[3]);
281                                                                 offs_bone[3][0]= offs_bone[3][1]= offs_bone[3][2]= 0.0f;
282                                                                 mul_m4_v3(pchan->parent->pose_mat, tmat[3]);
283                                                                 
284                                                                 mul_m4_m4m4(diff_mat, offs_bone, tmat);
285                                                                 invert_m4_m4(imat, diff_mat);
286                                                         }
287                                                         else {
288                                                                 /* pose_mat = par_pose_mat * bone_mat * chan_mat */
289                                                                 mul_m4_m4m4(diff_mat, offs_bone, pchan->parent->pose_mat);
290                                                                 invert_m4_m4(imat, diff_mat);
291                                                         }
292                                                 }
293                                                 else {
294                                                         /* pose_mat = chan_mat * arm_mat */
295                                                         invert_m4_m4(imat, pchan->bone->arm_mat);
296                                                 }
297                                                 
298                                                 copy_m4_m4(tempmat, mat);
299                                                 mul_m4_m4m4(mat, tempmat, imat);
300                                         }
301                                 }
302                                 /* pose to local with parent */
303                                 else if (to == CONSTRAINT_SPACE_PARLOCAL) {
304                                         if (pchan->bone) {
305                                                 invert_m4_m4(imat, pchan->bone->arm_mat);
306                                                 copy_m4_m4(tempmat, mat);
307                                                 mul_m4_m4m4(mat, tempmat, imat);
308                                         }
309                                 }
310                         }
311                                 break;
312                         case CONSTRAINT_SPACE_LOCAL: /* ------------ FROM LOCALSPACE --------- */
313                         {
314                                 /* local to pose - do inverse procedure that was done for pose to local */
315                                 if (pchan->bone) {
316                                         /* we need the posespace_matrix = local_matrix + (parent_posespace_matrix + restpos) */                                         
317                                         if (pchan->parent) {
318                                                 float offs_bone[4][4];
319                                                 
320                                                 /* construct offs_bone the same way it is done in armature.c */
321                                                 copy_m4_m3(offs_bone, pchan->bone->bone_mat);
322                                                 copy_v3_v3(offs_bone[3], pchan->bone->head);
323                                                 offs_bone[3][1]+= pchan->bone->parent->length;
324                                                 
325                                                 if (pchan->bone->flag & BONE_HINGE) {
326                                                         /* pose_mat = par_pose-space_location * chan_mat */
327                                                         float tmat[4][4];
328                                                         
329                                                         /* the rotation of the parent restposition */
330                                                         copy_m4_m4(tmat, pchan->bone->parent->arm_mat);
331                                                         
332                                                         /* the location of actual parent transform */
333                                                         copy_v3_v3(tmat[3], offs_bone[3]);
334                                                         zero_v3(offs_bone[3]);
335                                                         mul_m4_v3(pchan->parent->pose_mat, tmat[3]);
336                                                         
337                                                         mul_m4_m4m4(diff_mat, offs_bone, tmat);
338                                                         copy_m4_m4(tempmat, mat);
339                                                         mul_m4_m4m4(mat, tempmat, diff_mat);
340                                                 }
341                                                 else {
342                                                         /* pose_mat = par_pose_mat * bone_mat * chan_mat */
343                                                         mul_m4_m4m4(diff_mat, offs_bone, pchan->parent->pose_mat);
344                                                         copy_m4_m4(tempmat, mat);
345                                                         mul_m4_m4m4(mat, tempmat, diff_mat);
346                                                 }
347                                         }
348                                         else {
349                                                 copy_m4_m4(diff_mat, pchan->bone->arm_mat);
350                                                 
351                                                 copy_m4_m4(tempmat, mat);
352                                                 mul_m4_m4m4(mat, tempmat, diff_mat);
353                                         }
354                                 }
355                                 
356                                 /* use pose-space as stepping stone for other spaces */
357                                 if (ELEM(to, CONSTRAINT_SPACE_WORLD, CONSTRAINT_SPACE_PARLOCAL)) {
358                                         /* call self with slightly different values */
359                                         constraint_mat_convertspace(ob, pchan, mat, CONSTRAINT_SPACE_POSE, to);
360                                 }                               
361                         }
362                                 break;
363                         case CONSTRAINT_SPACE_PARLOCAL: /* -------------- FROM LOCAL WITH PARENT ---------- */
364                         {
365                                 /* local + parent to pose */
366                                 if (pchan->bone) {                                      
367                                         copy_m4_m4(diff_mat, pchan->bone->arm_mat);
368                                         copy_m4_m4(tempmat, mat);
369                                         mul_m4_m4m4(mat, diff_mat, tempmat);
370                                 }
371                                 
372                                 /* use pose-space as stepping stone for other spaces */
373                                 if (ELEM(to, CONSTRAINT_SPACE_WORLD, CONSTRAINT_SPACE_LOCAL)) {
374                                         /* call self with slightly different values */
375                                         constraint_mat_convertspace(ob, pchan, mat, CONSTRAINT_SPACE_POSE, to);
376                                 }
377                         }
378                                 break;
379                 }
380         }
381         else {
382                 /* objects */
383                 if (from==CONSTRAINT_SPACE_WORLD && to==CONSTRAINT_SPACE_LOCAL) {
384                         /* check if object has a parent */
385                         if (ob->parent) {
386                                 /* 'subtract' parent's effects from owner */
387                                 mul_m4_m4m4(diff_mat, ob->parentinv, ob->parent->obmat);
388                                 invert_m4_m4(imat, diff_mat);
389                                 copy_m4_m4(tempmat, mat);
390                                 mul_m4_m4m4(mat, tempmat, imat);
391                         }
392                         else {
393                                 /* Local space in this case will have to be defined as local to the owner's 
394                                  * transform-property-rotated axes. So subtract this rotation component.
395                                  */
396                                 object_to_mat4(ob, diff_mat);
397                                 normalize_m4(diff_mat);
398                                 zero_v3(diff_mat[3]);
399                                 
400                                 invert_m4_m4(imat, diff_mat);
401                                 copy_m4_m4(tempmat, mat);
402                                 mul_m4_m4m4(mat, tempmat, imat);
403                         }
404                 }
405                 else if (from==CONSTRAINT_SPACE_LOCAL && to==CONSTRAINT_SPACE_WORLD) {
406                         /* check that object has a parent - otherwise this won't work */
407                         if (ob->parent) {
408                                 /* 'add' parent's effect back to owner */
409                                 copy_m4_m4(tempmat, mat);
410                                 mul_m4_m4m4(diff_mat, ob->parentinv, ob->parent->obmat);
411                                 mul_m4_m4m4(mat, tempmat, diff_mat);
412                         }
413                         else {
414                                 /* Local space in this case will have to be defined as local to the owner's 
415                                  * transform-property-rotated axes. So add back this rotation component.
416                                  */
417                                 object_to_mat4(ob, diff_mat);
418                                 normalize_m4(diff_mat);
419                                 zero_v3(diff_mat[3]);
420                                 
421                                 copy_m4_m4(tempmat, mat);
422                                 mul_m4_m4m4(mat, tempmat, diff_mat);
423                         }
424                 }
425         }
426 }
427
428 /* ------------ General Target Matrix Tools ---------- */
429
430 /* function that sets the given matrix based on given vertex group in mesh */
431 static void contarget_get_mesh_mat (Scene *scene, Object *ob, const char *substring, float mat[][4])
432 {
433         DerivedMesh *dm = NULL;
434         Mesh *me= ob->data;
435         BMEditMesh *em = me->edit_btmesh;
436         float vec[3] = {0.0f, 0.0f, 0.0f};
437         float normal[3] = {0.0f, 0.0f, 0.0f}, plane[3];
438         float imat[3][3], tmat[3][3];
439         int dgroup;
440         short freeDM = 0;
441         
442         /* initialize target matrix using target matrix */
443         copy_m4_m4(mat, ob->obmat);
444         
445         /* get index of vertex group */
446         dgroup = defgroup_name_index(ob, substring);
447         if (dgroup < 0) return;
448         
449         /* get DerivedMesh */
450         if (em) {
451                 /* target is in editmode, so get a special derived mesh */
452                 dm = CDDM_from_BMEditMesh(em, ob->data, 0);
453                 freeDM= 1;
454         }
455         else {
456                 /* when not in EditMode, use the 'final' derived mesh 
457                  *      - check if the custom data masks for derivedFinal mean that we can just use that
458                  *        (this is more effficient + sufficient for most cases)
459                  */
460                 if (!(ob->lastDataMask & CD_MASK_MDEFORMVERT)) {
461                         dm = mesh_get_derived_final(scene, ob, CD_MASK_MDEFORMVERT);
462                         freeDM= 1;
463                 }
464                 else 
465                         dm = (DerivedMesh *)ob->derivedFinal;
466         }
467         
468         /* only continue if there's a valid DerivedMesh */
469         if (dm) {
470                 MDeformVert *dvert = dm->getVertDataArray(dm, CD_MDEFORMVERT);
471                 int numVerts = dm->getNumVerts(dm);
472                 int i, j, count = 0;
473                 float co[3], nor[3];
474                 
475                 /* check that dvert is a valid pointers (just in case) */
476                 if (dvert) {
477                         /* get the average of all verts with that are in the vertex-group */
478                         for (i = 0; i < numVerts; i++) {        
479                                 for (j = 0; j < dvert[i].totweight; j++) {
480                                         /* does this vertex belong to nominated vertex group? */
481                                         if (dvert[i].dw[j].def_nr == dgroup) {
482                                                 dm->getVertCo(dm, i, co);
483                                                 dm->getVertNo(dm, i, nor);
484                                                 add_v3_v3(vec, co);
485                                                 add_v3_v3(normal, nor);
486                                                 count++;
487                                                 break;
488                                         }
489                                         
490                                 }
491                         }
492                         
493                         
494                         /* calculate averages of normal and coordinates */
495                         if (count > 0) {
496                                 mul_v3_fl(vec, 1.0f / count);
497                                 mul_v3_fl(normal, 1.0f / count);
498                         }
499                         
500                         
501                         /* derive the rotation from the average normal: 
502                          *              - code taken from transform_manipulator.c, 
503                          *                      calc_manipulator_stats, V3D_MANIP_NORMAL case
504                          */
505                         /*      we need the transpose of the inverse for a normal... */
506                         copy_m3_m4(imat, ob->obmat);
507                         
508                         invert_m3_m3(tmat, imat);
509                         transpose_m3(tmat);
510                         mul_m3_v3(tmat, normal);
511                         
512                         normalize_v3(normal);
513                         copy_v3_v3(plane, tmat[1]);
514                         
515                         copy_v3_v3(tmat[2], normal);
516                         cross_v3_v3v3(tmat[0], normal, plane);
517                         cross_v3_v3v3(tmat[1], tmat[2], tmat[0]);
518                         
519                         copy_m4_m3(mat, tmat);
520                         normalize_m4(mat);
521                         
522                         
523                         /* apply the average coordinate as the new location */
524                         mul_v3_m4v3(mat[3], ob->obmat, vec);
525                 }
526         }
527         
528         /* free temporary DerivedMesh created (in EditMode case) */
529         if (dm && freeDM)
530                 dm->release(dm);
531 }
532
533 /* function that sets the given matrix based on given vertex group in lattice */
534 static void contarget_get_lattice_mat (Object *ob, const char *substring, float mat[][4])
535 {
536         Lattice *lt= (Lattice *)ob->data;
537         
538         DispList *dl = find_displist(&ob->disp, DL_VERTS);
539         float *co = dl?dl->verts:NULL;
540         BPoint *bp = lt->def;
541         
542         MDeformVert *dvert = lt->dvert;
543         int tot_verts= lt->pntsu*lt->pntsv*lt->pntsw;
544         float vec[3]= {0.0f, 0.0f, 0.0f}, tvec[3];
545         int dgroup=0, grouped=0;
546         int i, n;
547         
548         /* initialize target matrix using target matrix */
549         copy_m4_m4(mat, ob->obmat);
550         
551         /* get index of vertex group */
552         dgroup = defgroup_name_index(ob, substring);
553         if (dgroup < 0) return;
554         if (dvert == NULL) return;
555         
556         /* 1. Loop through control-points checking if in nominated vertex-group.
557          * 2. If it is, add it to vec to find the average point.
558          */
559         for (i=0; i < tot_verts; i++, dvert++) {
560                 for (n= 0; n < dvert->totweight; n++) {
561                         /* found match - vert is in vgroup */
562                         if (dvert->dw[n].def_nr == dgroup) {
563                                 /* copy coordinates of point to temporary vector, then add to find average */
564                                 if (co)
565                                         memcpy(tvec, co, 3*sizeof(float));
566                                 else
567                                         memcpy(tvec, bp->vec, 3*sizeof(float));
568                                         
569                                 add_v3_v3(vec, tvec);
570                                 grouped++;
571                                 
572                                 break;
573                         }
574                 }
575                 
576                 /* advance pointer to coordinate data */
577                 if (co) co+= 3;
578                 else bp++;
579         }
580         
581         /* find average location, then multiply by ob->obmat to find world-space location */
582         if (grouped)
583                 mul_v3_fl(vec, 1.0f / grouped);
584         mul_v3_m4v3(tvec, ob->obmat, vec);
585         
586         /* copy new location to matrix */
587         copy_v3_v3(mat[3], tvec);
588 }
589
590 /* generic function to get the appropriate matrix for most target cases */
591 /* The cases where the target can be object data have not been implemented */
592 static void constraint_target_to_mat4 (Scene *scene, Object *ob, const char *substring, float mat[][4], short from, short to, float headtail)
593 {
594         /*      Case OBJECT */
595         if (!strlen(substring)) {
596                 copy_m4_m4(mat, ob->obmat);
597                 constraint_mat_convertspace(ob, NULL, mat, from, to);
598         }
599         /*      Case VERTEXGROUP */
600         /* Current method just takes the average location of all the points in the
601          * VertexGroup, and uses that as the location value of the targets. Where 
602          * possible, the orientation will also be calculated, by calculating an
603          * 'average' vertex normal, and deriving the rotaation from that.
604          *
605          * NOTE: EditMode is not currently supported, and will most likely remain that
606          *              way as constraints can only really affect things on object/bone level.
607          */
608         else if (ob->type == OB_MESH) {
609                 contarget_get_mesh_mat(scene, ob, substring, mat);
610                 constraint_mat_convertspace(ob, NULL, mat, from, to);
611         }
612         else if (ob->type == OB_LATTICE) {
613                 contarget_get_lattice_mat(ob, substring, mat);
614                 constraint_mat_convertspace(ob, NULL, mat, from, to);
615         }
616         /*      Case BONE */
617         else {
618                 bPoseChannel *pchan;
619                 
620                 pchan = get_pose_channel(ob->pose, substring);
621                 if (pchan) {
622                         /* Multiply the PoseSpace accumulation/final matrix for this
623                          * PoseChannel by the Armature Object's Matrix to get a worldspace
624                          * matrix.
625                          */
626                         if (headtail < 0.000001f) {
627                                 /* skip length interpolation if set to head */
628                                 mul_m4_m4m4(mat, pchan->pose_mat, ob->obmat);
629                         }
630                         else {
631                                 float tempmat[4][4], loc[3];
632                                 
633                                 /* interpolate along length of bone */
634                                 interp_v3_v3v3(loc, pchan->pose_head, pchan->pose_tail, headtail);      
635                                 
636                                 /* use interpolated distance for subtarget */
637                                 copy_m4_m4(tempmat, pchan->pose_mat);   
638                                 copy_v3_v3(tempmat[3], loc);
639                                 
640                                 mul_m4_m4m4(mat, tempmat, ob->obmat);
641                         }
642                 } 
643                 else
644                         copy_m4_m4(mat, ob->obmat);
645                         
646                 /* convert matrix space as required */
647                 constraint_mat_convertspace(ob, pchan, mat, from, to);
648         }
649 }
650
651 /* ************************* Specific Constraints ***************************** */
652 /* Each constraint defines a set of functions, which will be called at the appropriate
653  * times. In addition to this, each constraint should have a type-info struct, where
654  * its functions are attached for use. 
655  */
656  
657 /* Template for type-info data:
658  *      - make a copy of this when creating new constraints, and just change the functions
659  *        pointed to as necessary
660  *      - although the naming of functions doesn't matter, it would help for code
661  *        readability, to follow the same naming convention as is presented here
662  *      - any functions that a constraint doesn't need to define, don't define
663  *        for such cases, just use NULL 
664  *      - these should be defined after all the functions have been defined, so that
665  *        forward-definitions/prototypes don't need to be used!
666  *      - keep this copy #if-def'd so that future constraints can get based off this
667  */
668 #if 0
669 static bConstraintTypeInfo CTI_CONSTRNAME = {
670         CONSTRAINT_TYPE_CONSTRNAME, /* type */
671         sizeof(bConstrNameConstraint), /* size */
672         "ConstrName", /* name */
673         "bConstrNameConstraint", /* struct name */
674         constrname_free, /* free data */
675         constrname_relink, /* relink data */
676         constrname_id_looper, /* id looper */
677         constrname_copy, /* copy data */
678         constrname_new_data, /* new data */
679         constrname_get_tars, /* get constraint targets */
680         constrname_flush_tars, /* flush constraint targets */
681         constrname_get_tarmat, /* get target matrix */
682         constrname_evaluate /* evaluate */
683 };
684 #endif
685
686 /* This function should be used for the get_target_matrix member of all 
687  * constraints that are not picky about what happens to their target matrix.
688  */
689 static void default_get_tarmat (bConstraint *con, bConstraintOb *cob, bConstraintTarget *ct, float UNUSED(ctime))
690 {
691         if (VALID_CONS_TARGET(ct))
692                 constraint_target_to_mat4(cob->scene, ct->tar, ct->subtarget, ct->matrix, CONSTRAINT_SPACE_WORLD, ct->space, con->headtail);
693         else if (ct)
694                 unit_m4(ct->matrix);
695 }
696
697 /* This following macro should be used for all standard single-target *_get_tars functions 
698  * to save typing and reduce maintainance woes.
699  * (Hopefully all compilers will be happy with the lines with just a space on them. Those are
700  *  really just to help this code easier to read)
701  */
702 // TODO: cope with getting rotation order...
703 #define SINGLETARGET_GET_TARS(con, datatar, datasubtarget, ct, list) \
704         { \
705                 ct= MEM_callocN(sizeof(bConstraintTarget), "tempConstraintTarget"); \
706                  \
707                 ct->tar= datatar; \
708                 BLI_strncpy(ct->subtarget, datasubtarget, sizeof(ct->subtarget)); \
709                 ct->space= con->tarspace; \
710                 ct->flag= CONSTRAINT_TAR_TEMP; \
711                  \
712                 if (ct->tar) { \
713                         if ((ct->tar->type==OB_ARMATURE) && (ct->subtarget[0])) { \
714                                 bPoseChannel *pchan= get_pose_channel(ct->tar->pose, ct->subtarget); \
715                                 ct->type = CONSTRAINT_OBTYPE_BONE; \
716                                 ct->rotOrder= (pchan) ? (pchan->rotmode) : EULER_ORDER_DEFAULT; \
717                         }\
718                         else if (ELEM(ct->tar->type, OB_MESH, OB_LATTICE) && (ct->subtarget[0])) { \
719                                 ct->type = CONSTRAINT_OBTYPE_VERT; \
720                                 ct->rotOrder = EULER_ORDER_DEFAULT; \
721                         } \
722                         else {\
723                                 ct->type = CONSTRAINT_OBTYPE_OBJECT; \
724                                 ct->rotOrder= ct->tar->rotmode; \
725                         } \
726                 } \
727                  \
728                 BLI_addtail(list, ct); \
729         }
730         
731 /* This following macro should be used for all standard single-target *_get_tars functions 
732  * to save typing and reduce maintainance woes. It does not do the subtarget related operations
733  * (Hopefully all compilers will be happy with the lines with just a space on them. Those are
734  *  really just to help this code easier to read)
735  */
736 // TODO: cope with getting rotation order...
737 #define SINGLETARGETNS_GET_TARS(con, datatar, ct, list) \
738         { \
739                 ct= MEM_callocN(sizeof(bConstraintTarget), "tempConstraintTarget"); \
740                  \
741                 ct->tar= datatar; \
742                 ct->space= con->tarspace; \
743                 ct->flag= CONSTRAINT_TAR_TEMP; \
744                  \
745                 if (ct->tar) ct->type = CONSTRAINT_OBTYPE_OBJECT; \
746                  \
747                 BLI_addtail(list, ct); \
748         }
749
750 /* This following macro should be used for all standard single-target *_flush_tars functions
751  * to save typing and reduce maintainance woes.
752  * Note: the pointer to ct will be changed to point to the next in the list (as it gets removed)
753  * (Hopefully all compilers will be happy with the lines with just a space on them. Those are
754  *  really just to help this code easier to read)
755  */
756 #define SINGLETARGET_FLUSH_TARS(con, datatar, datasubtarget, ct, list, nocopy) \
757         { \
758                 if (ct) { \
759                         bConstraintTarget *ctn = ct->next; \
760                         if (nocopy == 0) { \
761                                 datatar= ct->tar; \
762                                 BLI_strncpy(datasubtarget, ct->subtarget, sizeof(datasubtarget)); \
763                                 con->tarspace= (char)ct->space; \
764                         } \
765                          \
766                         BLI_freelinkN(list, ct); \
767                         ct= ctn; \
768                 } \
769         }
770         
771 /* This following macro should be used for all standard single-target *_flush_tars functions
772  * to save typing and reduce maintainance woes. It does not do the subtarget related operations.
773  * Note: the pointer to ct will be changed to point to the next in the list (as it gets removed)
774  * (Hopefully all compilers will be happy with the lines with just a space on them. Those are
775  *  really just to help this code easier to read)
776  */
777 #define SINGLETARGETNS_FLUSH_TARS(con, datatar, ct, list, nocopy) \
778         { \
779                 if (ct) { \
780                         bConstraintTarget *ctn = ct->next; \
781                         if (nocopy == 0) { \
782                                 datatar= ct->tar; \
783                                 con->tarspace= (char)ct->space; \
784                         } \
785                          \
786                         BLI_freelinkN(list, ct); \
787                         ct= ctn; \
788                 } \
789         }
790  
791 /* --------- ChildOf Constraint ------------ */
792
793 static void childof_new_data (void *cdata)
794 {
795         bChildOfConstraint *data= (bChildOfConstraint *)cdata;
796         
797         data->flag = (CHILDOF_LOCX | CHILDOF_LOCY | CHILDOF_LOCZ |
798                                         CHILDOF_ROTX |CHILDOF_ROTY | CHILDOF_ROTZ |
799                                         CHILDOF_SIZEX | CHILDOF_SIZEY | CHILDOF_SIZEZ);
800         unit_m4(data->invmat);
801 }
802
803 static void childof_id_looper (bConstraint *con, ConstraintIDFunc func, void *userdata)
804 {
805         bChildOfConstraint *data= con->data;
806         
807         /* target only */
808         func(con, (ID**)&data->tar, userdata);
809 }
810
811 static int childof_get_tars (bConstraint *con, ListBase *list)
812 {
813         if (con && list) {
814                 bChildOfConstraint *data= con->data;
815                 bConstraintTarget *ct;
816                 
817                 /* standard target-getting macro for single-target constraints */
818                 SINGLETARGET_GET_TARS(con, data->tar, data->subtarget, ct, list)
819                 
820                 return 1;
821         }
822         
823         return 0;
824 }
825
826 static void childof_flush_tars (bConstraint *con, ListBase *list, short nocopy)
827 {
828         if (con && list) {
829                 bChildOfConstraint *data= con->data;
830                 bConstraintTarget *ct= list->first;
831                 
832                 /* the following macro is used for all standard single-target constraints */
833                 SINGLETARGET_FLUSH_TARS(con, data->tar, data->subtarget, ct, list, nocopy)
834         }
835 }
836
837 static void childof_evaluate (bConstraint *con, bConstraintOb *cob, ListBase *targets)
838 {
839         bChildOfConstraint *data= con->data;
840         bConstraintTarget *ct= targets->first;
841         
842         /* only evaluate if there is a target */
843         if (VALID_CONS_TARGET(ct)) {
844                 float parmat[4][4];
845                 
846                 /* simple matrix parenting */
847                 if(data->flag == CHILDOF_ALL) {
848                         
849                         /* multiply target (parent matrix) by offset (parent inverse) to get 
850                          * the effect of the parent that will be exherted on the owner
851                          */
852                         mul_m4_m4m4(parmat, data->invmat, ct->matrix);
853                         
854                         /* now multiply the parent matrix by the owner matrix to get the 
855                          * the effect of this constraint (i.e.  owner is 'parented' to parent)
856                          */
857                         mul_m4_m4m4(cob->matrix, cob->matrix, parmat);
858                 }
859                 else {
860                         float invmat[4][4], tempmat[4][4];
861                         float loc[3], eul[3], size[3];
862                         float loco[3], eulo[3], sizo[3];
863                         
864                         /* get offset (parent-inverse) matrix */
865                         copy_m4_m4(invmat, data->invmat);
866                         
867                         /* extract components of both matrices */
868                         copy_v3_v3(loc, ct->matrix[3]);
869                         mat4_to_eulO(eul, ct->rotOrder, ct->matrix);
870                         mat4_to_size(size, ct->matrix);
871                         
872                         copy_v3_v3(loco, invmat[3]);
873                         mat4_to_eulO(eulo, cob->rotOrder, invmat);
874                         mat4_to_size(sizo, invmat);
875                         
876                         /* disable channels not enabled */
877                         if (!(data->flag & CHILDOF_LOCX)) loc[0]= loco[0]= 0.0f;
878                         if (!(data->flag & CHILDOF_LOCY)) loc[1]= loco[1]= 0.0f;
879                         if (!(data->flag & CHILDOF_LOCZ)) loc[2]= loco[2]= 0.0f;
880                         if (!(data->flag & CHILDOF_ROTX)) eul[0]= eulo[0]= 0.0f;
881                         if (!(data->flag & CHILDOF_ROTY)) eul[1]= eulo[1]= 0.0f;
882                         if (!(data->flag & CHILDOF_ROTZ)) eul[2]= eulo[2]= 0.0f;
883                         if (!(data->flag & CHILDOF_SIZEX)) size[0]= sizo[0]= 1.0f;
884                         if (!(data->flag & CHILDOF_SIZEY)) size[1]= sizo[1]= 1.0f;
885                         if (!(data->flag & CHILDOF_SIZEZ)) size[2]= sizo[2]= 1.0f;
886                         
887                         /* make new target mat and offset mat */
888                         loc_eulO_size_to_mat4(ct->matrix, loc, eul, size, ct->rotOrder);
889                         loc_eulO_size_to_mat4(invmat, loco, eulo, sizo, cob->rotOrder);
890                         
891                         /* multiply target (parent matrix) by offset (parent inverse) to get 
892                          * the effect of the parent that will be exherted on the owner
893                          */
894                         mul_m4_m4m4(parmat, invmat, ct->matrix);
895                         
896                         /* now multiply the parent matrix by the owner matrix to get the 
897                          * the effect of this constraint (i.e.  owner is 'parented' to parent)
898                          */
899                         copy_m4_m4(tempmat, cob->matrix);
900                         mul_m4_m4m4(cob->matrix, tempmat, parmat);
901
902                         /* without this, changes to scale and rotation can change location
903                          * of a parentless bone or a disconnected bone. Even though its set
904                          * to zero above. */
905                         if (!(data->flag & CHILDOF_LOCX)) cob->matrix[3][0]= tempmat[3][0];
906                         if (!(data->flag & CHILDOF_LOCY)) cob->matrix[3][1]= tempmat[3][1];
907                         if (!(data->flag & CHILDOF_LOCZ)) cob->matrix[3][2]= tempmat[3][2];     
908                 }
909         }
910 }
911
912 /* XXX note, con->flag should be CONSTRAINT_SPACEONCE for bone-childof, patched in readfile.c */
913 static bConstraintTypeInfo CTI_CHILDOF = {
914         CONSTRAINT_TYPE_CHILDOF, /* type */
915         sizeof(bChildOfConstraint), /* size */
916         "ChildOf", /* name */
917         "bChildOfConstraint", /* struct name */
918         NULL, /* free data */
919         NULL, /* relink data */
920         childof_id_looper, /* id looper */
921         NULL, /* copy data */
922         childof_new_data, /* new data */
923         childof_get_tars, /* get constraint targets */
924         childof_flush_tars, /* flush constraint targets */
925         default_get_tarmat, /* get a target matrix */
926         childof_evaluate /* evaluate */
927 };
928
929 /* -------- TrackTo Constraint ------- */
930
931 static void trackto_new_data (void *cdata)
932 {
933         bTrackToConstraint *data= (bTrackToConstraint *)cdata;
934         
935         data->reserved1 = TRACK_Y;
936         data->reserved2 = UP_Z;
937 }       
938
939 static void trackto_id_looper (bConstraint *con, ConstraintIDFunc func, void *userdata)
940 {
941         bTrackToConstraint *data= con->data;
942         
943         /* target only */
944         func(con, (ID**)&data->tar, userdata);
945 }
946
947 static int trackto_get_tars (bConstraint *con, ListBase *list)
948 {
949         if (con && list) {
950                 bTrackToConstraint *data= con->data;
951                 bConstraintTarget *ct;
952                 
953                 /* standard target-getting macro for single-target constraints */
954                 SINGLETARGET_GET_TARS(con, data->tar, data->subtarget, ct, list)
955                 
956                 return 1;
957         }
958         
959         return 0;
960 }
961
962 static void trackto_flush_tars (bConstraint *con, ListBase *list, short nocopy)
963 {
964         if (con && list) {
965                 bTrackToConstraint *data= con->data;
966                 bConstraintTarget *ct= list->first;
967                 
968                 /* the following macro is used for all standard single-target constraints */
969                 SINGLETARGET_FLUSH_TARS(con, data->tar, data->subtarget, ct, list, nocopy)
970         }
971 }
972
973
974 static int basis_cross (int n, int m)
975 {
976         switch (n-m) {
977                 case 1: 
978                 case -2:
979                         return 1;
980                         
981                 case -1: 
982                 case 2:
983                         return -1;
984                         
985                 default:
986                         return 0;
987         }
988 }
989
990 static void vectomat (float *vec, float *target_up, short axis, short upflag, short flags, float m[][3])
991 {
992         float n[3];
993         float u[3]; /* vector specifying the up axis */
994         float proj[3];
995         float right[3];
996         float neg = -1;
997         int right_index;
998
999         if (normalize_v3_v3(n, vec) == 0.0f) {
1000                 n[0] = 0.0f;
1001                 n[1] = 0.0f;
1002                 n[2] = 1.0f;
1003         }
1004         if (axis > 2) axis -= 3;
1005         else negate_v3(n);
1006
1007         /* n specifies the transformation of the track axis */
1008         if (flags & TARGET_Z_UP) { 
1009                 /* target Z axis is the global up axis */
1010                 copy_v3_v3(u, target_up);
1011         }
1012         else { 
1013                 /* world Z axis is the global up axis */
1014                 u[0] = 0;
1015                 u[1] = 0;
1016                 u[2] = 1;
1017         }
1018
1019         /* project the up vector onto the plane specified by n */
1020         project_v3_v3v3(proj, u, n); /* first u onto n... */
1021         sub_v3_v3v3(proj, u, proj); /* then onto the plane */
1022         /* proj specifies the transformation of the up axis */
1023
1024         if (normalize_v3(proj) == 0.0f) { /* degenerate projection */
1025                 proj[0] = 0.0f;
1026                 proj[1] = 1.0f;
1027                 proj[2] = 0.0f;
1028         }
1029
1030         /* Normalized cross product of n and proj specifies transformation of the right axis */
1031         cross_v3_v3v3(right, proj, n);
1032         normalize_v3(right);
1033
1034         if (axis != upflag) {
1035                 right_index = 3 - axis - upflag;
1036                 neg = (float)basis_cross(axis, upflag);
1037                 
1038                 /* account for up direction, track direction */
1039                 m[right_index][0] = neg * right[0];
1040                 m[right_index][1] = neg * right[1];
1041                 m[right_index][2] = neg * right[2];
1042                 
1043                 copy_v3_v3(m[upflag], proj);
1044                 
1045                 copy_v3_v3(m[axis], n);
1046         }
1047         /* identity matrix - don't do anything if the two axes are the same */
1048         else {
1049                 unit_m3(m);
1050         }
1051 }
1052
1053
1054 static void trackto_evaluate (bConstraint *con, bConstraintOb *cob, ListBase *targets)
1055 {
1056         bTrackToConstraint *data= con->data;
1057         bConstraintTarget *ct= targets->first;
1058         
1059         if (VALID_CONS_TARGET(ct)) {
1060                 float size[3], vec[3];
1061                 float totmat[3][3];
1062                 float tmat[4][4];
1063                 
1064                 /* Get size property, since ob->size is only the object's own relative size, not its global one */
1065                 mat4_to_size(size, cob->matrix);
1066                 
1067                 /* Clear the object's rotation */       
1068                 cob->matrix[0][0]=size[0];
1069                 cob->matrix[0][1]=0;
1070                 cob->matrix[0][2]=0;
1071                 cob->matrix[1][0]=0;
1072                 cob->matrix[1][1]=size[1];
1073                 cob->matrix[1][2]=0;
1074                 cob->matrix[2][0]=0;
1075                 cob->matrix[2][1]=0;
1076                 cob->matrix[2][2]=size[2];
1077                 
1078                 /* targetmat[2] instead of ownermat[2] is passed to vectomat
1079                  * for backwards compatability it seems... (Aligorith)
1080                  */
1081                 sub_v3_v3v3(vec, cob->matrix[3], ct->matrix[3]);
1082                 vectomat(vec, ct->matrix[2], 
1083                                 (short)data->reserved1, (short)data->reserved2, 
1084                                 data->flags, totmat);
1085                 
1086                 copy_m4_m4(tmat, cob->matrix);
1087                 mul_m4_m3m4(cob->matrix, totmat, tmat);
1088         }
1089 }
1090
1091 static bConstraintTypeInfo CTI_TRACKTO = {
1092         CONSTRAINT_TYPE_TRACKTO, /* type */
1093         sizeof(bTrackToConstraint), /* size */
1094         "TrackTo", /* name */
1095         "bTrackToConstraint", /* struct name */
1096         NULL, /* free data */
1097         NULL, /* relink data */
1098         trackto_id_looper, /* id looper */
1099         NULL, /* copy data */
1100         trackto_new_data, /* new data */
1101         trackto_get_tars, /* get constraint targets */
1102         trackto_flush_tars, /* flush constraint targets */
1103         default_get_tarmat, /* get target matrix */
1104         trackto_evaluate /* evaluate */
1105 };
1106
1107 /* --------- Inverse-Kinemetics --------- */
1108
1109 static void kinematic_new_data (void *cdata)
1110 {
1111         bKinematicConstraint *data= (bKinematicConstraint *)cdata;
1112         
1113         data->weight= (float)1.0;
1114         data->orientweight= (float)1.0;
1115         data->iterations = 500;
1116         data->dist= (float)1.0;
1117         data->flag= CONSTRAINT_IK_TIP|CONSTRAINT_IK_STRETCH|CONSTRAINT_IK_POS;
1118 }
1119
1120 static void kinematic_id_looper (bConstraint *con, ConstraintIDFunc func, void *userdata)
1121 {
1122         bKinematicConstraint *data= con->data;
1123         
1124         /* chain target */
1125         func(con, (ID**)&data->tar, userdata);
1126         
1127         /* poletarget */
1128         func(con, (ID**)&data->poletar, userdata);
1129 }
1130
1131 static int kinematic_get_tars (bConstraint *con, ListBase *list)
1132 {
1133         if (con && list) {
1134                 bKinematicConstraint *data= con->data;
1135                 bConstraintTarget *ct;
1136                 
1137                 /* standard target-getting macro for single-target constraints is used twice here */
1138                 SINGLETARGET_GET_TARS(con, data->tar, data->subtarget, ct, list)
1139                 SINGLETARGET_GET_TARS(con, data->poletar, data->polesubtarget, ct, list)
1140                 
1141                 return 2;
1142         }
1143         
1144         return 0;
1145 }
1146
1147 static void kinematic_flush_tars (bConstraint *con, ListBase *list, short nocopy)
1148 {
1149         if (con && list) {
1150                 bKinematicConstraint *data= con->data;
1151                 bConstraintTarget *ct= list->first;
1152                 
1153                 /* the following macro is used for all standard single-target constraints */
1154                 SINGLETARGET_FLUSH_TARS(con, data->tar, data->subtarget, ct, list, nocopy)
1155                 SINGLETARGET_FLUSH_TARS(con, data->poletar, data->polesubtarget, ct, list, nocopy)
1156         }
1157 }
1158
1159 static void kinematic_get_tarmat (bConstraint *con, bConstraintOb *cob, bConstraintTarget *ct, float UNUSED(ctime))
1160 {
1161         bKinematicConstraint *data= con->data;
1162         
1163         if (VALID_CONS_TARGET(ct)) 
1164                 constraint_target_to_mat4(cob->scene, ct->tar, ct->subtarget, ct->matrix, CONSTRAINT_SPACE_WORLD, ct->space, con->headtail);
1165         else if (ct) {
1166                 if (data->flag & CONSTRAINT_IK_AUTO) {
1167                         Object *ob= cob->ob;
1168                         
1169                         if (ob == NULL) {
1170                                 unit_m4(ct->matrix);
1171                         }
1172                         else {
1173                                 float vec[3];
1174                                 /* move grabtarget into world space */
1175                                 mul_v3_m4v3(vec, ob->obmat, data->grabtarget);
1176                                 copy_m4_m4(ct->matrix, ob->obmat);
1177                                 copy_v3_v3(ct->matrix[3], vec);
1178                         }
1179                 }
1180                 else
1181                         unit_m4(ct->matrix);
1182         }
1183 }
1184
1185 static bConstraintTypeInfo CTI_KINEMATIC = {
1186         CONSTRAINT_TYPE_KINEMATIC, /* type */
1187         sizeof(bKinematicConstraint), /* size */
1188         "IK", /* name */
1189         "bKinematicConstraint", /* struct name */
1190         NULL, /* free data */
1191         NULL, /* relink data */
1192         kinematic_id_looper, /* id looper */
1193         NULL, /* copy data */
1194         kinematic_new_data, /* new data */
1195         kinematic_get_tars, /* get constraint targets */
1196         kinematic_flush_tars, /* flush constraint targets */
1197         kinematic_get_tarmat, /* get target matrix */
1198         NULL /* evaluate - solved as separate loop */
1199 };
1200
1201 /* -------- Follow-Path Constraint ---------- */
1202
1203 static void followpath_new_data (void *cdata)
1204 {
1205         bFollowPathConstraint *data= (bFollowPathConstraint *)cdata;
1206         
1207         data->trackflag = TRACK_Y;
1208         data->upflag = UP_Z;
1209         data->offset = 0;
1210         data->followflag = 0;
1211 }
1212
1213 static void followpath_id_looper (bConstraint *con, ConstraintIDFunc func, void *userdata)
1214 {
1215         bFollowPathConstraint *data= con->data;
1216         
1217         /* target only */
1218         func(con, (ID**)&data->tar, userdata);
1219 }
1220
1221 static int followpath_get_tars (bConstraint *con, ListBase *list)
1222 {
1223         if (con && list) {
1224                 bFollowPathConstraint *data= con->data;
1225                 bConstraintTarget *ct;
1226                 
1227                 /* standard target-getting macro for single-target constraints without subtargets */
1228                 SINGLETARGETNS_GET_TARS(con, data->tar, ct, list)
1229                 
1230                 return 1;
1231         }
1232         
1233         return 0;
1234 }
1235
1236 static void followpath_flush_tars (bConstraint *con, ListBase *list, short nocopy)
1237 {
1238         if (con && list) {
1239                 bFollowPathConstraint *data= con->data;
1240                 bConstraintTarget *ct= list->first;
1241                 
1242                 /* the following macro is used for all standard single-target constraints */
1243                 SINGLETARGETNS_FLUSH_TARS(con, data->tar, ct, list, nocopy)
1244         }
1245 }
1246
1247 static void followpath_get_tarmat (bConstraint *con, bConstraintOb *cob, bConstraintTarget *ct, float UNUSED(ctime))
1248 {
1249         bFollowPathConstraint *data= con->data;
1250         
1251         if (VALID_CONS_TARGET(ct)) {
1252                 Curve *cu= ct->tar->data;
1253                 float vec[4], dir[3], radius;
1254                 float totmat[4][4]= MAT4_UNITY;
1255                 float curvetime;
1256
1257                 unit_m4(ct->matrix);
1258
1259                 /* note: when creating constraints that follow path, the curve gets the CU_PATH set now,
1260                  *              currently for paths to work it needs to go through the bevlist/displist system (ton) 
1261                  */
1262                 
1263                 /* only happens on reload file, but violates depsgraph still... fix! */
1264                 if (cu->path==NULL || cu->path->data==NULL)
1265                         makeDispListCurveTypes(cob->scene, ct->tar, 0);
1266                 
1267                 if (cu->path && cu->path->data) {
1268                         float quat[4];
1269                         if ((data->followflag & FOLLOWPATH_STATIC) == 0) {
1270                                 /* animated position along curve depending on time */
1271                                 if (cob->scene)
1272                                         curvetime= bsystem_time(cob->scene, ct->tar, cu->ctime, 0.0) - data->offset;
1273                                 else    
1274                                         curvetime= cu->ctime - data->offset;
1275                                 
1276                                 /* ctime is now a proper var setting of Curve which gets set by Animato like any other var that's animated,
1277                                  * but this will only work if it actually is animated... 
1278                                  *
1279                                  * we divide the curvetime calculated in the previous step by the length of the path, to get a time
1280                                  * factor, which then gets clamped to lie within 0.0 - 1.0 range
1281                                  */
1282                                 curvetime /= cu->pathlen;
1283                                 CLAMP(curvetime, 0.0f, 1.0f);
1284                         }
1285                         else {
1286                                 /* fixed position along curve */
1287                                 curvetime= data->offset_fac;
1288                         }
1289                         
1290                         if ( where_on_path(ct->tar, curvetime, vec, dir, (data->followflag & FOLLOWPATH_FOLLOW) ? quat : NULL, &radius, NULL) ) { /* quat_pt is quat or NULL*/
1291                                 if (data->followflag & FOLLOWPATH_FOLLOW) {
1292 #if 0
1293                                         float x1, q[4];
1294                                         vec_to_quat(quat, dir, (short)data->trackflag, (short)data->upflag);
1295                                         
1296                                         normalize_v3(dir);
1297                                         q[0]= (float)cos(0.5*vec[3]);
1298                                         x1= (float)sin(0.5*vec[3]);
1299                                         q[1]= -x1*dir[0];
1300                                         q[2]= -x1*dir[1];
1301                                         q[3]= -x1*dir[2];
1302                                         mul_qt_qtqt(quat, q, quat);
1303 #else
1304                                         quat_apply_track(quat, data->trackflag, data->upflag);
1305 #endif
1306
1307                                         quat_to_mat4(totmat, quat);
1308                                 }
1309
1310                                 if (data->followflag & FOLLOWPATH_RADIUS) {
1311                                         float tmat[4][4], rmat[4][4];
1312                                         scale_m4_fl(tmat, radius);
1313                                         mul_m4_m4m4(rmat, totmat, tmat);
1314                                         copy_m4_m4(totmat, rmat);
1315                                 }
1316                                 
1317                                 copy_v3_v3(totmat[3], vec);
1318                                 
1319                                 mul_serie_m4(ct->matrix, ct->tar->obmat, totmat, NULL, NULL, NULL, NULL, NULL, NULL);
1320                         }
1321                 }
1322         }
1323         else if (ct)
1324                 unit_m4(ct->matrix);
1325 }
1326
1327 static void followpath_evaluate (bConstraint *con, bConstraintOb *cob, ListBase *targets)
1328 {
1329         bConstraintTarget *ct= targets->first;
1330         
1331         /* only evaluate if there is a target */
1332         if (VALID_CONS_TARGET(ct)) {
1333                 float obmat[4][4];
1334                 float size[3];
1335                 bFollowPathConstraint *data= con->data;
1336                 
1337                 /* get Object transform (loc/rot/size) to determine transformation from path */
1338                 // TODO: this used to be local at one point, but is probably more useful as-is
1339                 copy_m4_m4(obmat, cob->matrix);
1340                 
1341                 /* get scaling of object before applying constraint */
1342                 mat4_to_size(size, cob->matrix);
1343                 
1344                 /* apply targetmat - containing location on path, and rotation */
1345                 mul_serie_m4(cob->matrix, ct->matrix, obmat, NULL, NULL, NULL, NULL, NULL, NULL);
1346                 
1347                 /* un-apply scaling caused by path */
1348                 if ((data->followflag & FOLLOWPATH_RADIUS)==0) { /* XXX - assume that scale correction means that radius will have some scale error in it - Campbell */
1349                         float obsize[3];
1350                         
1351                         mat4_to_size( obsize,cob->matrix);
1352                         if (obsize[0])
1353                                 mul_v3_fl(cob->matrix[0], size[0] / obsize[0]);
1354                         if (obsize[1])
1355                                 mul_v3_fl(cob->matrix[1], size[1] / obsize[1]);
1356                         if (obsize[2])
1357                                 mul_v3_fl(cob->matrix[2], size[2] / obsize[2]);
1358                 }
1359         }
1360 }
1361
1362 static bConstraintTypeInfo CTI_FOLLOWPATH = {
1363         CONSTRAINT_TYPE_FOLLOWPATH, /* type */
1364         sizeof(bFollowPathConstraint), /* size */
1365         "Follow Path", /* name */
1366         "bFollowPathConstraint", /* struct name */
1367         NULL, /* free data */
1368         NULL, /* relink data */
1369         followpath_id_looper, /* id looper */
1370         NULL, /* copy data */
1371         followpath_new_data, /* new data */
1372         followpath_get_tars, /* get constraint targets */
1373         followpath_flush_tars, /* flush constraint targets */
1374         followpath_get_tarmat, /* get target matrix */
1375         followpath_evaluate /* evaluate */
1376 };
1377
1378 /* --------- Limit Location --------- */
1379
1380
1381 static void loclimit_evaluate (bConstraint *con, bConstraintOb *cob, ListBase *UNUSED(targets))
1382 {
1383         bLocLimitConstraint *data = con->data;
1384         
1385         if (data->flag & LIMIT_XMIN) {
1386                 if (cob->matrix[3][0] < data->xmin)
1387                         cob->matrix[3][0] = data->xmin;
1388         }
1389         if (data->flag & LIMIT_XMAX) {
1390                 if (cob->matrix[3][0] > data->xmax)
1391                         cob->matrix[3][0] = data->xmax;
1392         }
1393         if (data->flag & LIMIT_YMIN) {
1394                 if (cob->matrix[3][1] < data->ymin)
1395                         cob->matrix[3][1] = data->ymin;
1396         }
1397         if (data->flag & LIMIT_YMAX) {
1398                 if (cob->matrix[3][1] > data->ymax)
1399                         cob->matrix[3][1] = data->ymax;
1400         }
1401         if (data->flag & LIMIT_ZMIN) {
1402                 if (cob->matrix[3][2] < data->zmin) 
1403                         cob->matrix[3][2] = data->zmin;
1404         }
1405         if (data->flag & LIMIT_ZMAX) {
1406                 if (cob->matrix[3][2] > data->zmax)
1407                         cob->matrix[3][2] = data->zmax;
1408         }
1409 }
1410
1411 static bConstraintTypeInfo CTI_LOCLIMIT = {
1412         CONSTRAINT_TYPE_LOCLIMIT, /* type */
1413         sizeof(bLocLimitConstraint), /* size */
1414         "Limit Location", /* name */
1415         "bLocLimitConstraint", /* struct name */
1416         NULL, /* free data */
1417         NULL, /* relink data */
1418         NULL, /* id looper */
1419         NULL, /* copy data */
1420         NULL, /* new data */
1421         NULL, /* get constraint targets */
1422         NULL, /* flush constraint targets */
1423         NULL, /* get target matrix */
1424         loclimit_evaluate /* evaluate */
1425 };
1426
1427 /* -------- Limit Rotation --------- */
1428
1429 static void rotlimit_evaluate (bConstraint *con, bConstraintOb *cob, ListBase *UNUSED(targets))
1430 {
1431         bRotLimitConstraint *data = con->data;
1432         float loc[3];
1433         float eul[3];
1434         float size[3];
1435         
1436         copy_v3_v3(loc, cob->matrix[3]);
1437         mat4_to_size(size, cob->matrix);
1438
1439         mat4_to_eulO(eul, cob->rotOrder, cob->matrix);
1440
1441         /* constraint data uses radians internally */
1442         
1443         /* limiting of euler values... */
1444         if (data->flag & LIMIT_XROT) {
1445                 if (eul[0] < data->xmin) 
1446                         eul[0] = data->xmin;
1447                         
1448                 if (eul[0] > data->xmax)
1449                         eul[0] = data->xmax;
1450         }
1451         if (data->flag & LIMIT_YROT) {
1452                 if (eul[1] < data->ymin)
1453                         eul[1] = data->ymin;
1454                         
1455                 if (eul[1] > data->ymax)
1456                         eul[1] = data->ymax;
1457         }
1458         if (data->flag & LIMIT_ZROT) {
1459                 if (eul[2] < data->zmin)
1460                         eul[2] = data->zmin;
1461                         
1462                 if (eul[2] > data->zmax)
1463                         eul[2] = data->zmax;
1464         }
1465                 
1466         loc_eulO_size_to_mat4(cob->matrix, loc, eul, size, cob->rotOrder);
1467 }
1468
1469 static bConstraintTypeInfo CTI_ROTLIMIT = {
1470         CONSTRAINT_TYPE_ROTLIMIT, /* type */
1471         sizeof(bRotLimitConstraint), /* size */
1472         "Limit Rotation", /* name */
1473         "bRotLimitConstraint", /* struct name */
1474         NULL, /* free data */
1475         NULL, /* relink data */
1476         NULL, /* id looper */
1477         NULL, /* copy data */
1478         NULL, /* new data */
1479         NULL, /* get constraint targets */
1480         NULL, /* flush constraint targets */
1481         NULL, /* get target matrix */
1482         rotlimit_evaluate /* evaluate */
1483 };
1484
1485 /* --------- Limit Scaling --------- */
1486
1487
1488 static void sizelimit_evaluate (bConstraint *con, bConstraintOb *cob, ListBase *UNUSED(targets))
1489 {
1490         bSizeLimitConstraint *data = con->data;
1491         float obsize[3], size[3];
1492         
1493         mat4_to_size( size,cob->matrix);
1494         mat4_to_size( obsize,cob->matrix);
1495         
1496         if (data->flag & LIMIT_XMIN) {
1497                 if (size[0] < data->xmin) 
1498                         size[0] = data->xmin;   
1499         }
1500         if (data->flag & LIMIT_XMAX) {
1501                 if (size[0] > data->xmax) 
1502                         size[0] = data->xmax;
1503         }
1504         if (data->flag & LIMIT_YMIN) {
1505                 if (size[1] < data->ymin) 
1506                         size[1] = data->ymin;   
1507         }
1508         if (data->flag & LIMIT_YMAX) {
1509                 if (size[1] > data->ymax) 
1510                         size[1] = data->ymax;
1511         }
1512         if (data->flag & LIMIT_ZMIN) {
1513                 if (size[2] < data->zmin) 
1514                         size[2] = data->zmin;   
1515         }
1516         if (data->flag & LIMIT_ZMAX) {
1517                 if (size[2] > data->zmax) 
1518                         size[2] = data->zmax;
1519         }
1520         
1521         if (obsize[0]) 
1522                 mul_v3_fl(cob->matrix[0], size[0]/obsize[0]);
1523         if (obsize[1]) 
1524                 mul_v3_fl(cob->matrix[1], size[1]/obsize[1]);
1525         if (obsize[2]) 
1526                 mul_v3_fl(cob->matrix[2], size[2]/obsize[2]);
1527 }
1528
1529 static bConstraintTypeInfo CTI_SIZELIMIT = {
1530         CONSTRAINT_TYPE_SIZELIMIT, /* type */
1531         sizeof(bSizeLimitConstraint), /* size */
1532         "Limit Scaling", /* name */
1533         "bSizeLimitConstraint", /* struct name */
1534         NULL, /* free data */
1535         NULL, /* relink data */
1536         NULL, /* id looper */
1537         NULL, /* copy data */
1538         NULL, /* new data */
1539         NULL, /* get constraint targets */
1540         NULL, /* flush constraint targets */
1541         NULL, /* get target matrix */
1542         sizelimit_evaluate /* evaluate */
1543 };
1544
1545 /* ----------- Copy Location ------------- */
1546
1547 static void loclike_new_data (void *cdata)
1548 {
1549         bLocateLikeConstraint *data= (bLocateLikeConstraint *)cdata;
1550         
1551         data->flag = LOCLIKE_X|LOCLIKE_Y|LOCLIKE_Z;
1552 }
1553
1554 static void loclike_id_looper (bConstraint *con, ConstraintIDFunc func, void *userdata)
1555 {
1556         bLocateLikeConstraint *data= con->data;
1557         
1558         /* target only */
1559         func(con, (ID**)&data->tar, userdata);
1560 }
1561
1562 static int loclike_get_tars (bConstraint *con, ListBase *list)
1563 {
1564         if (con && list) {
1565                 bLocateLikeConstraint *data= con->data;
1566                 bConstraintTarget *ct;
1567                 
1568                 /* standard target-getting macro for single-target constraints */
1569                 SINGLETARGET_GET_TARS(con, data->tar, data->subtarget, ct, list)
1570                 
1571                 return 1;
1572         }
1573         
1574         return 0;
1575 }
1576
1577 static void loclike_flush_tars (bConstraint *con, ListBase *list, short nocopy)
1578 {
1579         if (con && list) {
1580                 bLocateLikeConstraint *data= con->data;
1581                 bConstraintTarget *ct= list->first;
1582                 
1583                 /* the following macro is used for all standard single-target constraints */
1584                 SINGLETARGET_FLUSH_TARS(con, data->tar, data->subtarget, ct, list, nocopy)
1585         }
1586 }
1587
1588 static void loclike_evaluate (bConstraint *con, bConstraintOb *cob, ListBase *targets)
1589 {
1590         bLocateLikeConstraint *data= con->data;
1591         bConstraintTarget *ct= targets->first;
1592         
1593         if (VALID_CONS_TARGET(ct)) {
1594                 float offset[3] = {0.0f, 0.0f, 0.0f};
1595                 
1596                 if (data->flag & LOCLIKE_OFFSET)
1597                         copy_v3_v3(offset, cob->matrix[3]);
1598                         
1599                 if (data->flag & LOCLIKE_X) {
1600                         cob->matrix[3][0] = ct->matrix[3][0];
1601                         
1602                         if (data->flag & LOCLIKE_X_INVERT) cob->matrix[3][0] *= -1;
1603                         cob->matrix[3][0] += offset[0];
1604                 }
1605                 if (data->flag & LOCLIKE_Y) {
1606                         cob->matrix[3][1] = ct->matrix[3][1];
1607                         
1608                         if (data->flag & LOCLIKE_Y_INVERT) cob->matrix[3][1] *= -1;
1609                         cob->matrix[3][1] += offset[1];
1610                 }
1611                 if (data->flag & LOCLIKE_Z) {
1612                         cob->matrix[3][2] = ct->matrix[3][2];
1613                         
1614                         if (data->flag & LOCLIKE_Z_INVERT) cob->matrix[3][2] *= -1;
1615                         cob->matrix[3][2] += offset[2];
1616                 }
1617         }
1618 }
1619
1620 static bConstraintTypeInfo CTI_LOCLIKE = {
1621         CONSTRAINT_TYPE_LOCLIKE, /* type */
1622         sizeof(bLocateLikeConstraint), /* size */
1623         "Copy Location", /* name */
1624         "bLocateLikeConstraint", /* struct name */
1625         NULL, /* free data */
1626         NULL, /* relink data */
1627         loclike_id_looper, /* id looper */
1628         NULL, /* copy data */
1629         loclike_new_data, /* new data */
1630         loclike_get_tars, /* get constraint targets */
1631         loclike_flush_tars, /* flush constraint targets */
1632         default_get_tarmat, /* get target matrix */
1633         loclike_evaluate /* evaluate */
1634 };
1635
1636 /* ----------- Copy Rotation ------------- */
1637
1638 static void rotlike_new_data (void *cdata)
1639 {
1640         bRotateLikeConstraint *data= (bRotateLikeConstraint *)cdata;
1641         
1642         data->flag = ROTLIKE_X|ROTLIKE_Y|ROTLIKE_Z;
1643 }
1644
1645 static void rotlike_id_looper (bConstraint *con, ConstraintIDFunc func, void *userdata)
1646 {
1647         bChildOfConstraint *data= con->data;
1648         
1649         /* target only */
1650         func(con, (ID**)&data->tar, userdata);
1651 }
1652
1653 static int rotlike_get_tars (bConstraint *con, ListBase *list)
1654 {
1655         if (con && list) {
1656                 bRotateLikeConstraint *data= con->data;
1657                 bConstraintTarget *ct;
1658                 
1659                 /* standard target-getting macro for single-target constraints */
1660                 SINGLETARGET_GET_TARS(con, data->tar, data->subtarget, ct, list)
1661                 
1662                 return 1;
1663         }
1664         
1665         return 0;
1666 }
1667
1668 static void rotlike_flush_tars (bConstraint *con, ListBase *list, short nocopy)
1669 {
1670         if (con && list) {
1671                 bRotateLikeConstraint *data= con->data;
1672                 bConstraintTarget *ct= list->first;
1673                 
1674                 /* the following macro is used for all standard single-target constraints */
1675                 SINGLETARGET_FLUSH_TARS(con, data->tar, data->subtarget, ct, list, nocopy)
1676         }
1677 }
1678
1679 static void rotlike_evaluate (bConstraint *con, bConstraintOb *cob, ListBase *targets)
1680 {
1681         bRotateLikeConstraint *data= con->data;
1682         bConstraintTarget *ct= targets->first;
1683         
1684         if (VALID_CONS_TARGET(ct)) {
1685                 float   loc[3];
1686                 float   eul[3], obeul[3];
1687                 float   size[3];
1688                 
1689                 copy_v3_v3(loc, cob->matrix[3]);
1690                 mat4_to_size(size, cob->matrix);
1691                 
1692                 /* to allow compatible rotations, must get both rotations in the order of the owner... */
1693                 mat4_to_eulO(obeul, cob->rotOrder, cob->matrix);
1694                 /* we must get compatible eulers from the beginning because some of them can be modified below (see bug #21875) */
1695                 mat4_to_compatible_eulO(eul, obeul, cob->rotOrder, ct->matrix);
1696                 
1697                 if ((data->flag & ROTLIKE_X)==0)
1698                         eul[0] = obeul[0];
1699                 else {
1700                         if (data->flag & ROTLIKE_OFFSET)
1701                                 rotate_eulO(eul, cob->rotOrder, 'X', obeul[0]);
1702                         
1703                         if (data->flag & ROTLIKE_X_INVERT)
1704                                 eul[0] *= -1;
1705                 }
1706                 
1707                 if ((data->flag & ROTLIKE_Y)==0)
1708                         eul[1] = obeul[1];
1709                 else {
1710                         if (data->flag & ROTLIKE_OFFSET)
1711                                 rotate_eulO(eul, cob->rotOrder, 'Y', obeul[1]);
1712                         
1713                         if (data->flag & ROTLIKE_Y_INVERT)
1714                                 eul[1] *= -1;
1715                 }
1716                 
1717                 if ((data->flag & ROTLIKE_Z)==0)
1718                         eul[2] = obeul[2];
1719                 else {
1720                         if (data->flag & ROTLIKE_OFFSET)
1721                                 rotate_eulO(eul, cob->rotOrder, 'Z', obeul[2]);
1722                         
1723                         if (data->flag & ROTLIKE_Z_INVERT)
1724                                 eul[2] *= -1;
1725                 }
1726                 
1727                 /* good to make eulers compatible again, since we don't know how much they were changed above */
1728                 compatible_eul(eul, obeul);
1729                 loc_eulO_size_to_mat4(cob->matrix, loc, eul, size, cob->rotOrder);
1730         }
1731 }
1732
1733 static bConstraintTypeInfo CTI_ROTLIKE = {
1734         CONSTRAINT_TYPE_ROTLIKE, /* type */
1735         sizeof(bRotateLikeConstraint), /* size */
1736         "Copy Rotation", /* name */
1737         "bRotateLikeConstraint", /* struct name */
1738         NULL, /* free data */
1739         NULL, /* relink data */
1740         rotlike_id_looper, /* id looper */
1741         NULL, /* copy data */
1742         rotlike_new_data, /* new data */
1743         rotlike_get_tars, /* get constraint targets */
1744         rotlike_flush_tars, /* flush constraint targets */
1745         default_get_tarmat, /* get target matrix */
1746         rotlike_evaluate /* evaluate */
1747 };
1748
1749 /* ---------- Copy Scaling ---------- */
1750
1751 static void sizelike_new_data (void *cdata)
1752 {
1753         bSizeLikeConstraint *data= (bSizeLikeConstraint *)cdata;
1754         
1755         data->flag = SIZELIKE_X|SIZELIKE_Y|SIZELIKE_Z;
1756 }
1757
1758 static void sizelike_id_looper (bConstraint *con, ConstraintIDFunc func, void *userdata)
1759 {
1760         bSizeLikeConstraint *data= con->data;
1761         
1762         /* target only */
1763         func(con, (ID**)&data->tar, userdata);
1764 }
1765
1766 static int sizelike_get_tars (bConstraint *con, ListBase *list)
1767 {
1768         if (con && list) {
1769                 bSizeLikeConstraint *data= con->data;
1770                 bConstraintTarget *ct;
1771                 
1772                 /* standard target-getting macro for single-target constraints */
1773                 SINGLETARGET_GET_TARS(con, data->tar, data->subtarget, ct, list)
1774                 
1775                 return 1;
1776         }
1777         
1778         return 0;
1779 }
1780
1781 static void sizelike_flush_tars (bConstraint *con, ListBase *list, short nocopy)
1782 {
1783         if (con && list) {
1784                 bSizeLikeConstraint *data= con->data;
1785                 bConstraintTarget *ct= list->first;
1786                 
1787                 /* the following macro is used for all standard single-target constraints */
1788                 SINGLETARGET_FLUSH_TARS(con, data->tar, data->subtarget, ct, list, nocopy)
1789         }
1790 }
1791
1792 static void sizelike_evaluate (bConstraint *con, bConstraintOb *cob, ListBase *targets)
1793 {
1794         bSizeLikeConstraint *data= con->data;
1795         bConstraintTarget *ct= targets->first;
1796         
1797         if (VALID_CONS_TARGET(ct)) {
1798                 float obsize[3], size[3];
1799                 
1800                 mat4_to_size(size, ct->matrix);
1801                 mat4_to_size(obsize, cob->matrix);
1802                 
1803                 if ((data->flag & SIZELIKE_X) && (obsize[0] != 0)) {
1804                         if (data->flag & SIZELIKE_OFFSET) {
1805                                 size[0] += (obsize[0] - 1.0f);
1806                                 mul_v3_fl(cob->matrix[0], size[0] / obsize[0]);
1807                         }
1808                         else
1809                                 mul_v3_fl(cob->matrix[0], size[0] / obsize[0]);
1810                 }
1811                 if ((data->flag & SIZELIKE_Y) && (obsize[1] != 0)) {
1812                         if (data->flag & SIZELIKE_OFFSET) {
1813                                 size[1] += (obsize[1] - 1.0f);
1814                                 mul_v3_fl(cob->matrix[1], size[1] / obsize[1]);
1815                         }
1816                         else
1817                                 mul_v3_fl(cob->matrix[1], size[1] / obsize[1]);
1818                 }
1819                 if ((data->flag & SIZELIKE_Z) && (obsize[2] != 0)) {
1820                         if (data->flag & SIZELIKE_OFFSET) {
1821                                 size[2] += (obsize[2] - 1.0f);
1822                                 mul_v3_fl(cob->matrix[2], size[2] / obsize[2]);
1823                         }
1824                         else
1825                                 mul_v3_fl(cob->matrix[2], size[2] / obsize[2]);
1826                 }
1827         }
1828 }
1829
1830 static bConstraintTypeInfo CTI_SIZELIKE = {
1831         CONSTRAINT_TYPE_SIZELIKE, /* type */
1832         sizeof(bSizeLikeConstraint), /* size */
1833         "Copy Scale", /* name */
1834         "bSizeLikeConstraint", /* struct name */
1835         NULL, /* free data */
1836         NULL, /* relink data */
1837         sizelike_id_looper, /* id looper */
1838         NULL, /* copy data */
1839         sizelike_new_data, /* new data */
1840         sizelike_get_tars, /* get constraint targets */
1841         sizelike_flush_tars, /* flush constraint targets */
1842         default_get_tarmat, /* get target matrix */
1843         sizelike_evaluate /* evaluate */
1844 };
1845
1846 /* ----------- Copy Transforms ------------- */
1847
1848 static void translike_id_looper (bConstraint *con, ConstraintIDFunc func, void *userdata)
1849 {
1850         bTransLikeConstraint *data= con->data;
1851         
1852         /* target only */
1853         func(con, (ID**)&data->tar, userdata);
1854 }
1855
1856 static int translike_get_tars (bConstraint *con, ListBase *list)
1857 {
1858         if (con && list) {
1859                 bTransLikeConstraint *data= con->data;
1860                 bConstraintTarget *ct;
1861                 
1862                 /* standard target-getting macro for single-target constraints */
1863                 SINGLETARGET_GET_TARS(con, data->tar, data->subtarget, ct, list)
1864                 
1865                 return 1;
1866         }
1867         
1868         return 0;
1869 }
1870
1871 static void translike_flush_tars (bConstraint *con, ListBase *list, short nocopy)
1872 {
1873         if (con && list) {
1874                 bTransLikeConstraint *data= con->data;
1875                 bConstraintTarget *ct= list->first;
1876                 
1877                 /* the following macro is used for all standard single-target constraints */
1878                 SINGLETARGET_FLUSH_TARS(con, data->tar, data->subtarget, ct, list, nocopy)
1879         }
1880 }
1881
1882 static void translike_evaluate (bConstraint *UNUSED(con), bConstraintOb *cob, ListBase *targets)
1883 {
1884         bConstraintTarget *ct= targets->first;
1885         
1886         if (VALID_CONS_TARGET(ct)) {
1887                 /* just copy the entire transform matrix of the target */
1888                 copy_m4_m4(cob->matrix, ct->matrix);
1889         }
1890 }
1891
1892 static bConstraintTypeInfo CTI_TRANSLIKE = {
1893         CONSTRAINT_TYPE_TRANSLIKE, /* type */
1894         sizeof(bTransLikeConstraint), /* size */
1895         "Copy Transforms", /* name */
1896         "bTransLikeConstraint", /* struct name */
1897         NULL, /* free data */
1898         NULL, /* relink data */
1899         translike_id_looper, /* id looper */
1900         NULL, /* copy data */
1901         NULL, /* new data */
1902         translike_get_tars, /* get constraint targets */
1903         translike_flush_tars, /* flush constraint targets */
1904         default_get_tarmat, /* get target matrix */
1905         translike_evaluate /* evaluate */
1906 };
1907
1908 /* ---------- Maintain Volume ---------- */
1909
1910 static void samevolume_new_data (void *cdata)
1911 {
1912         bSameVolumeConstraint *data= (bSameVolumeConstraint *)cdata;
1913
1914         data->flag = SAMEVOL_Y;
1915         data->volume = 1.0f;
1916 }
1917
1918 static void samevolume_evaluate (bConstraint *con, bConstraintOb *cob, ListBase *UNUSED(targets))
1919 {
1920         bSameVolumeConstraint *data= con->data;
1921
1922         float volume = data->volume;
1923         float fac = 1.0f;
1924         float obsize[3];
1925
1926         mat4_to_size(obsize, cob->matrix);
1927         
1928         /* calculate normalising scale factor for non-essential values */
1929         if (obsize[data->flag] != 0) 
1930                 fac = sqrtf(volume / obsize[data->flag]) / obsize[data->flag];
1931         
1932         /* apply scaling factor to the channels not being kept */
1933         switch (data->flag) {
1934                 case SAMEVOL_X:
1935                         mul_v3_fl(cob->matrix[1], fac);
1936                         mul_v3_fl(cob->matrix[2], fac);
1937                         break;
1938                 case SAMEVOL_Y:
1939                         mul_v3_fl(cob->matrix[0], fac);
1940                         mul_v3_fl(cob->matrix[2], fac);
1941                         break;
1942                 case SAMEVOL_Z:
1943                         mul_v3_fl(cob->matrix[0], fac);
1944                         mul_v3_fl(cob->matrix[1], fac);
1945                         break;
1946         }
1947 }
1948
1949 static bConstraintTypeInfo CTI_SAMEVOL = {
1950         CONSTRAINT_TYPE_SAMEVOL, /* type */
1951         sizeof(bSameVolumeConstraint), /* size */
1952         "Maintain Volume", /* name */
1953         "bSameVolumeConstraint", /* struct name */
1954         NULL, /* free data */
1955         NULL, /* relink data */
1956         NULL, /* id looper */
1957         NULL, /* copy data */
1958         samevolume_new_data, /* new data */
1959         NULL, /* get constraint targets */
1960         NULL, /* flush constraint targets */
1961         NULL, /* get target matrix */
1962         samevolume_evaluate /* evaluate */
1963 };
1964
1965 /* ----------- Python Constraint -------------- */
1966
1967 static void pycon_free (bConstraint *con)
1968 {
1969         bPythonConstraint *data= con->data;
1970         
1971         /* id-properties */
1972         IDP_FreeProperty(data->prop);
1973         MEM_freeN(data->prop);
1974         
1975         /* multiple targets */
1976         BLI_freelistN(&data->targets);
1977 }       
1978
1979 static void pycon_relink (bConstraint *con)
1980 {
1981         bPythonConstraint *data= con->data;
1982         
1983         ID_NEW(data->text);
1984 }
1985
1986 static void pycon_copy (bConstraint *con, bConstraint *srccon)
1987 {
1988         bPythonConstraint *pycon = (bPythonConstraint *)con->data;
1989         bPythonConstraint *opycon = (bPythonConstraint *)srccon->data;
1990         
1991         pycon->prop = IDP_CopyProperty(opycon->prop);
1992         BLI_duplicatelist(&pycon->targets, &opycon->targets);
1993 }
1994
1995 static void pycon_new_data (void *cdata)
1996 {
1997         bPythonConstraint *data= (bPythonConstraint *)cdata;
1998         
1999         /* everything should be set correctly by calloc, except for the prop->type constant.*/
2000         data->prop = MEM_callocN(sizeof(IDProperty), "PyConstraintProps");
2001         data->prop->type = IDP_GROUP;
2002 }
2003
2004 static int pycon_get_tars (bConstraint *con, ListBase *list)
2005 {
2006         if (con && list) {
2007                 bPythonConstraint *data= con->data;
2008                 
2009                 list->first = data->targets.first;
2010                 list->last = data->targets.last;
2011                 
2012                 return data->tarnum;
2013         }
2014         
2015         return 0;
2016 }
2017
2018 static void pycon_id_looper (bConstraint *con, ConstraintIDFunc func, void *userdata)
2019 {
2020         bPythonConstraint *data= con->data;
2021         bConstraintTarget *ct;
2022         
2023         /* targets */
2024         for (ct= data->targets.first; ct; ct= ct->next)
2025                 func(con, (ID**)&ct->tar, userdata);
2026                 
2027         /* script */
2028         func(con, (ID**)&data->text, userdata);
2029 }
2030
2031 /* Whether this approach is maintained remains to be seen (aligorith) */
2032 static void pycon_get_tarmat (bConstraint *con, bConstraintOb *cob, bConstraintTarget *ct, float UNUSED(ctime))
2033 {
2034 #ifdef WITH_PYTHON
2035         bPythonConstraint *data= con->data;
2036 #endif
2037
2038         if (VALID_CONS_TARGET(ct)) {
2039                 /* special exception for curves - depsgraph issues */
2040                 if (ct->tar->type == OB_CURVE) {
2041                         Curve *cu= ct->tar->data;
2042                         
2043                         /* this check is to make sure curve objects get updated on file load correctly.*/
2044                         if (cu->path==NULL || cu->path->data==NULL) /* only happens on reload file, but violates depsgraph still... fix! */
2045                                 makeDispListCurveTypes(cob->scene, ct->tar, 0);                         
2046                 }
2047                 
2048                 /* firstly calculate the matrix the normal way, then let the py-function override
2049                  * this matrix if it needs to do so
2050                  */
2051                 constraint_target_to_mat4(cob->scene, ct->tar, ct->subtarget, ct->matrix, CONSTRAINT_SPACE_WORLD, ct->space, con->headtail);
2052                 
2053                 /* only execute target calculation if allowed */
2054 #ifdef WITH_PYTHON
2055                 if (G.f & G_SCRIPT_AUTOEXEC)
2056                         BPY_pyconstraint_target(data, ct);
2057 #endif
2058         }
2059         else if (ct)
2060                 unit_m4(ct->matrix);
2061 }
2062
2063 static void pycon_evaluate (bConstraint *con, bConstraintOb *cob, ListBase *targets)
2064 {
2065 #ifndef WITH_PYTHON
2066         (void)con; (void)cob; (void)targets; /* unused */
2067         return;
2068 #else
2069         bPythonConstraint *data= con->data;
2070         
2071         /* only evaluate in python if we're allowed to do so */
2072         if ((G.f & G_SCRIPT_AUTOEXEC)==0)  return;
2073         
2074 /* currently removed, until I this can be re-implemented for multiple targets */
2075 #if 0
2076         /* Firstly, run the 'driver' function which has direct access to the objects involved 
2077          * Technically, this is potentially dangerous as users may abuse this and cause dependency-problems,
2078          * but it also allows certain 'clever' rigging hacks to work.
2079          */
2080         BPY_pyconstraint_driver(data, cob, targets);
2081 #endif
2082         
2083         /* Now, run the actual 'constraint' function, which should only access the matrices */
2084         BPY_pyconstraint_exec(data, cob, targets);
2085 #endif /* WITH_PYTHON */
2086 }
2087
2088 static bConstraintTypeInfo CTI_PYTHON = {
2089         CONSTRAINT_TYPE_PYTHON, /* type */
2090         sizeof(bPythonConstraint), /* size */
2091         "Script", /* name */
2092         "bPythonConstraint", /* struct name */
2093         pycon_free, /* free data */
2094         pycon_relink, /* relink data */
2095         pycon_id_looper, /* id looper */
2096         pycon_copy, /* copy data */
2097         pycon_new_data, /* new data */
2098         pycon_get_tars, /* get constraint targets */
2099         NULL, /* flush constraint targets */
2100         pycon_get_tarmat, /* get target matrix */
2101         pycon_evaluate /* evaluate */
2102 };
2103
2104 /* -------- Action Constraint ----------- */
2105
2106 static void actcon_relink (bConstraint *con)
2107 {
2108         bActionConstraint *data= con->data;
2109         ID_NEW(data->act);
2110 }
2111
2112 static void actcon_new_data (void *cdata)
2113 {
2114         bActionConstraint *data= (bActionConstraint *)cdata;
2115         
2116         /* set type to 20 (Loc X), as 0 is Rot X for backwards compatability */
2117         data->type = 20;
2118 }
2119
2120 static void actcon_id_looper (bConstraint *con, ConstraintIDFunc func, void *userdata)
2121 {
2122         bActionConstraint *data= con->data;
2123         
2124         /* target */
2125         func(con, (ID**)&data->tar, userdata);
2126         
2127         /* action */
2128         func(con, (ID**)&data->act, userdata);
2129 }
2130
2131 static int actcon_get_tars (bConstraint *con, ListBase *list)
2132 {
2133         if (con && list) {
2134                 bActionConstraint *data= con->data;
2135                 bConstraintTarget *ct;
2136                 
2137                 /* standard target-getting macro for single-target constraints */
2138                 SINGLETARGET_GET_TARS(con, data->tar, data->subtarget, ct, list)
2139                 
2140                 return 1;
2141         }
2142         
2143         return 0;
2144 }
2145
2146 static void actcon_flush_tars (bConstraint *con, ListBase *list, short nocopy)
2147 {
2148         if (con && list) {
2149                 bActionConstraint *data= con->data;
2150                 bConstraintTarget *ct= list->first;
2151                 
2152                 /* the following macro is used for all standard single-target constraints */
2153                 SINGLETARGET_FLUSH_TARS(con, data->tar, data->subtarget, ct, list, nocopy)
2154         }
2155 }
2156
2157 static void actcon_get_tarmat (bConstraint *con, bConstraintOb *cob, bConstraintTarget *ct, float UNUSED(ctime))
2158 {
2159         bActionConstraint *data = con->data;
2160         
2161         if (VALID_CONS_TARGET(ct)) {
2162                 float tempmat[4][4], vec[3];
2163                 float s, t;
2164                 short axis;
2165                 
2166                 /* initialise return matrix */
2167                 unit_m4(ct->matrix);
2168                 
2169                 /* get the transform matrix of the target */
2170                 constraint_target_to_mat4(cob->scene, ct->tar, ct->subtarget, tempmat, CONSTRAINT_SPACE_WORLD, ct->space, con->headtail);
2171                 
2172                 /* determine where in transform range target is */
2173                 /* data->type is mapped as follows for backwards compatability:
2174                  *      00,01,02        - rotation (it used to be like this)
2175                  *      10,11,12        - scaling
2176                  *      20,21,22        - location
2177                  */
2178                 if (data->type < 10) {
2179                         /* extract rotation (is in whatever space target should be in) */
2180                         mat4_to_eul(vec, tempmat);
2181                         mul_v3_fl(vec, (float)(180.0/M_PI)); /* rad -> deg */
2182                         axis= data->type;
2183                 }
2184                 else if (data->type < 20) {
2185                         /* extract scaling (is in whatever space target should be in) */
2186                         mat4_to_size(vec, tempmat);
2187                         axis= data->type - 10;
2188                 }
2189                 else {
2190                         /* extract location */
2191                         copy_v3_v3(vec, tempmat[3]);
2192                         axis= data->type - 20;
2193                 }
2194                 
2195                 /* Target defines the animation */
2196                 s = (vec[axis]-data->min) / (data->max-data->min);
2197                 CLAMP(s, 0, 1);
2198                 t = (s * (data->end-data->start)) + data->start;
2199                 
2200                 if (G.f & G_DEBUG)
2201                         printf("do Action Constraint %s - Ob %s Pchan %s \n", con->name, cob->ob->id.name+2, (cob->pchan)?cob->pchan->name:NULL);
2202                 
2203                 /* Get the appropriate information from the action */
2204                 if (cob->type == CONSTRAINT_OBTYPE_BONE) {
2205                         Object workob;
2206                         bPose *pose;
2207                         bPoseChannel *pchan, *tchan;
2208                         
2209                         /* make a temporary pose and evaluate using that */
2210                         pose = MEM_callocN(sizeof(bPose), "pose");
2211                         
2212                         /* make a copy of the bone of interest in the temp pose before evaluating action, so that it can get set 
2213                          *      - we need to manually copy over a few settings, including rotation order, otherwise this fails
2214                          */
2215                         pchan = cob->pchan;
2216                         
2217                         tchan= verify_pose_channel(pose, pchan->name);
2218                         tchan->rotmode= pchan->rotmode;
2219                         
2220                         /* evaluate action using workob (it will only set the PoseChannel in question) */
2221                         what_does_obaction(cob->scene, cob->ob, &workob, pose, data->act, pchan->name, t);
2222                         
2223                         /* convert animation to matrices for use here */
2224                         pchan_calc_mat(tchan);
2225                         copy_m4_m4(ct->matrix, tchan->chan_mat);
2226                         
2227                         /* Clean up */
2228                         free_pose(pose);
2229                 }
2230                 else if (cob->type == CONSTRAINT_OBTYPE_OBJECT) {
2231                         Object workob;
2232                         
2233                         /* evaluate using workob */
2234                         // FIXME: we don't have any consistent standards on limiting effects on object...
2235                         what_does_obaction(cob->scene, cob->ob, &workob, NULL, data->act, NULL, t);
2236                         object_to_mat4(&workob, ct->matrix);
2237                 }
2238                 else {
2239                         /* behaviour undefined... */
2240                         puts("Error: unknown owner type for Action Constraint");
2241                 }
2242         }
2243 }
2244
2245 static void actcon_evaluate (bConstraint *UNUSED(con), bConstraintOb *cob, ListBase *targets)
2246 {
2247         bConstraintTarget *ct= targets->first;
2248         
2249         if (VALID_CONS_TARGET(ct)) {
2250                 float temp[4][4];
2251                 
2252                 /* Nice and simple... we just need to multiply the matrices, as the get_target_matrix
2253                  * function has already taken care of everything else.
2254                  */
2255                 copy_m4_m4(temp, cob->matrix);
2256                 mul_m4_m4m4(cob->matrix, ct->matrix, temp);
2257         }
2258 }
2259
2260 static bConstraintTypeInfo CTI_ACTION = {
2261         CONSTRAINT_TYPE_ACTION, /* type */
2262         sizeof(bActionConstraint), /* size */
2263         "Action", /* name */
2264         "bActionConstraint", /* struct name */
2265         NULL, /* free data */
2266         actcon_relink, /* relink data */
2267         actcon_id_looper, /* id looper */
2268         NULL, /* copy data */
2269         actcon_new_data, /* new data */
2270         actcon_get_tars, /* get constraint targets */
2271         actcon_flush_tars, /* flush constraint targets */
2272         actcon_get_tarmat, /* get target matrix */
2273         actcon_evaluate /* evaluate */
2274 };
2275
2276 /* --------- Locked Track ---------- */
2277
2278 static void locktrack_new_data (void *cdata)
2279 {
2280         bLockTrackConstraint *data= (bLockTrackConstraint *)cdata;
2281         
2282         data->trackflag = TRACK_Y;
2283         data->lockflag = LOCK_Z;
2284 }       
2285
2286 static void locktrack_id_looper (bConstraint *con, ConstraintIDFunc func, void *userdata)
2287 {
2288         bLockTrackConstraint *data= con->data;
2289         
2290         /* target only */
2291         func(con, (ID**)&data->tar, userdata);
2292 }
2293
2294 static int locktrack_get_tars (bConstraint *con, ListBase *list)
2295 {
2296         if (con && list) {
2297                 bLockTrackConstraint *data= con->data;
2298                 bConstraintTarget *ct;
2299                 
2300                 /* the following macro is used for all standard single-target constraints */
2301                 SINGLETARGET_GET_TARS(con, data->tar, data->subtarget, ct, list)
2302                 
2303                 return 1;
2304         }
2305         
2306         return 0;
2307 }
2308
2309 static void locktrack_flush_tars (bConstraint *con, ListBase *list, short nocopy)
2310 {
2311         if (con && list) {
2312                 bLockTrackConstraint *data= con->data;
2313                 bConstraintTarget *ct= list->first;
2314                 
2315                 /* the following macro is used for all standard single-target constraints */
2316                 SINGLETARGET_FLUSH_TARS(con, data->tar, data->subtarget, ct, list, nocopy)
2317         }
2318 }
2319
2320 static void locktrack_evaluate (bConstraint *con, bConstraintOb *cob, ListBase *targets)
2321 {
2322         bLockTrackConstraint *data= con->data;
2323         bConstraintTarget *ct= targets->first;
2324         
2325         if (VALID_CONS_TARGET(ct)) {
2326                 float vec[3],vec2[3];
2327                 float totmat[3][3];
2328                 float tmpmat[3][3];
2329                 float invmat[3][3];
2330                 float tmat[4][4];
2331                 float mdet;
2332                 
2333                 /* Vector object -> target */
2334                 sub_v3_v3v3(vec, ct->matrix[3], cob->matrix[3]);
2335                 switch (data->lockflag){
2336                 case LOCK_X: /* LOCK X */
2337                 {
2338                         switch (data->trackflag) {
2339                                 case TRACK_Y: /* LOCK X TRACK Y */
2340                                 {
2341                                         /* Projection of Vector on the plane */
2342                                         project_v3_v3v3(vec2, vec, cob->matrix[0]);
2343                                         sub_v3_v3v3(totmat[1], vec, vec2);
2344                                         normalize_v3(totmat[1]);
2345                                         
2346                                         /* the x axis is fixed */
2347                                         normalize_v3_v3(totmat[0], cob->matrix[0]);
2348                                         
2349                                         /* the z axis gets mapped onto a third orthogonal vector */
2350                                         cross_v3_v3v3(totmat[2], totmat[0], totmat[1]);
2351                                 }
2352                                         break;
2353                                 case TRACK_Z: /* LOCK X TRACK Z */
2354                                 {
2355                                         /* Projection of Vector on the plane */
2356                                         project_v3_v3v3(vec2, vec, cob->matrix[0]);
2357                                         sub_v3_v3v3(totmat[2], vec, vec2);
2358                                         normalize_v3(totmat[2]);
2359                                         
2360                                         /* the x axis is fixed */
2361                                         normalize_v3_v3(totmat[0], cob->matrix[0]);
2362                                         
2363                                         /* the z axis gets mapped onto a third orthogonal vector */
2364                                         cross_v3_v3v3(totmat[1], totmat[2], totmat[0]);
2365                                 }
2366                                         break;
2367                                 case TRACK_nY: /* LOCK X TRACK -Y */
2368                                 {
2369                                         /* Projection of Vector on the plane */
2370                                         project_v3_v3v3(vec2, vec, cob->matrix[0]);
2371                                         sub_v3_v3v3(totmat[1], vec, vec2);
2372                                         normalize_v3(totmat[1]);
2373                                         negate_v3(totmat[1]);
2374                                         
2375                                         /* the x axis is fixed */
2376                                         normalize_v3_v3(totmat[0], cob->matrix[0]);
2377                                         
2378                                         /* the z axis gets mapped onto a third orthogonal vector */
2379                                         cross_v3_v3v3(totmat[2], totmat[0], totmat[1]);
2380                                 }
2381                                         break;
2382                                 case TRACK_nZ: /* LOCK X TRACK -Z */
2383                                 {
2384                                         /* Projection of Vector on the plane */
2385                                         project_v3_v3v3(vec2, vec, cob->matrix[0]);
2386                                         sub_v3_v3v3(totmat[2], vec, vec2);
2387                                         normalize_v3(totmat[2]);
2388                                         negate_v3(totmat[2]);
2389                                                 
2390                                         /* the x axis is fixed */
2391                                         normalize_v3_v3(totmat[0], cob->matrix[0]);
2392                                                 
2393                                         /* the z axis gets mapped onto a third orthogonal vector */
2394                                         cross_v3_v3v3(totmat[1], totmat[2], totmat[0]);
2395                                 }
2396                                         break;
2397                                 default:
2398                                 {
2399                                         unit_m3(totmat);
2400                                 }
2401                                         break;
2402                         }
2403                 }
2404                         break;
2405                 case LOCK_Y: /* LOCK Y */
2406                 {
2407                         switch (data->trackflag) {
2408                                 case TRACK_X: /* LOCK Y TRACK X */
2409                                 {
2410                                         /* Projection of Vector on the plane */
2411                                         project_v3_v3v3(vec2, vec, cob->matrix[1]);
2412                                         sub_v3_v3v3(totmat[0], vec, vec2);
2413                                         normalize_v3(totmat[0]);
2414                                         
2415                                         /* the y axis is fixed */
2416                                         normalize_v3_v3(totmat[1], cob->matrix[1]);
2417
2418                                         /* the z axis gets mapped onto a third orthogonal vector */
2419                                         cross_v3_v3v3(totmat[2], totmat[0], totmat[1]);
2420                                 }
2421                                         break;
2422                                 case TRACK_Z: /* LOCK Y TRACK Z */
2423                                 {
2424                                         /* Projection of Vector on the plane */
2425                                         project_v3_v3v3(vec2, vec, cob->matrix[1]);
2426                                         sub_v3_v3v3(totmat[2], vec, vec2);
2427                                         normalize_v3(totmat[2]);
2428                                         
2429                                         /* the y axis is fixed */
2430                                         normalize_v3_v3(totmat[1], cob->matrix[1]);
2431                                         
2432                                         /* the z axis gets mapped onto a third orthogonal vector */
2433                                         cross_v3_v3v3(totmat[0], totmat[1], totmat[2]);
2434                                 }
2435                                         break;
2436                                 case TRACK_nX: /* LOCK Y TRACK -X */
2437                                 {
2438                                         /* Projection of Vector on the plane */
2439                                         project_v3_v3v3(vec2, vec, cob->matrix[1]);
2440                                         sub_v3_v3v3(totmat[0], vec, vec2);
2441                                         normalize_v3(totmat[0]);
2442                                         negate_v3(totmat[0]);
2443                                         
2444                                         /* the y axis is fixed */
2445                                         normalize_v3_v3(totmat[1], cob->matrix[1]);
2446                                         
2447                                         /* the z axis gets mapped onto a third orthogonal vector */
2448                                         cross_v3_v3v3(totmat[2], totmat[0], totmat[1]);
2449                                 }
2450                                         break;
2451                                 case TRACK_nZ: /* LOCK Y TRACK -Z */
2452                                 {
2453                                         /* Projection of Vector on the plane */
2454                                         project_v3_v3v3(vec2, vec, cob->matrix[1]);
2455                                         sub_v3_v3v3(totmat[2], vec, vec2);
2456                                         normalize_v3(totmat[2]);
2457                                         negate_v3(totmat[2]);
2458                                         
2459                                         /* the y axis is fixed */
2460                                         normalize_v3_v3(totmat[1], cob->matrix[1]);
2461                                         
2462                                         /* the z axis gets mapped onto a third orthogonal vector */
2463                                         cross_v3_v3v3(totmat[0], totmat[1], totmat[2]);
2464                                 }
2465                                         break;
2466                                 default:
2467                                 {
2468                                         unit_m3(totmat);
2469                                 }
2470                                         break;
2471                         }
2472                 }
2473                         break;
2474                 case LOCK_Z: /* LOCK Z */
2475                 {
2476                         switch (data->trackflag) {
2477                                 case TRACK_X: /* LOCK Z TRACK X */
2478                                 {
2479                                         /* Projection of Vector on the plane */
2480                                         project_v3_v3v3(vec2, vec, cob->matrix[2]);
2481                                         sub_v3_v3v3(totmat[0], vec, vec2);
2482                                         normalize_v3(totmat[0]);
2483                                         
2484                                         /* the z axis is fixed */
2485                                         normalize_v3_v3(totmat[2], cob->matrix[2]);
2486                                         
2487                                         /* the x axis gets mapped onto a third orthogonal vector */
2488                                         cross_v3_v3v3(totmat[1], totmat[2], totmat[0]);
2489                                 }
2490                                         break;
2491                                 case TRACK_Y: /* LOCK Z TRACK Y */
2492                                 {
2493                                         /* Projection of Vector on the plane */
2494                                         project_v3_v3v3(vec2, vec, cob->matrix[2]);
2495                                         sub_v3_v3v3(totmat[1], vec, vec2);
2496                                         normalize_v3(totmat[1]);
2497                                         
2498                                         /* the z axis is fixed */
2499                                         normalize_v3_v3(totmat[2], cob->matrix[2]);
2500                                                 
2501                                         /* the x axis gets mapped onto a third orthogonal vector */
2502                                         cross_v3_v3v3(totmat[0], totmat[1], totmat[2]);
2503                                 }
2504                                         break;
2505                                 case TRACK_nX: /* LOCK Z TRACK -X */
2506                                 {
2507                                         /* Projection of Vector on the plane */
2508                                         project_v3_v3v3(vec2, vec, cob->matrix[2]);
2509                                         sub_v3_v3v3(totmat[0], vec, vec2);
2510                                         normalize_v3(totmat[0]);
2511                                         negate_v3(totmat[0]);
2512                                         
2513                                         /* the z axis is fixed */
2514                                         normalize_v3_v3(totmat[2], cob->matrix[2]);
2515                                         
2516                                         /* the x axis gets mapped onto a third orthogonal vector */
2517                                         cross_v3_v3v3(totmat[1], totmat[2], totmat[0]);
2518                                 }
2519                                         break;
2520                                 case TRACK_nY: /* LOCK Z TRACK -Y */
2521                                 {
2522                                         /* Projection of Vector on the plane */
2523                                         project_v3_v3v3(vec2, vec, cob->matrix[2]);
2524                                         sub_v3_v3v3(totmat[1], vec, vec2);
2525                                         normalize_v3(totmat[1]);
2526                                         negate_v3(totmat[1]);
2527                                         
2528                                         /* the z axis is fixed */
2529                                         normalize_v3_v3(totmat[2], cob->matrix[2]);
2530                                                 
2531                                         /* the x axis gets mapped onto a third orthogonal vector */
2532                                         cross_v3_v3v3(totmat[0], totmat[1], totmat[2]);
2533                                 }
2534                                         break;
2535                                 default:
2536                                 {
2537                                         unit_m3(totmat);
2538                                 }
2539                                         break;
2540                         }
2541                 }
2542                         break;
2543                 default:
2544                         {
2545                                 unit_m3(totmat);
2546                         }
2547                         break;
2548                 }
2549                 /* Block to keep matrix heading */
2550                 copy_m3_m4(tmpmat, cob->matrix);
2551                 normalize_m3(tmpmat);
2552                 invert_m3_m3(invmat, tmpmat);
2553                 mul_m3_m3m3(tmpmat, totmat, invmat);
2554                 totmat[0][0] = tmpmat[0][0];totmat[0][1] = tmpmat[0][1];totmat[0][2] = tmpmat[0][2];
2555                 totmat[1][0] = tmpmat[1][0];totmat[1][1] = tmpmat[1][1];totmat[1][2] = tmpmat[1][2];
2556                 totmat[2][0] = tmpmat[2][0];totmat[2][1] = tmpmat[2][1];totmat[2][2] = tmpmat[2][2];
2557                 
2558                 copy_m4_m4(tmat, cob->matrix);
2559                 
2560                 mdet = determinant_m3(  totmat[0][0],totmat[0][1],totmat[0][2],
2561                                                 totmat[1][0],totmat[1][1],totmat[1][2],
2562                                                 totmat[2][0],totmat[2][1],totmat[2][2]);
2563                 if (mdet==0) {
2564                         unit_m3(totmat);
2565                 }
2566                 
2567                 /* apply out transformaton to the object */
2568                 mul_m4_m3m4(cob->matrix, totmat, tmat);
2569         }
2570 }
2571
2572 static bConstraintTypeInfo CTI_LOCKTRACK = {
2573         CONSTRAINT_TYPE_LOCKTRACK, /* type */
2574         sizeof(bLockTrackConstraint), /* size */
2575         "Locked Track", /* name */
2576         "bLockTrackConstraint", /* struct name */
2577         NULL, /* free data */
2578         NULL, /* relink data */
2579         locktrack_id_looper, /* id looper */
2580         NULL, /* copy data */
2581         locktrack_new_data, /* new data */
2582         locktrack_get_tars, /* get constraint targets */
2583         locktrack_flush_tars, /* flush constraint targets */
2584         default_get_tarmat, /* get target matrix */
2585         locktrack_evaluate /* evaluate */
2586 };
2587
2588 /* ---------- Limit Distance Constraint ----------- */
2589
2590 static void distlimit_new_data (void *cdata)
2591 {
2592         bDistLimitConstraint *data= (bDistLimitConstraint *)cdata;
2593         
2594         data->dist= 0.0f;
2595 }
2596
2597 static void distlimit_id_looper (bConstraint *con, ConstraintIDFunc func, void *userdata)
2598 {
2599         bDistLimitConstraint *data= con->data;
2600         
2601         /* target only */
2602         func(con, (ID**)&data->tar, userdata);
2603 }
2604
2605 static int distlimit_get_tars (bConstraint *con, ListBase *list)
2606 {
2607         if (con && list) {
2608                 bDistLimitConstraint *data= con->data;
2609                 bConstraintTarget *ct;
2610                 
2611                 /* standard target-getting macro for single-target constraints */
2612                 SINGLETARGET_GET_TARS(con, data->tar, data->subtarget, ct, list)
2613                 
2614                 return 1;
2615         }
2616         
2617         return 0;
2618 }
2619
2620 static void distlimit_flush_tars (bConstraint *con, ListBase *list, short nocopy)
2621 {
2622         if (con && list) {
2623                 bDistLimitConstraint *data= con->data;
2624                 bConstraintTarget *ct= list->first;
2625                 
2626                 /* the following macro is used for all standard single-target constraints */
2627                 SINGLETARGET_FLUSH_TARS(con, data->tar, data->subtarget, ct, list, nocopy)
2628         }
2629 }
2630
2631 static void distlimit_evaluate (bConstraint *con, bConstraintOb *cob, ListBase *targets)
2632 {
2633         bDistLimitConstraint *data= con->data;
2634         bConstraintTarget *ct= targets->first;
2635         
2636         /* only evaluate if there is a target */
2637         if (VALID_CONS_TARGET(ct)) {
2638                 float dvec[3], dist=0.0f, sfac=1.0f;
2639                 short clamp_surf= 0;
2640                 
2641                 /* calculate our current distance from the target */
2642                 dist= len_v3v3(cob->matrix[3], ct->matrix[3]);
2643                 
2644                 /* set distance (flag is only set when user demands it) */
2645                 if (data->dist == 0)
2646                         data->dist= dist;
2647                 
2648                 /* check if we're which way to clamp from, and calculate interpolation factor (if needed) */
2649                 if (data->mode == LIMITDIST_OUTSIDE) {
2650                         /* if inside, then move to surface */
2651                         if (dist <= data->dist) {
2652                                 clamp_surf= 1;
2653                                 sfac= data->dist / dist;
2654                         }
2655                         /* if soft-distance is enabled, start fading once owner is dist+softdist from the target */
2656                         else if (data->flag & LIMITDIST_USESOFT) {
2657                                 if (dist <= (data->dist + data->soft)) {
2658                                         
2659                                 }
2660                         }
2661                 }
2662                 else if (data->mode == LIMITDIST_INSIDE) {
2663                         /* if outside, then move to surface */
2664                         if (dist >= data->dist) {
2665                                 clamp_surf= 1;
2666                                 sfac= data->dist / dist;
2667                         }
2668                         /* if soft-distance is enabled, start fading once owner is dist-soft from the target */
2669                         else if (data->flag & LIMITDIST_USESOFT) {
2670                                 // FIXME: there's a problem with "jumping" when this kicks in
2671                                 if (dist >= (data->dist - data->soft)) {
2672                                         sfac = (float)( data->soft*(1.0f - expf(-(dist - data->dist)/data->soft)) + data->dist );
2673                                         sfac /= dist;
2674                                         
2675                                         clamp_surf= 1;
2676                                 }
2677                         }
2678                 }
2679                 else {
2680                         if (IS_EQF(dist, data->dist)==0) {
2681                                 clamp_surf= 1;
2682                                 sfac= data->dist / dist;
2683                         }
2684                 }
2685                 
2686                 /* clamp to 'surface' (i.e. move owner so that dist == data->dist) */
2687                 if (clamp_surf) {
2688                         /* simply interpolate along line formed by target -> owner */
2689                         interp_v3_v3v3(dvec, ct->matrix[3], cob->matrix[3], sfac);
2690                         
2691                         /* copy new vector onto owner */
2692                         copy_v3_v3(cob->matrix[3], dvec);
2693                 }
2694         }
2695 }
2696
2697 static bConstraintTypeInfo CTI_DISTLIMIT = {
2698         CONSTRAINT_TYPE_DISTLIMIT, /* type */
2699         sizeof(bDistLimitConstraint), /* size */
2700         "Limit Distance", /* name */
2701         "bDistLimitConstraint", /* struct name */
2702         NULL, /* free data */
2703         NULL, /* relink data */
2704         distlimit_id_looper, /* id looper */
2705         NULL, /* copy data */
2706         distlimit_new_data, /* new data */
2707         distlimit_get_tars, /* get constraint targets */
2708         distlimit_flush_tars, /* flush constraint targets */
2709         default_get_tarmat, /* get a target matrix */
2710         distlimit_evaluate /* evaluate */
2711 };
2712
2713 /* ---------- Stretch To ------------ */
2714
2715 static void stretchto_new_data (void *cdata)
2716 {
2717         bStretchToConstraint *data= (bStretchToConstraint *)cdata;
2718         
2719         data->volmode = 0;
2720         data->plane = 0;
2721         data->orglength = 0.0; 
2722         data->bulge = 1.0;
2723 }
2724
2725 static void stretchto_id_looper (bConstraint *con, ConstraintIDFunc func, void *userdata)
2726 {
2727         bStretchToConstraint *data= con->data;
2728         
2729         /* target only */
2730         func(con, (ID**)&data->tar, userdata);
2731 }
2732
2733 static int stretchto_get_tars (bConstraint *con, ListBase *list)
2734 {
2735         if (con && list) {
2736                 bStretchToConstraint *data= con->data;
2737                 bConstraintTarget *ct;
2738                 
2739                 /* standard target-getting macro for single-target constraints */
2740                 SINGLETARGET_GET_TARS(con, data->tar, data->subtarget, ct, list)
2741                 
2742                 return 1;
2743         }
2744         
2745         return 0;
2746 }
2747
2748 static void stretchto_flush_tars (bConstraint *con, ListBase *list, short nocopy)
2749 {
2750         if (con && list) {
2751                 bStretchToConstraint *data= con->data;
2752                 bConstraintTarget *ct= list->first;
2753                 
2754                 /* the following macro is used for all standard single-target constraints */
2755                 SINGLETARGET_FLUSH_TARS(con, data->tar, data->subtarget, ct, list, nocopy)
2756         }
2757 }
2758
2759 static void stretchto_evaluate (bConstraint *con, bConstraintOb *cob, ListBase *targets)
2760 {
2761         bStretchToConstraint *data= con->data;
2762         bConstraintTarget *ct= targets->first;
2763         
2764         /* only evaluate if there is a target */
2765         if (VALID_CONS_TARGET(ct)) {
2766                 float size[3], scale[3], vec[3], xx[3], zz[3], orth[3];
2767                 float totmat[3][3];
2768                 float tmat[4][4];
2769                 float dist;
2770                 
2771                 /* store scaling before destroying obmat */
2772                 mat4_to_size(size, cob->matrix);
2773                 
2774                 /* store X orientation before destroying obmat */
2775                 normalize_v3_v3(xx, cob->matrix[0]);
2776                 
2777                 /* store Z orientation before destroying obmat */
2778                 normalize_v3_v3(zz, cob->matrix[2]);
2779                 
2780                 sub_v3_v3v3(vec, cob->matrix[3], ct->matrix[3]);
2781                 vec[0] /= size[0];
2782                 vec[1] /= size[1];
2783                 vec[2] /= size[2];
2784                 
2785                 dist = normalize_v3(vec);
2786                 //dist = len_v3v3( ob->obmat[3], targetmat[3]);
2787                 
2788                 /* data->orglength==0 occurs on first run, and after 'R' button is clicked */
2789                 if (data->orglength == 0)  
2790                         data->orglength = dist;
2791                 if (data->bulge == 0) 
2792                         data->bulge = 1.0;
2793                 
2794                 scale[1] = dist/data->orglength;
2795                 switch (data->volmode) {
2796                 /* volume preserving scaling */
2797                 case VOLUME_XZ :
2798                         scale[0] = 1.0f - (float)sqrt(data->bulge) + (float)sqrt(data->bulge*(data->orglength/dist));
2799                         scale[2] = scale[0];
2800                         break;
2801                 case VOLUME_X:
2802                         scale[0] = 1.0f + data->bulge * (data->orglength /dist - 1);
2803                         scale[2] = 1.0;
2804                         break;
2805                 case VOLUME_Z:
2806                         scale[0] = 1.0;
2807                         scale[2] = 1.0f + data->bulge * (data->orglength /dist - 1);
2808                         break;
2809                         /* don't care for volume */
2810                 case NO_VOLUME:
2811                         scale[0] = 1.0;
2812                         scale[2] = 1.0;
2813                         break;
2814                 default: /* should not happen, but in case*/
2815                         return;    
2816                 } /* switch (data->volmode) */
2817
2818                 /* Clear the object's rotation and scale */
2819                 cob->matrix[0][0]=size[0]*scale[0];
2820                 cob->matrix[0][1]=0;
2821                 cob->matrix[0][2]=0;
2822                 cob->matrix[1][0]=0;
2823                 cob->matrix[1][1]=size[1]*scale[1];
2824                 cob->matrix[1][2]=0;
2825                 cob->matrix[2][0]=0;
2826                 cob->matrix[2][1]=0;
2827                 cob->matrix[2][2]=size[2]*scale[2];
2828                 
2829                 sub_v3_v3v3(vec, cob->matrix[3], ct->matrix[3]);
2830                 normalize_v3(vec);
2831                 
2832                 /* new Y aligns  object target connection*/
2833                 negate_v3_v3(totmat[1], vec);
2834                 switch (data->plane) {
2835                 case PLANE_X:
2836                         /* build new Z vector */
2837                         /* othogonal to "new Y" "old X! plane */
2838                         cross_v3_v3v3(orth, vec, xx);
2839                         normalize_v3(orth);
2840                         
2841                         /* new Z*/
2842                         copy_v3_v3(totmat[2], orth);
2843                         
2844                         /* we decided to keep X plane*/
2845                         cross_v3_v3v3(xx, orth, vec);
2846                         normalize_v3_v3(totmat[0], xx);
2847                         break;
2848                 case PLANE_Z:
2849                         /* build new X vector */
2850                         /* othogonal to "new Y" "old Z! plane */
2851                         cross_v3_v3v3(orth, vec, zz);
2852                         normalize_v3(orth);
2853                         
2854                         /* new X */
2855                         negate_v3_v3(totmat[0], orth);
2856                         
2857                         /* we decided to keep Z */
2858                         cross_v3_v3v3(zz, orth, vec);
2859                         normalize_v3_v3(totmat[2], zz);
2860                         break;
2861                 } /* switch (data->plane) */
2862                 
2863                 copy_m4_m4(tmat, cob->matrix);
2864                 mul_m4_m3m4(cob->matrix, totmat, tmat);
2865         }
2866 }
2867
2868 static bConstraintTypeInfo CTI_STRETCHTO = {
2869         CONSTRAINT_TYPE_STRETCHTO, /* type */
2870         sizeof(bStretchToConstraint), /* size */
2871         "Stretch To", /* name */
2872         "bStretchToConstraint", /* struct name */
2873         NULL, /* free data */
2874         NULL, /* relink data */
2875         stretchto_id_looper, /* id looper */
2876         NULL, /* copy data */
2877         stretchto_new_data, /* new data */
2878         stretchto_get_tars, /* get constraint targets */
2879         stretchto_flush_tars, /* flush constraint targets */
2880         default_get_tarmat, /* get target matrix */
2881         stretchto_evaluate /* evaluate */
2882 };
2883
2884 /* ---------- Floor ------------ */
2885
2886 static void minmax_new_data (void *cdata)
2887 {
2888         bMinMaxConstraint *data= (bMinMaxConstraint *)cdata;
2889         
2890         data->minmaxflag = TRACK_Z;
2891         data->offset = 0.0f;
2892         data->cache[0] = data->cache[1] = data->cache[2] = 0.0f;
2893         data->flag = 0;
2894 }
2895
2896 static void minmax_id_looper (bConstraint *con, ConstraintIDFunc func, void *userdata)
2897 {
2898         bMinMaxConstraint *data= con->data;
2899         
2900         /* target only */
2901         func(con, (ID**)&data->tar, userdata);
2902 }
2903
2904 static int minmax_get_tars (bConstraint *con, ListBase *list)
2905 {
2906         if (con && list) {
2907                 bMinMaxConstraint *data= con->data;
2908                 bConstraintTarget *ct;
2909                 
2910                 /* standard target-getting macro for single-target constraints */
2911                 SINGLETARGET_GET_TARS(con, data->tar, data->subtarget, ct, list)
2912                 
2913                 return 1;
2914         }
2915         
2916         return 0;
2917 }
2918
2919 static void minmax_flush_tars (bConstraint *con, ListBase *list, short nocopy)
2920 {
2921         if (con && list) {
2922                 bMinMaxConstraint *data= con->data;
2923                 bConstraintTarget *ct= list->first;
2924                 
2925                 /* the following macro is used for all standard single-target constraints */
2926                 SINGLETARGET_FLUSH_TARS(con, data->tar, data->subtarget, ct, list, nocopy)
2927         }
2928 }
2929
2930 static void minmax_evaluate (bConstraint *con, bConstraintOb *cob, ListBase *targets)
2931 {
2932         bMinMaxConstraint *data= con->data;
2933         bConstraintTarget *ct= targets->first;
2934         
2935         /* only evaluate if there is a target */
2936         if (VALID_CONS_TARGET(ct)) {
2937                 float obmat[4][4], imat[4][4], tarmat[4][4], tmat[4][4];
2938                 float val1, val2;
2939                 int index;
2940                 
2941                 copy_m4_m4(obmat, cob->matrix);
2942                 copy_m4_m4(tarmat, ct->matrix);