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