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