Merge with trunk revision 37149.
[blender-staging.git] / source / blender / blenkernel / intern / constraint.c
1 /*
2  * $Id$
3  *
4  * ***** BEGIN GPL LICENSE BLOCK *****
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License
8  * as published by the Free Software Foundation; either version 2
9  * of the License, or (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software Foundation,
18  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19  *
20  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
21  * All rights reserved.
22  *
23  * The Original Code is: all of this file.
24  *
25  * Contributor(s): 2007, Joshua Leung, major recode
26  *
27  * ***** END GPL LICENSE BLOCK *****
28  */
29
30 /** \file blender/blenkernel/intern/constraint.c
31  *  \ingroup bke
32  */
33
34
35 #include <stdio.h> 
36 #include <stddef.h>
37 #include <string.h>
38 #include <math.h>
39 #include <float.h>
40
41 #include "MEM_guardedalloc.h"
42
43 #include "BLI_blenlib.h"
44 #include "BLI_listbase.h"
45 #include "BLI_math.h"
46 #include "BLI_editVert.h"
47 #include "BLI_utildefines.h"
48
49 #include "DNA_armature_types.h"
50 #include "DNA_constraint_types.h"
51 #include "DNA_modifier_types.h"
52 #include "DNA_object_types.h"
53 #include "DNA_action_types.h"
54 #include "DNA_curve_types.h"
55 #include "DNA_mesh_types.h"
56 #include "DNA_meshdata_types.h"
57 #include "DNA_lattice_types.h"
58 #include "DNA_scene_types.h"
59 #include "DNA_text_types.h"
60
61
62 #include "BKE_action.h"
63 #include "BKE_anim.h" /* for the curve calculation part */
64 #include "BKE_armature.h"
65 #include "BKE_blender.h"
66 #include "BKE_constraint.h"
67 #include "BKE_displist.h"
68 #include "BKE_deform.h"
69 #include "BKE_DerivedMesh.h"    /* for geometry targets */
70 #include "BKE_cdderivedmesh.h" /* for geometry targets */
71 #include "BKE_object.h"
72 #include "BKE_ipo.h"
73 #include "BKE_global.h"
74 #include "BKE_library.h"
75 #include "BKE_idprop.h"
76 #include "BKE_shrinkwrap.h"
77 #include "BKE_mesh.h"
78
79 #ifdef WITH_PYTHON
80 #include "BPY_extern.h"
81 #endif
82
83 #ifndef M_PI
84 #define M_PI            3.14159265358979323846
85 #endif
86
87
88
89 /* ************************ Constraints - General Utilities *************************** */
90 /* These functions here don't act on any specific constraints, and are therefore should/will
91  * not require any of the special function-pointers afforded by the relevant constraint 
92  * type-info structs.
93  */
94
95 /* -------------- Naming -------------- */
96
97 /* Find the first available, non-duplicate name for a given constraint */
98 void unique_constraint_name (bConstraint *con, ListBase *list)
99 {
100         BLI_uniquename(list, con, "Const", '.', offsetof(bConstraint, name), sizeof(con->name));
101 }
102
103 /* ----------------- Evaluation Loop Preparation --------------- */
104
105 /* package an object/bone for use in constraint evaluation */
106 /* This function MEM_calloc's a bConstraintOb struct, that will need to be freed after evaluation */
107 bConstraintOb *constraints_make_evalob (Scene *scene, Object *ob, void *subdata, short datatype)
108 {
109         bConstraintOb *cob;
110         
111         /* create regardless of whether we have any data! */
112         cob= MEM_callocN(sizeof(bConstraintOb), "bConstraintOb");
113         
114         /* for system time, part of deglobalization, code nicer later with local time (ton) */
115         cob->scene= scene;
116         
117         /* based on type of available data */
118         switch (datatype) {
119                 case CONSTRAINT_OBTYPE_OBJECT:
120                 {
121                         /* disregard subdata... calloc should set other values right */
122                         if (ob) {
123                                 cob->ob = ob;
124                                 cob->type = datatype;
125                                 cob->rotOrder = EULER_ORDER_DEFAULT; // TODO: when objects have rotation order too, use that
126                                 copy_m4_m4(cob->matrix, ob->obmat);
127                         }
128                         else
129                                 unit_m4(cob->matrix);
130                         
131                         copy_m4_m4(cob->startmat, cob->matrix);
132                 }
133                         break;
134                 case CONSTRAINT_OBTYPE_BONE:
135                 {
136                         /* only set if we have valid bone, otherwise default */
137                         if (ob && subdata) {
138                                 cob->ob = ob;
139                                 cob->pchan = (bPoseChannel *)subdata;
140                                 cob->type = datatype;
141                                 
142                                 if (cob->pchan->rotmode > 0) {
143                                         /* should be some type of Euler order */
144                                         cob->rotOrder= cob->pchan->rotmode; 
145                                 }
146                                 else {
147                                         /* Quats, so eulers should just use default order */
148                                         cob->rotOrder= EULER_ORDER_DEFAULT;
149                                 }
150                                 
151                                 /* matrix in world-space */
152                                 mul_m4_m4m4(cob->matrix, cob->pchan->pose_mat, ob->obmat);
153                         }
154                         else
155                                 unit_m4(cob->matrix);
156                                 
157                         copy_m4_m4(cob->startmat, cob->matrix);
158                 }
159                         break;
160                         
161                 default: /* other types not yet handled */
162                         unit_m4(cob->matrix);
163                         unit_m4(cob->startmat);
164                         break;
165         }
166         
167         return cob;
168 }
169
170 /* cleanup after constraint evaluation */
171 void constraints_clear_evalob (bConstraintOb *cob)
172 {
173         float delta[4][4], imat[4][4];
174         
175         /* prevent crashes */
176         if (cob == NULL) 
177                 return;
178         
179         /* calculate delta of constraints evaluation */
180         invert_m4_m4(imat, cob->startmat);
181         mul_m4_m4m4(delta, imat, cob->matrix);
182         
183         /* copy matrices back to source */
184         switch (cob->type) {
185                 case CONSTRAINT_OBTYPE_OBJECT:
186                 {
187                         /* cob->ob might not exist! */
188                         if (cob->ob) {
189                                 /* copy new ob-matrix back to owner */
190                                 copy_m4_m4(cob->ob->obmat, cob->matrix);
191                                 
192                                 /* copy inverse of delta back to owner */
193                                 invert_m4_m4(cob->ob->constinv, delta);
194                         }
195                 }
196                         break;
197                 case CONSTRAINT_OBTYPE_BONE:
198                 {
199                         /* cob->ob or cob->pchan might not exist */
200                         if (cob->ob && cob->pchan) {
201                                 /* copy new pose-matrix back to owner */
202                                 mul_m4_m4m4(cob->pchan->pose_mat, cob->matrix, cob->ob->imat);
203                                 
204                                 /* copy inverse of delta back to owner */
205                                 invert_m4_m4(cob->pchan->constinv, delta);
206                         }
207                 }
208                         break;
209         }
210         
211         /* free tempolary struct */
212         MEM_freeN(cob);
213 }
214
215 /* -------------- Space-Conversion API -------------- */
216
217 /* This function is responsible for the correct transformations/conversions 
218  * of a matrix from one space to another for constraint evaluation.
219  * For now, this is only implemented for Objects and PoseChannels.
220  */
221 void constraint_mat_convertspace (Object *ob, bPoseChannel *pchan, float mat[][4], short from, short to)
222 {
223         float tempmat[4][4];
224         float diff_mat[4][4];
225         float imat[4][4];
226         
227         /* prevent crashes in these unlikely events  */
228         if (ob==NULL || mat==NULL) return;
229         /* optimise trick - check if need to do anything */
230         if (from == to) return;
231         
232         /* are we dealing with pose-channels or objects */
233         if (pchan) {
234                 /* pose channels */
235                 switch (from) {
236                         case CONSTRAINT_SPACE_WORLD: /* ---------- FROM WORLDSPACE ---------- */
237                         {
238                                 /* world to pose */
239                                 invert_m4_m4(imat, ob->obmat);
240                                 copy_m4_m4(tempmat, mat);
241                                 mul_m4_m4m4(mat, tempmat, imat);
242                                 
243                                 /* use pose-space as stepping stone for other spaces... */
244                                 if (ELEM(to, CONSTRAINT_SPACE_LOCAL, CONSTRAINT_SPACE_PARLOCAL)) {
245                                         /* call self with slightly different values */
246                                         constraint_mat_convertspace(ob, pchan, mat, CONSTRAINT_SPACE_POSE, to);
247                                 }
248                         }
249                                 break;
250                         case CONSTRAINT_SPACE_POSE:     /* ---------- FROM POSESPACE ---------- */
251                         {
252                                 /* pose to world */
253                                 if (to == CONSTRAINT_SPACE_WORLD) {
254                                         copy_m4_m4(tempmat, mat);
255                                         mul_m4_m4m4(mat, tempmat, ob->obmat);
256                                 }
257                                 /* pose to local */
258                                 else if (to == CONSTRAINT_SPACE_LOCAL) {
259                                         if (pchan->bone) {
260                                                 if (pchan->parent) {
261                                                         float offs_bone[4][4];
262                                                                 
263                                                         /* construct offs_bone the same way it is done in armature.c */
264                                                         copy_m4_m3(offs_bone, pchan->bone->bone_mat);
265                                                         copy_v3_v3(offs_bone[3], pchan->bone->head);
266                                                         offs_bone[3][1]+= pchan->bone->parent->length;
267                                                         
268                                                         if (pchan->bone->flag & BONE_HINGE) {
269                                                                 /* pose_mat = par_pose-space_location * chan_mat */
270                                                                 float tmat[4][4];
271                                                                 
272                                                                 /* the rotation of the parent restposition */
273                                                                 copy_m4_m4(tmat, pchan->bone->parent->arm_mat);
274                                                                 
275                                                                 /* the location of actual parent transform */
276                                                                 copy_v3_v3(tmat[3], offs_bone[3]);
277                                                                 offs_bone[3][0]= offs_bone[3][1]= offs_bone[3][2]= 0.0f;
278                                                                 mul_m4_v3(pchan->parent->pose_mat, tmat[3]);
279                                                                 
280                                                                 mul_m4_m4m4(diff_mat, offs_bone, tmat);
281                                                                 invert_m4_m4(imat, diff_mat);
282                                                         }
283                                                         else {
284                                                                 /* pose_mat = par_pose_mat * bone_mat * chan_mat */
285                                                                 mul_m4_m4m4(diff_mat, offs_bone, pchan->parent->pose_mat);
286                                                                 invert_m4_m4(imat, diff_mat);
287                                                         }
288                                                 }
289                                                 else {
290                                                         /* pose_mat = chan_mat * arm_mat */
291                                                         invert_m4_m4(imat, pchan->bone->arm_mat);
292                                                 }
293                                                 
294                                                 copy_m4_m4(tempmat, mat);
295                                                 mul_m4_m4m4(mat, tempmat, imat);
296                                         }
297                                 }
298                                 /* pose to local with parent */
299                                 else if (to == CONSTRAINT_SPACE_PARLOCAL) {
300                                         if (pchan->bone) {
301                                                 invert_m4_m4(imat, pchan->bone->arm_mat);
302                                                 copy_m4_m4(tempmat, mat);
303                                                 mul_m4_m4m4(mat, tempmat, imat);
304                                         }
305                                 }
306                         }
307                                 break;
308                         case CONSTRAINT_SPACE_LOCAL: /* ------------ FROM LOCALSPACE --------- */
309                         {
310                                 /* local to pose - do inverse procedure that was done for pose to local */
311                                 if (pchan->bone) {
312                                         /* we need the posespace_matrix = local_matrix + (parent_posespace_matrix + restpos) */                                         
313                                         if (pchan->parent) {
314                                                 float offs_bone[4][4];
315                                                 
316                                                 /* construct offs_bone the same way it is done in armature.c */
317                                                 copy_m4_m3(offs_bone, pchan->bone->bone_mat);
318                                                 copy_v3_v3(offs_bone[3], pchan->bone->head);
319                                                 offs_bone[3][1]+= pchan->bone->parent->length;
320                                                 
321                                                 if (pchan->bone->flag & BONE_HINGE) {
322                                                         /* pose_mat = par_pose-space_location * chan_mat */
323                                                         float tmat[4][4];
324                                                         
325                                                         /* the rotation of the parent restposition */
326                                                         copy_m4_m4(tmat, pchan->bone->parent->arm_mat);
327                                                         
328                                                         /* the location of actual parent transform */
329                                                         copy_v3_v3(tmat[3], offs_bone[3]);
330                                                         zero_v3(offs_bone[3]);
331                                                         mul_m4_v3(pchan->parent->pose_mat, tmat[3]);
332                                                         
333                                                         mul_m4_m4m4(diff_mat, offs_bone, tmat);
334                                                         copy_m4_m4(tempmat, mat);
335                                                         mul_m4_m4m4(mat, tempmat, diff_mat);
336                                                 }
337                                                 else {
338                                                         /* pose_mat = par_pose_mat * bone_mat * chan_mat */
339                                                         mul_m4_m4m4(diff_mat, offs_bone, pchan->parent->pose_mat);
340                                                         copy_m4_m4(tempmat, mat);
341                                                         mul_m4_m4m4(mat, tempmat, diff_mat);
342                                                 }
343                                         }
344                                         else {
345                                                 copy_m4_m4(diff_mat, pchan->bone->arm_mat);
346                                                 
347                                                 copy_m4_m4(tempmat, mat);
348                                                 mul_m4_m4m4(mat, tempmat, diff_mat);
349                                         }
350                                 }
351                                 
352                                 /* use pose-space as stepping stone for other spaces */
353                                 if (ELEM(to, CONSTRAINT_SPACE_WORLD, CONSTRAINT_SPACE_PARLOCAL)) {
354                                         /* call self with slightly different values */
355                                         constraint_mat_convertspace(ob, pchan, mat, CONSTRAINT_SPACE_POSE, to);
356                                 }                               
357                         }
358                                 break;
359                         case CONSTRAINT_SPACE_PARLOCAL: /* -------------- FROM LOCAL WITH PARENT ---------- */
360                         {
361                                 /* local + parent to pose */
362                                 if (pchan->bone) {                                      
363                                         copy_m4_m4(diff_mat, pchan->bone->arm_mat);
364                                         copy_m4_m4(tempmat, mat);
365                                         mul_m4_m4m4(mat, diff_mat, tempmat);
366                                 }
367                                 
368                                 /* use pose-space as stepping stone for other spaces */
369                                 if (ELEM(to, CONSTRAINT_SPACE_WORLD, CONSTRAINT_SPACE_LOCAL)) {
370                                         /* call self with slightly different values */
371                                         constraint_mat_convertspace(ob, pchan, mat, CONSTRAINT_SPACE_POSE, to);
372                                 }
373                         }
374                                 break;
375                 }
376         }
377         else {
378                 /* objects */
379                 if (from==CONSTRAINT_SPACE_WORLD && to==CONSTRAINT_SPACE_LOCAL) {
380                         /* check if object has a parent */
381                         if (ob->parent) {
382                                 /* 'subtract' parent's effects from owner */
383                                 mul_m4_m4m4(diff_mat, ob->parentinv, ob->parent->obmat);
384                                 invert_m4_m4(imat, diff_mat);
385                                 copy_m4_m4(tempmat, mat);
386                                 mul_m4_m4m4(mat, tempmat, imat);
387                         }
388                         else {
389                                 /* Local space in this case will have to be defined as local to the owner's 
390                                  * transform-property-rotated axes. So subtract this rotation component.
391                                  */
392                                 object_to_mat4(ob, diff_mat);
393                                 normalize_m4(diff_mat);
394                                 zero_v3(diff_mat[3]);
395                                 
396                                 invert_m4_m4(imat, diff_mat);
397                                 copy_m4_m4(tempmat, mat);
398                                 mul_m4_m4m4(mat, tempmat, imat);
399                         }
400                 }
401                 else if (from==CONSTRAINT_SPACE_LOCAL && to==CONSTRAINT_SPACE_WORLD) {
402                         /* check that object has a parent - otherwise this won't work */
403                         if (ob->parent) {
404                                 /* 'add' parent's effect back to owner */
405                                 copy_m4_m4(tempmat, mat);
406                                 mul_m4_m4m4(diff_mat, ob->parentinv, ob->parent->obmat);
407                                 mul_m4_m4m4(mat, tempmat, diff_mat);
408                         }
409                         else {
410                                 /* Local space in this case will have to be defined as local to the owner's 
411                                  * transform-property-rotated axes. So add back this rotation component.
412                                  */
413                                 object_to_mat4(ob, diff_mat);
414                                 normalize_m4(diff_mat);
415                                 zero_v3(diff_mat[3]);
416                                 
417                                 copy_m4_m4(tempmat, mat);
418                                 mul_m4_m4m4(mat, tempmat, diff_mat);
419                         }
420                 }
421         }
422 }
423
424 /* ------------ General Target Matrix Tools ---------- */
425
426 /* function that sets the given matrix based on given vertex group in mesh */
427 static void contarget_get_mesh_mat (Scene *scene, Object *ob, const char *substring, float mat[][4])
428 {
429         DerivedMesh *dm = NULL;
430         Mesh *me= ob->data;
431         EditMesh *em = BKE_mesh_get_editmesh(me);
432         float vec[3] = {0.0f, 0.0f, 0.0f};
433         float normal[3] = {0.0f, 0.0f, 0.0f}, plane[3];
434         float imat[3][3], tmat[3][3];
435         int dgroup;
436         short freeDM = 0;
437         
438         /* initialize target matrix using target matrix */
439         copy_m4_m4(mat, ob->obmat);
440         
441         /* get index of vertex group */
442         dgroup = defgroup_name_index(ob, substring);
443         if (dgroup < 0) return;
444         
445         /* get DerivedMesh */
446         if (em) {
447                 /* target is in editmode, so get a special derived mesh */
448                 dm = CDDM_from_editmesh(em, ob->data);
449                 freeDM= 1;
450         }
451         else {
452                 /* when not in EditMode, use the 'final' derived mesh 
453                  *      - check if the custom data masks for derivedFinal mean that we can just use that
454                  *        (this is more effficient + sufficient for most cases)
455                  */
456                 if (!(ob->lastDataMask & CD_MASK_MDEFORMVERT)) {
457                         dm = mesh_get_derived_final(scene, ob, CD_MASK_MDEFORMVERT);
458                         freeDM= 1;
459                 }
460                 else 
461                         dm = (DerivedMesh *)ob->derivedFinal;
462         }
463         
464         /* only continue if there's a valid DerivedMesh */
465         if (dm) {
466                 MDeformVert *dvert = dm->getVertDataArray(dm, CD_MDEFORMVERT);
467                 int numVerts = dm->getNumVerts(dm);
468                 int i, j, count = 0;
469                 float co[3], nor[3];
470                 
471                 /* check that dvert is a valid pointers (just in case) */
472                 if (dvert) {
473                         /* get the average of all verts with that are in the vertex-group */
474                         for (i = 0; i < numVerts; i++) {        
475                                 for (j = 0; j < dvert[i].totweight; j++) {
476                                         /* does this vertex belong to nominated vertex group? */
477                                         if (dvert[i].dw[j].def_nr == dgroup) {
478                                                 dm->getVertCo(dm, i, co);
479                                                 dm->getVertNo(dm, i, nor);
480                                                 add_v3_v3(vec, co);
481                                                 add_v3_v3(normal, nor);
482                                                 count++;
483                                                 break;
484                                         }
485                                         
486                                 }
487                         }
488                         
489                         
490                         /* calculate averages of normal and coordinates */
491                         if (count > 0) {
492                                 mul_v3_fl(vec, 1.0f / count);
493                                 mul_v3_fl(normal, 1.0f / count);
494                         }
495                         
496                         
497                         /* derive the rotation from the average normal: 
498                          *              - code taken from transform_manipulator.c, 
499                          *                      calc_manipulator_stats, V3D_MANIP_NORMAL case
500                          */
501                         /*      we need the transpose of the inverse for a normal... */
502                         copy_m3_m4(imat, ob->obmat);
503                         
504                         invert_m3_m3(tmat, imat);
505                         transpose_m3(tmat);
506                         mul_m3_v3(tmat, normal);
507                         
508                         normalize_v3(normal);
509                         copy_v3_v3(plane, tmat[1]);
510                         
511                         copy_v3_v3(tmat[2], normal);
512                         cross_v3_v3v3(tmat[0], normal, plane);
513                         cross_v3_v3v3(tmat[1], tmat[2], tmat[0]);
514                         
515                         copy_m4_m3(mat, tmat);
516                         normalize_m4(mat);
517                         
518                         
519                         /* apply the average coordinate as the new location */
520                         mul_v3_m4v3(mat[3], ob->obmat, vec);
521                 }
522         }
523         
524         /* free temporary DerivedMesh created (in EditMode case) */
525         if (dm && freeDM)
526                 dm->release(dm);
527         if (em)
528                 BKE_mesh_end_editmesh(me, em);
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 (Scene *scene, 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(scene, 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 *cob, bConstraintTarget *ct, float UNUSED(ctime))
688 {
689         if (VALID_CONS_TARGET(ct))
690                 constraint_target_to_mat4(cob->scene, 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 (ELEM(ct->tar->type, OB_MESH, OB_LATTICE) && (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 compatability 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(cob->scene, 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                                 if (cob->scene)
1270                                         curvetime= bsystem_time(cob->scene, ct->tar, cu->ctime, 0.0) - data->offset;
1271                                 else    
1272                                         curvetime= cu->ctime - data->offset;
1273                                 
1274                                 /* ctime is now a proper var setting of Curve which gets set by Animato like any other var that's animated,
1275                                  * but this will only work if it actually is animated... 
1276                                  *
1277                                  * we divide the curvetime calculated in the previous step by the length of the path, to get a time
1278                                  * factor, which then gets clamped to lie within 0.0 - 1.0 range
1279                                  */
1280                                 curvetime /= cu->pathlen;
1281                                 CLAMP(curvetime, 0.0f, 1.0f);
1282                         }
1283                         else {
1284                                 /* fixed position along curve */
1285                                 curvetime= data->offset_fac;
1286                         }
1287                         
1288                         if ( where_on_path(ct->tar, curvetime, vec, dir, (data->followflag & FOLLOWPATH_FOLLOW) ? quat : NULL, &radius, NULL) ) { /* quat_pt is quat or NULL*/
1289                                 if (data->followflag & FOLLOWPATH_FOLLOW) {
1290 #if 0
1291                                         float x1, q[4];
1292                                         vec_to_quat(quat, dir, (short)data->trackflag, (short)data->upflag);
1293                                         
1294                                         normalize_v3(dir);
1295                                         q[0]= (float)cos(0.5*vec[3]);
1296                                         x1= (float)sin(0.5*vec[3]);
1297                                         q[1]= -x1*dir[0];
1298                                         q[2]= -x1*dir[1];
1299                                         q[3]= -x1*dir[2];
1300                                         mul_qt_qtqt(quat, q, quat);
1301 #else
1302                                         quat_apply_track(quat, data->trackflag, data->upflag);
1303 #endif
1304
1305                                         quat_to_mat4(totmat, quat);
1306                                 }
1307
1308                                 if (data->followflag & FOLLOWPATH_RADIUS) {
1309                                         float tmat[4][4], rmat[4][4];
1310                                         scale_m4_fl(tmat, radius);
1311                                         mul_m4_m4m4(rmat, totmat, tmat);
1312                                         copy_m4_m4(totmat, rmat);
1313                                 }
1314                                 
1315                                 copy_v3_v3(totmat[3], vec);
1316                                 
1317                                 mul_serie_m4(ct->matrix, ct->tar->obmat, totmat, NULL, NULL, NULL, NULL, NULL, NULL);
1318                         }
1319                 }
1320         }
1321         else if (ct)
1322                 unit_m4(ct->matrix);
1323 }
1324
1325 static void followpath_evaluate (bConstraint *con, bConstraintOb *cob, ListBase *targets)
1326 {
1327         bConstraintTarget *ct= targets->first;
1328         
1329         /* only evaluate if there is a target */
1330         if (VALID_CONS_TARGET(ct)) {
1331                 float obmat[4][4];
1332                 float size[3];
1333                 bFollowPathConstraint *data= con->data;
1334                 
1335                 /* get Object transform (loc/rot/size) to determine transformation from path */
1336                 // TODO: this used to be local at one point, but is probably more useful as-is
1337                 copy_m4_m4(obmat, cob->matrix);
1338                 
1339                 /* get scaling of object before applying constraint */
1340                 mat4_to_size(size, cob->matrix);
1341                 
1342                 /* apply targetmat - containing location on path, and rotation */
1343                 mul_serie_m4(cob->matrix, ct->matrix, obmat, NULL, NULL, NULL, NULL, NULL, NULL);
1344                 
1345                 /* un-apply scaling caused by path */
1346                 if ((data->followflag & FOLLOWPATH_RADIUS)==0) { /* XXX - assume that scale correction means that radius will have some scale error in it - Campbell */
1347                         float obsize[3];
1348                         
1349                         mat4_to_size( obsize,cob->matrix);
1350                         if (obsize[0])
1351                                 mul_v3_fl(cob->matrix[0], size[0] / obsize[0]);
1352                         if (obsize[1])
1353                                 mul_v3_fl(cob->matrix[1], size[1] / obsize[1]);
1354                         if (obsize[2])
1355                                 mul_v3_fl(cob->matrix[2], size[2] / obsize[2]);
1356                 }
1357         }
1358 }
1359
1360 static bConstraintTypeInfo CTI_FOLLOWPATH = {
1361         CONSTRAINT_TYPE_FOLLOWPATH, /* type */
1362         sizeof(bFollowPathConstraint), /* size */
1363         "Follow Path", /* name */
1364         "bFollowPathConstraint", /* struct name */
1365         NULL, /* free data */
1366         NULL, /* relink data */
1367         followpath_id_looper, /* id looper */
1368         NULL, /* copy data */
1369         followpath_new_data, /* new data */
1370         followpath_get_tars, /* get constraint targets */
1371         followpath_flush_tars, /* flush constraint targets */
1372         followpath_get_tarmat, /* get target matrix */
1373         followpath_evaluate /* evaluate */
1374 };
1375
1376 /* --------- Limit Location --------- */
1377
1378
1379 static void loclimit_evaluate (bConstraint *con, bConstraintOb *cob, ListBase *UNUSED(targets))
1380 {
1381         bLocLimitConstraint *data = con->data;
1382         
1383         if (data->flag & LIMIT_XMIN) {
1384                 if (cob->matrix[3][0] < data->xmin)
1385                         cob->matrix[3][0] = data->xmin;
1386         }
1387         if (data->flag & LIMIT_XMAX) {
1388                 if (cob->matrix[3][0] > data->xmax)
1389                         cob->matrix[3][0] = data->xmax;
1390         }
1391         if (data->flag & LIMIT_YMIN) {
1392                 if (cob->matrix[3][1] < data->ymin)
1393                         cob->matrix[3][1] = data->ymin;
1394         }
1395         if (data->flag & LIMIT_YMAX) {
1396                 if (cob->matrix[3][1] > data->ymax)
1397                         cob->matrix[3][1] = data->ymax;
1398         }
1399         if (data->flag & LIMIT_ZMIN) {
1400                 if (cob->matrix[3][2] < data->zmin) 
1401                         cob->matrix[3][2] = data->zmin;
1402         }
1403         if (data->flag & LIMIT_ZMAX) {
1404                 if (cob->matrix[3][2] > data->zmax)
1405                         cob->matrix[3][2] = data->zmax;
1406         }
1407 }
1408
1409 static bConstraintTypeInfo CTI_LOCLIMIT = {
1410         CONSTRAINT_TYPE_LOCLIMIT, /* type */
1411         sizeof(bLocLimitConstraint), /* size */
1412         "Limit Location", /* name */
1413         "bLocLimitConstraint", /* struct name */
1414         NULL, /* free data */
1415         NULL, /* relink data */
1416         NULL, /* id looper */
1417         NULL, /* copy data */
1418         NULL, /* new data */
1419         NULL, /* get constraint targets */
1420         NULL, /* flush constraint targets */
1421         NULL, /* get target matrix */
1422         loclimit_evaluate /* evaluate */
1423 };
1424
1425 /* -------- Limit Rotation --------- */
1426
1427 static void rotlimit_evaluate (bConstraint *con, bConstraintOb *cob, ListBase *UNUSED(targets))
1428 {
1429         bRotLimitConstraint *data = con->data;
1430         float loc[3];
1431         float eul[3];
1432         float size[3];
1433         
1434         copy_v3_v3(loc, cob->matrix[3]);
1435         mat4_to_size(size, cob->matrix);
1436
1437         mat4_to_eulO(eul, cob->rotOrder, cob->matrix);
1438
1439         /* constraint data uses radians internally */
1440         
1441         /* limiting of euler values... */
1442         if (data->flag & LIMIT_XROT) {
1443                 if (eul[0] < data->xmin) 
1444                         eul[0] = data->xmin;
1445                         
1446                 if (eul[0] > data->xmax)
1447                         eul[0] = data->xmax;
1448         }
1449         if (data->flag & LIMIT_YROT) {
1450                 if (eul[1] < data->ymin)
1451                         eul[1] = data->ymin;
1452                         
1453                 if (eul[1] > data->ymax)
1454                         eul[1] = data->ymax;
1455         }
1456         if (data->flag & LIMIT_ZROT) {
1457                 if (eul[2] < data->zmin)
1458                         eul[2] = data->zmin;
1459                         
1460                 if (eul[2] > data->zmax)
1461                         eul[2] = data->zmax;
1462         }
1463                 
1464         loc_eulO_size_to_mat4(cob->matrix, loc, eul, size, cob->rotOrder);
1465 }
1466
1467 static bConstraintTypeInfo CTI_ROTLIMIT = {
1468         CONSTRAINT_TYPE_ROTLIMIT, /* type */
1469         sizeof(bRotLimitConstraint), /* size */
1470         "Limit Rotation", /* name */
1471         "bRotLimitConstraint", /* struct name */
1472         NULL, /* free data */
1473         NULL, /* relink data */
1474         NULL, /* id looper */
1475         NULL, /* copy data */
1476         NULL, /* new data */
1477         NULL, /* get constraint targets */
1478         NULL, /* flush constraint targets */
1479         NULL, /* get target matrix */
1480         rotlimit_evaluate /* evaluate */
1481 };
1482
1483 /* --------- Limit Scaling --------- */
1484
1485
1486 static void sizelimit_evaluate (bConstraint *con, bConstraintOb *cob, ListBase *UNUSED(targets))
1487 {
1488         bSizeLimitConstraint *data = con->data;
1489         float obsize[3], size[3];
1490         
1491         mat4_to_size( size,cob->matrix);
1492         mat4_to_size( obsize,cob->matrix);
1493         
1494         if (data->flag & LIMIT_XMIN) {
1495                 if (size[0] < data->xmin) 
1496                         size[0] = data->xmin;   
1497         }
1498         if (data->flag & LIMIT_XMAX) {
1499                 if (size[0] > data->xmax) 
1500                         size[0] = data->xmax;
1501         }
1502         if (data->flag & LIMIT_YMIN) {
1503                 if (size[1] < data->ymin) 
1504                         size[1] = data->ymin;   
1505         }
1506         if (data->flag & LIMIT_YMAX) {
1507                 if (size[1] > data->ymax) 
1508                         size[1] = data->ymax;
1509         }
1510         if (data->flag & LIMIT_ZMIN) {
1511                 if (size[2] < data->zmin) 
1512                         size[2] = data->zmin;   
1513         }
1514         if (data->flag & LIMIT_ZMAX) {
1515                 if (size[2] > data->zmax) 
1516                         size[2] = data->zmax;
1517         }
1518         
1519         if (obsize[0]) 
1520                 mul_v3_fl(cob->matrix[0], size[0]/obsize[0]);
1521         if (obsize[1]) 
1522                 mul_v3_fl(cob->matrix[1], size[1]/obsize[1]);
1523         if (obsize[2]) 
1524                 mul_v3_fl(cob->matrix[2], size[2]/obsize[2]);
1525 }
1526
1527 static bConstraintTypeInfo CTI_SIZELIMIT = {
1528         CONSTRAINT_TYPE_SIZELIMIT, /* type */
1529         sizeof(bSizeLimitConstraint), /* size */
1530         "Limit Scaling", /* name */
1531         "bSizeLimitConstraint", /* struct name */
1532         NULL, /* free data */
1533         NULL, /* relink data */
1534         NULL, /* id looper */
1535         NULL, /* copy data */
1536         NULL, /* new data */
1537         NULL, /* get constraint targets */
1538         NULL, /* flush constraint targets */
1539         NULL, /* get target matrix */
1540         sizelimit_evaluate /* evaluate */
1541 };
1542
1543 /* ----------- Copy Location ------------- */
1544
1545 static void loclike_new_data (void *cdata)
1546 {
1547         bLocateLikeConstraint *data= (bLocateLikeConstraint *)cdata;
1548         
1549         data->flag = LOCLIKE_X|LOCLIKE_Y|LOCLIKE_Z;
1550 }
1551
1552 static void loclike_id_looper (bConstraint *con, ConstraintIDFunc func, void *userdata)
1553 {
1554         bLocateLikeConstraint *data= con->data;
1555         
1556         /* target only */
1557         func(con, (ID**)&data->tar, userdata);
1558 }
1559
1560 static int loclike_get_tars (bConstraint *con, ListBase *list)
1561 {
1562         if (con && list) {
1563                 bLocateLikeConstraint *data= con->data;
1564                 bConstraintTarget *ct;
1565                 
1566                 /* standard target-getting macro for single-target constraints */
1567                 SINGLETARGET_GET_TARS(con, data->tar, data->subtarget, ct, list)
1568                 
1569                 return 1;
1570         }
1571         
1572         return 0;
1573 }
1574
1575 static void loclike_flush_tars (bConstraint *con, ListBase *list, short nocopy)
1576 {
1577         if (con && list) {
1578                 bLocateLikeConstraint *data= con->data;
1579                 bConstraintTarget *ct= list->first;
1580                 
1581                 /* the following macro is used for all standard single-target constraints */
1582                 SINGLETARGET_FLUSH_TARS(con, data->tar, data->subtarget, ct, list, nocopy)
1583         }
1584 }
1585
1586 static void loclike_evaluate (bConstraint *con, bConstraintOb *cob, ListBase *targets)
1587 {
1588         bLocateLikeConstraint *data= con->data;
1589         bConstraintTarget *ct= targets->first;
1590         
1591         if (VALID_CONS_TARGET(ct)) {
1592                 float offset[3] = {0.0f, 0.0f, 0.0f};
1593                 
1594                 if (data->flag & LOCLIKE_OFFSET)
1595                         copy_v3_v3(offset, cob->matrix[3]);
1596                         
1597                 if (data->flag & LOCLIKE_X) {
1598                         cob->matrix[3][0] = ct->matrix[3][0];
1599                         
1600                         if (data->flag & LOCLIKE_X_INVERT) cob->matrix[3][0] *= -1;
1601                         cob->matrix[3][0] += offset[0];
1602                 }
1603                 if (data->flag & LOCLIKE_Y) {
1604                         cob->matrix[3][1] = ct->matrix[3][1];
1605                         
1606                         if (data->flag & LOCLIKE_Y_INVERT) cob->matrix[3][1] *= -1;
1607                         cob->matrix[3][1] += offset[1];
1608                 }
1609                 if (data->flag & LOCLIKE_Z) {
1610                         cob->matrix[3][2] = ct->matrix[3][2];
1611                         
1612                         if (data->flag & LOCLIKE_Z_INVERT) cob->matrix[3][2] *= -1;
1613                         cob->matrix[3][2] += offset[2];
1614                 }
1615         }
1616 }
1617
1618 static bConstraintTypeInfo CTI_LOCLIKE = {
1619         CONSTRAINT_TYPE_LOCLIKE, /* type */
1620         sizeof(bLocateLikeConstraint), /* size */
1621         "Copy Location", /* name */
1622         "bLocateLikeConstraint", /* struct name */
1623         NULL, /* free data */
1624         NULL, /* relink data */
1625         loclike_id_looper, /* id looper */
1626         NULL, /* copy data */
1627         loclike_new_data, /* new data */
1628         loclike_get_tars, /* get constraint targets */
1629         loclike_flush_tars, /* flush constraint targets */
1630         default_get_tarmat, /* get target matrix */
1631         loclike_evaluate /* evaluate */
1632 };
1633
1634 /* ----------- Copy Rotation ------------- */
1635
1636 static void rotlike_new_data (void *cdata)
1637 {
1638         bRotateLikeConstraint *data= (bRotateLikeConstraint *)cdata;
1639         
1640         data->flag = ROTLIKE_X|ROTLIKE_Y|ROTLIKE_Z;
1641 }
1642
1643 static void rotlike_id_looper (bConstraint *con, ConstraintIDFunc func, void *userdata)
1644 {
1645         bChildOfConstraint *data= con->data;
1646         
1647         /* target only */
1648         func(con, (ID**)&data->tar, userdata);
1649 }
1650
1651 static int rotlike_get_tars (bConstraint *con, ListBase *list)
1652 {
1653         if (con && list) {
1654                 bRotateLikeConstraint *data= con->data;
1655                 bConstraintTarget *ct;
1656                 
1657                 /* standard target-getting macro for single-target constraints */
1658                 SINGLETARGET_GET_TARS(con, data->tar, data->subtarget, ct, list)
1659                 
1660                 return 1;
1661         }
1662         
1663         return 0;
1664 }
1665
1666 static void rotlike_flush_tars (bConstraint *con, ListBase *list, short nocopy)
1667 {
1668         if (con && list) {
1669                 bRotateLikeConstraint *data= con->data;
1670                 bConstraintTarget *ct= list->first;
1671                 
1672                 /* the following macro is used for all standard single-target constraints */
1673                 SINGLETARGET_FLUSH_TARS(con, data->tar, data->subtarget, ct, list, nocopy)
1674         }
1675 }
1676
1677 static void rotlike_evaluate (bConstraint *con, bConstraintOb *cob, ListBase *targets)
1678 {
1679         bRotateLikeConstraint *data= con->data;
1680         bConstraintTarget *ct= targets->first;
1681         
1682         if (VALID_CONS_TARGET(ct)) {
1683                 float   loc[3];
1684                 float   eul[3], obeul[3];
1685                 float   size[3];
1686                 
1687                 copy_v3_v3(loc, cob->matrix[3]);
1688                 mat4_to_size(size, cob->matrix);
1689                 
1690                 /* to allow compatible rotations, must get both rotations in the order of the owner... */
1691                 mat4_to_eulO(obeul, cob->rotOrder, cob->matrix);
1692                 /* we must get compatible eulers from the beginning because some of them can be modified below (see bug #21875) */
1693                 mat4_to_compatible_eulO(eul, obeul, cob->rotOrder, ct->matrix);
1694                 
1695                 if ((data->flag & ROTLIKE_X)==0)
1696                         eul[0] = obeul[0];
1697                 else {
1698                         if (data->flag & ROTLIKE_OFFSET)
1699                                 rotate_eulO(eul, cob->rotOrder, 'X', obeul[0]);
1700                         
1701                         if (data->flag & ROTLIKE_X_INVERT)
1702                                 eul[0] *= -1;
1703                 }
1704                 
1705                 if ((data->flag & ROTLIKE_Y)==0)
1706                         eul[1] = obeul[1];
1707                 else {
1708                         if (data->flag & ROTLIKE_OFFSET)
1709                                 rotate_eulO(eul, cob->rotOrder, 'Y', obeul[1]);
1710                         
1711                         if (data->flag & ROTLIKE_Y_INVERT)
1712                                 eul[1] *= -1;
1713                 }
1714                 
1715                 if ((data->flag & ROTLIKE_Z)==0)
1716                         eul[2] = obeul[2];
1717                 else {
1718                         if (data->flag & ROTLIKE_OFFSET)
1719                                 rotate_eulO(eul, cob->rotOrder, 'Z', obeul[2]);
1720                         
1721                         if (data->flag & ROTLIKE_Z_INVERT)
1722                                 eul[2] *= -1;
1723                 }
1724                 
1725                 /* good to make eulers compatible again, since we don't know how much they were changed above */
1726                 compatible_eul(eul, obeul);
1727                 loc_eulO_size_to_mat4(cob->matrix, loc, eul, size, cob->rotOrder);
1728         }
1729 }
1730
1731 static bConstraintTypeInfo CTI_ROTLIKE = {
1732         CONSTRAINT_TYPE_ROTLIKE, /* type */
1733         sizeof(bRotateLikeConstraint), /* size */
1734         "Copy Rotation", /* name */
1735         "bRotateLikeConstraint", /* struct name */
1736         NULL, /* free data */
1737         NULL, /* relink data */
1738         rotlike_id_looper, /* id looper */
1739         NULL, /* copy data */
1740         rotlike_new_data, /* new data */
1741         rotlike_get_tars, /* get constraint targets */
1742         rotlike_flush_tars, /* flush constraint targets */
1743         default_get_tarmat, /* get target matrix */
1744         rotlike_evaluate /* evaluate */
1745 };
1746
1747 /* ---------- Copy Scaling ---------- */
1748
1749 static void sizelike_new_data (void *cdata)
1750 {
1751         bSizeLikeConstraint *data= (bSizeLikeConstraint *)cdata;
1752         
1753         data->flag = SIZELIKE_X|SIZELIKE_Y|SIZELIKE_Z;
1754 }
1755
1756 static void sizelike_id_looper (bConstraint *con, ConstraintIDFunc func, void *userdata)
1757 {
1758         bSizeLikeConstraint *data= con->data;
1759         
1760         /* target only */
1761         func(con, (ID**)&data->tar, userdata);
1762 }
1763
1764 static int sizelike_get_tars (bConstraint *con, ListBase *list)
1765 {
1766         if (con && list) {
1767                 bSizeLikeConstraint *data= con->data;
1768                 bConstraintTarget *ct;
1769                 
1770                 /* standard target-getting macro for single-target constraints */
1771                 SINGLETARGET_GET_TARS(con, data->tar, data->subtarget, ct, list)
1772                 
1773                 return 1;
1774         }
1775         
1776         return 0;
1777 }
1778
1779 static void sizelike_flush_tars (bConstraint *con, ListBase *list, short nocopy)
1780 {
1781         if (con && list) {
1782                 bSizeLikeConstraint *data= con->data;
1783                 bConstraintTarget *ct= list->first;
1784                 
1785                 /* the following macro is used for all standard single-target constraints */
1786                 SINGLETARGET_FLUSH_TARS(con, data->tar, data->subtarget, ct, list, nocopy)
1787         }
1788 }
1789
1790 static void sizelike_evaluate (bConstraint *con, bConstraintOb *cob, ListBase *targets)
1791 {
1792         bSizeLikeConstraint *data= con->data;
1793         bConstraintTarget *ct= targets->first;
1794         
1795         if (VALID_CONS_TARGET(ct)) {
1796                 float obsize[3], size[3];
1797                 
1798                 mat4_to_size(size, ct->matrix);
1799                 mat4_to_size(obsize, cob->matrix);
1800                 
1801                 if ((data->flag & SIZELIKE_X) && (obsize[0] != 0)) {
1802                         if (data->flag & SIZELIKE_OFFSET) {
1803                                 size[0] += (obsize[0] - 1.0f);
1804                                 mul_v3_fl(cob->matrix[0], size[0] / obsize[0]);
1805                         }
1806                         else
1807                                 mul_v3_fl(cob->matrix[0], size[0] / obsize[0]);
1808                 }
1809                 if ((data->flag & SIZELIKE_Y) && (obsize[1] != 0)) {
1810                         if (data->flag & SIZELIKE_OFFSET) {
1811                                 size[1] += (obsize[1] - 1.0f);
1812                                 mul_v3_fl(cob->matrix[1], size[1] / obsize[1]);
1813                         }
1814                         else
1815                                 mul_v3_fl(cob->matrix[1], size[1] / obsize[1]);
1816                 }
1817                 if ((data->flag & SIZELIKE_Z) && (obsize[2] != 0)) {
1818                         if (data->flag & SIZELIKE_OFFSET) {
1819                                 size[2] += (obsize[2] - 1.0f);
1820                                 mul_v3_fl(cob->matrix[2], size[2] / obsize[2]);
1821                         }
1822                         else
1823                                 mul_v3_fl(cob->matrix[2], size[2] / obsize[2]);
1824                 }
1825         }
1826 }
1827
1828 static bConstraintTypeInfo CTI_SIZELIKE = {
1829         CONSTRAINT_TYPE_SIZELIKE, /* type */
1830         sizeof(bSizeLikeConstraint), /* size */
1831         "Copy Scale", /* name */
1832         "bSizeLikeConstraint", /* struct name */
1833         NULL, /* free data */
1834         NULL, /* relink data */
1835         sizelike_id_looper, /* id looper */
1836         NULL, /* copy data */
1837         sizelike_new_data, /* new data */
1838         sizelike_get_tars, /* get constraint targets */
1839         sizelike_flush_tars, /* flush constraint targets */
1840         default_get_tarmat, /* get target matrix */
1841         sizelike_evaluate /* evaluate */
1842 };
1843
1844 /* ----------- Copy Transforms ------------- */
1845
1846 static void translike_id_looper (bConstraint *con, ConstraintIDFunc func, void *userdata)
1847 {
1848         bTransLikeConstraint *data= con->data;
1849         
1850         /* target only */
1851         func(con, (ID**)&data->tar, userdata);
1852 }
1853
1854 static int translike_get_tars (bConstraint *con, ListBase *list)
1855 {
1856         if (con && list) {
1857                 bTransLikeConstraint *data= con->data;
1858                 bConstraintTarget *ct;
1859                 
1860                 /* standard target-getting macro for single-target constraints */
1861                 SINGLETARGET_GET_TARS(con, data->tar, data->subtarget, ct, list)
1862                 
1863                 return 1;
1864         }
1865         
1866         return 0;
1867 }
1868
1869 static void translike_flush_tars (bConstraint *con, ListBase *list, short nocopy)
1870 {
1871         if (con && list) {
1872                 bTransLikeConstraint *data= con->data;
1873                 bConstraintTarget *ct= list->first;
1874                 
1875                 /* the following macro is used for all standard single-target constraints */
1876                 SINGLETARGET_FLUSH_TARS(con, data->tar, data->subtarget, ct, list, nocopy)
1877         }
1878 }
1879
1880 static void translike_evaluate (bConstraint *UNUSED(con), bConstraintOb *cob, ListBase *targets)
1881 {
1882         bConstraintTarget *ct= targets->first;
1883         
1884         if (VALID_CONS_TARGET(ct)) {
1885                 /* just copy the entire transform matrix of the target */
1886                 copy_m4_m4(cob->matrix, ct->matrix);
1887         }
1888 }
1889
1890 static bConstraintTypeInfo CTI_TRANSLIKE = {
1891         CONSTRAINT_TYPE_TRANSLIKE, /* type */
1892         sizeof(bTransLikeConstraint), /* size */
1893         "Copy Transforms", /* name */
1894         "bTransLikeConstraint", /* struct name */
1895         NULL, /* free data */
1896         NULL, /* relink data */
1897         translike_id_looper, /* id looper */
1898         NULL, /* copy data */
1899         NULL, /* new data */
1900         translike_get_tars, /* get constraint targets */
1901         translike_flush_tars, /* flush constraint targets */
1902         default_get_tarmat, /* get target matrix */
1903         translike_evaluate /* evaluate */
1904 };
1905
1906 /* ---------- Maintain Volume ---------- */
1907
1908 static void samevolume_new_data (void *cdata)
1909 {
1910         bSameVolumeConstraint *data= (bSameVolumeConstraint *)cdata;
1911
1912         data->flag = SAMEVOL_Y;
1913         data->volume = 1.0f;
1914 }
1915
1916 static void samevolume_evaluate (bConstraint *con, bConstraintOb *cob, ListBase *UNUSED(targets))
1917 {
1918         bSameVolumeConstraint *data= con->data;
1919
1920         float volume = data->volume;
1921         float fac = 1.0f;
1922         float obsize[3];
1923
1924         mat4_to_size(obsize, cob->matrix);
1925         
1926         /* calculate normalising scale factor for non-essential values */
1927         if (obsize[data->flag] != 0) 
1928                 fac = sqrtf(volume / obsize[data->flag]) / obsize[data->flag];
1929         
1930         /* apply scaling factor to the channels not being kept */
1931         switch (data->flag) {
1932                 case SAMEVOL_X:
1933                         mul_v3_fl(cob->matrix[1], fac);
1934                         mul_v3_fl(cob->matrix[2], fac);
1935                         break;
1936                 case SAMEVOL_Y:
1937                         mul_v3_fl(cob->matrix[0], fac);
1938                         mul_v3_fl(cob->matrix[2], fac);
1939                         break;
1940                 case SAMEVOL_Z:
1941                         mul_v3_fl(cob->matrix[0], fac);
1942                         mul_v3_fl(cob->matrix[1], fac);
1943                         break;
1944         }
1945 }
1946
1947 static bConstraintTypeInfo CTI_SAMEVOL = {
1948         CONSTRAINT_TYPE_SAMEVOL, /* type */
1949         sizeof(bSameVolumeConstraint), /* size */
1950         "Maintain Volume", /* name */
1951         "bSameVolumeConstraint", /* struct name */
1952         NULL, /* free data */
1953         NULL, /* relink data */
1954         NULL, /* id looper */
1955         NULL, /* copy data */
1956         samevolume_new_data, /* new data */
1957         NULL, /* get constraint targets */
1958         NULL, /* flush constraint targets */
1959         NULL, /* get target matrix */
1960         samevolume_evaluate /* evaluate */
1961 };
1962
1963 /* ----------- Python Constraint -------------- */
1964
1965 static void pycon_free (bConstraint *con)
1966 {
1967         bPythonConstraint *data= con->data;
1968         
1969         /* id-properties */
1970         IDP_FreeProperty(data->prop);
1971         MEM_freeN(data->prop);
1972         
1973         /* multiple targets */
1974         BLI_freelistN(&data->targets);
1975 }       
1976
1977 static void pycon_relink (bConstraint *con)
1978 {
1979         bPythonConstraint *data= con->data;
1980         
1981         ID_NEW(data->text);
1982 }
1983
1984 static void pycon_copy (bConstraint *con, bConstraint *srccon)
1985 {
1986         bPythonConstraint *pycon = (bPythonConstraint *)con->data;
1987         bPythonConstraint *opycon = (bPythonConstraint *)srccon->data;
1988         
1989         pycon->prop = IDP_CopyProperty(opycon->prop);
1990         BLI_duplicatelist(&pycon->targets, &opycon->targets);
1991 }
1992
1993 static void pycon_new_data (void *cdata)
1994 {
1995         bPythonConstraint *data= (bPythonConstraint *)cdata;
1996         
1997         /* everything should be set correctly by calloc, except for the prop->type constant.*/
1998         data->prop = MEM_callocN(sizeof(IDProperty), "PyConstraintProps");
1999         data->prop->type = IDP_GROUP;
2000 }
2001
2002 static int pycon_get_tars (bConstraint *con, ListBase *list)
2003 {
2004         if (con && list) {
2005                 bPythonConstraint *data= con->data;
2006                 
2007                 list->first = data->targets.first;
2008                 list->last = data->targets.last;
2009                 
2010                 return data->tarnum;
2011         }
2012         
2013         return 0;
2014 }
2015
2016 static void pycon_id_looper (bConstraint *con, ConstraintIDFunc func, void *userdata)
2017 {
2018         bPythonConstraint *data= con->data;
2019         bConstraintTarget *ct;
2020         
2021         /* targets */
2022         for (ct= data->targets.first; ct; ct= ct->next)
2023                 func(con, (ID**)&ct->tar, userdata);
2024                 
2025         /* script */
2026         func(con, (ID**)&data->text, userdata);
2027 }
2028
2029 /* Whether this approach is maintained remains to be seen (aligorith) */
2030 static void pycon_get_tarmat (bConstraint *con, bConstraintOb *cob, bConstraintTarget *ct, float UNUSED(ctime))
2031 {
2032 #ifdef WITH_PYTHON
2033         bPythonConstraint *data= con->data;
2034 #endif
2035
2036         if (VALID_CONS_TARGET(ct)) {
2037                 /* special exception for curves - depsgraph issues */
2038                 if (ct->tar->type == OB_CURVE) {
2039                         Curve *cu= ct->tar->data;
2040                         
2041                         /* this check is to make sure curve objects get updated on file load correctly.*/
2042                         if (cu->path==NULL || cu->path->data==NULL) /* only happens on reload file, but violates depsgraph still... fix! */
2043                                 makeDispListCurveTypes(cob->scene, ct->tar, 0);                         
2044                 }
2045                 
2046                 /* firstly calculate the matrix the normal way, then let the py-function override
2047                  * this matrix if it needs to do so
2048                  */
2049                 constraint_target_to_mat4(cob->scene, ct->tar, ct->subtarget, ct->matrix, CONSTRAINT_SPACE_WORLD, ct->space, con->headtail);
2050                 
2051                 /* only execute target calculation if allowed */
2052 #ifdef WITH_PYTHON
2053                 if (G.f & G_SCRIPT_AUTOEXEC)
2054                         BPY_pyconstraint_target(data, ct);
2055 #endif
2056         }
2057         else if (ct)
2058                 unit_m4(ct->matrix);
2059 }
2060
2061 static void pycon_evaluate (bConstraint *con, bConstraintOb *cob, ListBase *targets)
2062 {
2063 #ifndef WITH_PYTHON
2064         (void)con; (void)cob; (void)targets; /* unused */
2065         return;
2066 #else
2067         bPythonConstraint *data= con->data;
2068         
2069         /* only evaluate in python if we're allowed to do so */
2070         if ((G.f & G_SCRIPT_AUTOEXEC)==0)  return;
2071         
2072 /* currently removed, until I this can be re-implemented for multiple targets */
2073 #if 0
2074         /* Firstly, run the 'driver' function which has direct access to the objects involved 
2075          * Technically, this is potentially dangerous as users may abuse this and cause dependency-problems,
2076          * but it also allows certain 'clever' rigging hacks to work.
2077          */
2078         BPY_pyconstraint_driver(data, cob, targets);
2079 #endif
2080         
2081         /* Now, run the actual 'constraint' function, which should only access the matrices */
2082         BPY_pyconstraint_exec(data, cob, targets);
2083 #endif /* WITH_PYTHON */
2084 }
2085
2086 static bConstraintTypeInfo CTI_PYTHON = {
2087         CONSTRAINT_TYPE_PYTHON, /* type */
2088         sizeof(bPythonConstraint), /* size */
2089         "Script", /* name */
2090         "bPythonConstraint", /* struct name */
2091         pycon_free, /* free data */
2092         pycon_relink, /* relink data */
2093         pycon_id_looper, /* id looper */
2094         pycon_copy, /* copy data */
2095         pycon_new_data, /* new data */
2096         pycon_get_tars, /* get constraint targets */
2097         NULL, /* flush constraint targets */
2098         pycon_get_tarmat, /* get target matrix */
2099         pycon_evaluate /* evaluate */
2100 };
2101
2102 /* -------- Action Constraint ----------- */
2103
2104 static void actcon_relink (bConstraint *con)
2105 {
2106         bActionConstraint *data= con->data;
2107         ID_NEW(data->act);
2108 }
2109
2110 static void actcon_new_data (void *cdata)
2111 {
2112         bActionConstraint *data= (bActionConstraint *)cdata;
2113         
2114         /* set type to 20 (Loc X), as 0 is Rot X for backwards compatability */
2115         data->type = 20;
2116 }
2117
2118 static void actcon_id_looper (bConstraint *con, ConstraintIDFunc func, void *userdata)
2119 {
2120         bActionConstraint *data= con->data;
2121         
2122         /* target */
2123         func(con, (ID**)&data->tar, userdata);
2124         
2125         /* action */
2126         func(con, (ID**)&data->act, userdata);
2127 }
2128
2129 static int actcon_get_tars (bConstraint *con, ListBase *list)
2130 {
2131         if (con && list) {
2132                 bActionConstraint *data= con->data;
2133                 bConstraintTarget *ct;
2134                 
2135                 /* standard target-getting macro for single-target constraints */
2136                 SINGLETARGET_GET_TARS(con, data->tar, data->subtarget, ct, list)
2137                 
2138                 return 1;
2139         }
2140         
2141         return 0;
2142 }
2143
2144 static void actcon_flush_tars (bConstraint *con, ListBase *list, short nocopy)
2145 {
2146         if (con && list) {
2147                 bActionConstraint *data= con->data;
2148                 bConstraintTarget *ct= list->first;
2149                 
2150                 /* the following macro is used for all standard single-target constraints */
2151                 SINGLETARGET_FLUSH_TARS(con, data->tar, data->subtarget, ct, list, nocopy)
2152         }
2153 }
2154
2155 static void actcon_get_tarmat (bConstraint *con, bConstraintOb *cob, bConstraintTarget *ct, float UNUSED(ctime))
2156 {
2157         bActionConstraint *data = con->data;
2158         
2159         if (VALID_CONS_TARGET(ct)) {
2160                 float tempmat[4][4], vec[3];
2161                 float s, t;
2162                 short axis;
2163                 
2164                 /* initialise return matrix */
2165                 unit_m4(ct->matrix);
2166                 
2167                 /* get the transform matrix of the target */
2168                 constraint_target_to_mat4(cob->scene, ct->tar, ct->subtarget, tempmat, CONSTRAINT_SPACE_WORLD, ct->space, con->headtail);
2169                 
2170                 /* determine where in transform range target is */
2171                 /* data->type is mapped as follows for backwards compatability:
2172                  *      00,01,02        - rotation (it used to be like this)
2173                  *      10,11,12        - scaling
2174                  *      20,21,22        - location
2175                  */
2176                 if (data->type < 10) {
2177                         /* extract rotation (is in whatever space target should be in) */
2178                         mat4_to_eul(vec, tempmat);
2179                         mul_v3_fl(vec, (float)(180.0/M_PI)); /* rad -> deg */
2180                         axis= data->type;
2181                 }
2182                 else if (data->type < 20) {
2183                         /* extract scaling (is in whatever space target should be in) */
2184                         mat4_to_size(vec, tempmat);
2185                         axis= data->type - 10;
2186                 }
2187                 else {
2188                         /* extract location */
2189                         copy_v3_v3(vec, tempmat[3]);
2190                         axis= data->type - 20;
2191                 }
2192                 
2193                 /* Target defines the animation */
2194                 s = (vec[axis]-data->min) / (data->max-data->min);
2195                 CLAMP(s, 0, 1);
2196                 t = (s * (data->end-data->start)) + data->start;
2197                 
2198                 if (G.f & G_DEBUG)
2199                         printf("do Action Constraint %s - Ob %s Pchan %s \n", con->name, cob->ob->id.name+2, (cob->pchan)?cob->pchan->name:NULL);
2200                 
2201                 /* Get the appropriate information from the action */
2202                 if (cob->type == CONSTRAINT_OBTYPE_BONE) {
2203                         Object workob;
2204                         bPose *pose;
2205                         bPoseChannel *pchan, *tchan;
2206                         
2207                         /* make a temporary pose and evaluate using that */
2208                         pose = MEM_callocN(sizeof(bPose), "pose");
2209                         
2210                         /* make a copy of the bone of interest in the temp pose before evaluating action, so that it can get set 
2211                          *      - we need to manually copy over a few settings, including rotation order, otherwise this fails
2212                          */
2213                         pchan = cob->pchan;
2214                         
2215                         tchan= verify_pose_channel(pose, pchan->name);
2216                         tchan->rotmode= pchan->rotmode;
2217                         
2218                         /* evaluate action using workob (it will only set the PoseChannel in question) */
2219                         what_does_obaction(cob->scene, cob->ob, &workob, pose, data->act, pchan->name, t);
2220                         
2221                         /* convert animation to matrices for use here */
2222                         pchan_calc_mat(tchan);
2223                         copy_m4_m4(ct->matrix, tchan->chan_mat);
2224                         
2225                         /* Clean up */
2226                         free_pose(pose);
2227                 }
2228                 else if (cob->type == CONSTRAINT_OBTYPE_OBJECT) {
2229                         Object workob;
2230                         
2231                         /* evaluate using workob */
2232                         // FIXME: we don't have any consistent standards on limiting effects on object...
2233                         what_does_obaction(cob->scene, cob->ob, &workob, NULL, data->act, NULL, t);
2234                         object_to_mat4(&workob, ct->matrix);
2235                 }
2236                 else {
2237                         /* behaviour undefined... */
2238                         puts("Error: unknown owner type for Action Constraint");
2239                 }
2240         }
2241 }
2242
2243 static void actcon_evaluate (bConstraint *UNUSED(con), bConstraintOb *cob, ListBase *targets)
2244 {
2245         bConstraintTarget *ct= targets->first;
2246         
2247         if (VALID_CONS_TARGET(ct)) {
2248                 float temp[4][4];
2249                 
2250                 /* Nice and simple... we just need to multiply the matrices, as the get_target_matrix
2251                  * function has already taken care of everything else.
2252                  */
2253                 copy_m4_m4(temp, cob->matrix);
2254                 mul_m4_m4m4(cob->matrix, ct->matrix, temp);
2255         }
2256 }
2257
2258 static bConstraintTypeInfo CTI_ACTION = {
2259         CONSTRAINT_TYPE_ACTION, /* type */
2260         sizeof(bActionConstraint), /* size */
2261         "Action", /* name */
2262         "bActionConstraint", /* struct name */
2263         NULL, /* free data */
2264         actcon_relink, /* relink data */
2265         actcon_id_looper, /* id looper */
2266         NULL, /* copy data */
2267         actcon_new_data, /* new data */
2268         actcon_get_tars, /* get constraint targets */
2269         actcon_flush_tars, /* flush constraint targets */
2270         actcon_get_tarmat, /* get target matrix */
2271         actcon_evaluate /* evaluate */
2272 };
2273
2274 /* --------- Locked Track ---------- */
2275
2276 static void locktrack_new_data (void *cdata)
2277 {
2278         bLockTrackConstraint *data= (bLockTrackConstraint *)cdata;
2279         
2280         data->trackflag = TRACK_Y;
2281         data->lockflag = LOCK_Z;
2282 }       
2283
2284 static void locktrack_id_looper (bConstraint *con, ConstraintIDFunc func, void *userdata)
2285 {
2286         bLockTrackConstraint *data= con->data;
2287         
2288         /* target only */
2289         func(con, (ID**)&data->tar, userdata);
2290 }
2291
2292 static int locktrack_get_tars (bConstraint *con, ListBase *list)
2293 {
2294         if (con && list) {
2295                 bLockTrackConstraint *data= con->data;
2296                 bConstraintTarget *ct;
2297                 
2298                 /* the following macro is used for all standard single-target constraints */
2299                 SINGLETARGET_GET_TARS(con, data->tar, data->subtarget, ct, list)
2300                 
2301                 return 1;
2302         }
2303         
2304         return 0;
2305 }
2306
2307 static void locktrack_flush_tars (bConstraint *con, ListBase *list, short nocopy)
2308 {
2309         if (con && list) {
2310                 bLockTrackConstraint *data= con->data;
2311                 bConstraintTarget *ct= list->first;
2312                 
2313                 /* the following macro is used for all standard single-target constraints */
2314                 SINGLETARGET_FLUSH_TARS(con, data->tar, data->subtarget, ct, list, nocopy)
2315         }
2316 }
2317
2318 static void locktrack_evaluate (bConstraint *con, bConstraintOb *cob, ListBase *targets)
2319 {
2320         bLockTrackConstraint *data= con->data;
2321         bConstraintTarget *ct= targets->first;
2322         
2323         if (VALID_CONS_TARGET(ct)) {
2324                 float vec[3],vec2[3];
2325                 float totmat[3][3];
2326                 float tmpmat[3][3];
2327                 float invmat[3][3];
2328                 float tmat[4][4];
2329                 float mdet;
2330                 
2331                 /* Vector object -> target */
2332                 sub_v3_v3v3(vec, ct->matrix[3], cob->matrix[3]);
2333                 switch (data->lockflag){
2334                 case LOCK_X: /* LOCK X */
2335                 {
2336                         switch (data->trackflag) {
2337                                 case TRACK_Y: /* LOCK X TRACK Y */
2338                                 {
2339                                         /* Projection of Vector on the plane */
2340                                         project_v3_v3v3(vec2, vec, cob->matrix[0]);
2341                                         sub_v3_v3v3(totmat[1], vec, vec2);
2342                                         normalize_v3(totmat[1]);
2343                                         
2344                                         /* the x axis is fixed */
2345                                         normalize_v3_v3(totmat[0], cob->matrix[0]);
2346                                         
2347                                         /* the z axis gets mapped onto a third orthogonal vector */
2348                                         cross_v3_v3v3(totmat[2], totmat[0], totmat[1]);
2349                                 }
2350                                         break;
2351                                 case TRACK_Z: /* LOCK X TRACK Z */
2352                                 {
2353                                         /* Projection of Vector on the plane */
2354                                         project_v3_v3v3(vec2, vec, cob->matrix[0]);
2355                                         sub_v3_v3v3(totmat[2], vec, vec2);
2356                                         normalize_v3(totmat[2]);
2357                                         
2358                                         /* the x axis is fixed */
2359                                         normalize_v3_v3(totmat[0], cob->matrix[0]);
2360                                         
2361                                         /* the z axis gets mapped onto a third orthogonal vector */
2362                                         cross_v3_v3v3(totmat[1], totmat[2], totmat[0]);
2363                                 }
2364                                         break;
2365                                 case TRACK_nY: /* LOCK X TRACK -Y */
2366                                 {
2367                                         /* Projection of Vector on the plane */
2368                                         project_v3_v3v3(vec2, vec, cob->matrix[0]);
2369                                         sub_v3_v3v3(totmat[1], vec, vec2);
2370                                         normalize_v3(totmat[1]);
2371                                         negate_v3(totmat[1]);
2372                                         
2373                                         /* the x axis is fixed */
2374                                         normalize_v3_v3(totmat[0], cob->matrix[0]);
2375                                         
2376                                         /* the z axis gets mapped onto a third orthogonal vector */
2377                                         cross_v3_v3v3(totmat[2], totmat[0], totmat[1]);
2378                                 }
2379                                         break;
2380                                 case TRACK_nZ: /* LOCK X TRACK -Z */
2381                                 {
2382                                         /* Projection of Vector on the plane */
2383                                         project_v3_v3v3(vec2, vec, cob->matrix[0]);
2384                                         sub_v3_v3v3(totmat[2], vec, vec2);
2385                                         normalize_v3(totmat[2]);
2386                                         negate_v3(totmat[2]);
2387                                                 
2388                                         /* the x axis is fixed */
2389                                         normalize_v3_v3(totmat[0], cob->matrix[0]);
2390                                                 
2391                                         /* the z axis gets mapped onto a third orthogonal vector */
2392                                         cross_v3_v3v3(totmat[1], totmat[2], totmat[0]);
2393                                 }
2394                                         break;
2395                                 default:
2396                                 {
2397                                         unit_m3(totmat);
2398                                 }
2399                                         break;
2400                         }
2401                 }
2402                         break;
2403                 case LOCK_Y: /* LOCK Y */
2404                 {
2405                         switch (data->trackflag) {
2406                                 case TRACK_X: /* LOCK Y TRACK X */
2407                                 {
2408                                         /* Projection of Vector on the plane */
2409                                         project_v3_v3v3(vec2, vec, cob->matrix[1]);
2410                                         sub_v3_v3v3(totmat[0], vec, vec2);
2411                                         normalize_v3(totmat[0]);
2412                                         
2413                                         /* the y axis is fixed */
2414                                         normalize_v3_v3(totmat[1], cob->matrix[1]);
2415
2416                                         /* the z axis gets mapped onto a third orthogonal vector */
2417                                         cross_v3_v3v3(totmat[2], totmat[0], totmat[1]);
2418                                 }
2419                                         break;
2420                                 case TRACK_Z: /* LOCK Y TRACK Z */
2421                                 {
2422                                         /* Projection of Vector on the plane */
2423                                         project_v3_v3v3(vec2, vec, cob->matrix[1]);
2424                                         sub_v3_v3v3(totmat[2], vec, vec2);
2425                                         normalize_v3(totmat[2]);
2426                                         
2427                                         /* the y axis is fixed */
2428                                         normalize_v3_v3(totmat[1], cob->matrix[1]);
2429                                         
2430                                         /* the z axis gets mapped onto a third orthogonal vector */
2431                                         cross_v3_v3v3(totmat[0], totmat[1], totmat[2]);
2432                                 }
2433                                         break;
2434                                 case TRACK_nX: /* LOCK Y TRACK -X */
2435                                 {
2436                                         /* Projection of Vector on the plane */
2437                                         project_v3_v3v3(vec2, vec, cob->matrix[1]);
2438                                         sub_v3_v3v3(totmat[0], vec, vec2);
2439                                         normalize_v3(totmat[0]);
2440                                         negate_v3(totmat[0]);
2441                                         
2442                                         /* the y axis is fixed */
2443                                         normalize_v3_v3(totmat[1], cob->matrix[1]);
2444                                         
2445                                         /* the z axis gets mapped onto a third orthogonal vector */
2446                                         cross_v3_v3v3(totmat[2], totmat[0], totmat[1]);
2447                                 }
2448                                         break;
2449                                 case TRACK_nZ: /* LOCK Y TRACK -Z */
2450                                 {
2451                                         /* Projection of Vector on the plane */
2452                                         project_v3_v3v3(vec2, vec, cob->matrix[1]);
2453                                         sub_v3_v3v3(totmat[2], vec, vec2);
2454                                         normalize_v3(totmat[2]);
2455                                         negate_v3(totmat[2]);
2456                                         
2457                                         /* the y axis is fixed */
2458                                         normalize_v3_v3(totmat[1], cob->matrix[1]);
2459                                         
2460                                         /* the z axis gets mapped onto a third orthogonal vector */
2461                                         cross_v3_v3v3(totmat[0], totmat[1], totmat[2]);
2462                                 }
2463                                         break;
2464                                 default:
2465                                 {
2466                                         unit_m3(totmat);
2467                                 }
2468                                         break;
2469                         }
2470                 }
2471                         break;
2472                 case LOCK_Z: /* LOCK Z */
2473                 {
2474                         switch (data->trackflag) {
2475                                 case TRACK_X: /* LOCK Z TRACK X */
2476                                 {
2477                                         /* Projection of Vector on the plane */
2478                                         project_v3_v3v3(vec2, vec, cob->matrix[2]);
2479                                         sub_v3_v3v3(totmat[0], vec, vec2);
2480                                         normalize_v3(totmat[0]);
2481                                         
2482                                         /* the z axis is fixed */
2483                                         normalize_v3_v3(totmat[2], cob->matrix[2]);
2484                                         
2485                                         /* the x axis gets mapped onto a third orthogonal vector */
2486                                         cross_v3_v3v3(totmat[1], totmat[2], totmat[0]);
2487                                 }
2488                                         break;
2489                                 case TRACK_Y: /* LOCK Z TRACK Y */
2490                                 {
2491                                         /* Projection of Vector on the plane */
2492                                         project_v3_v3v3(vec2, vec, cob->matrix[2]);
2493                                         sub_v3_v3v3(totmat[1], vec, vec2);
2494                                         normalize_v3(totmat[1]);
2495                                         
2496                                         /* the z axis is fixed */
2497                                         normalize_v3_v3(totmat[2], cob->matrix[2]);
2498                                                 
2499                                         /* the x axis gets mapped onto a third orthogonal vector */
2500                                         cross_v3_v3v3(totmat[0], totmat[1], totmat[2]);
2501                                 }
2502                                         break;
2503                                 case TRACK_nX: /* LOCK Z TRACK -X */
2504                                 {
2505                                         /* Projection of Vector on the plane */
2506                                         project_v3_v3v3(vec2, vec, cob->matrix[2]);
2507                                         sub_v3_v3v3(totmat[0], vec, vec2);
2508                                         normalize_v3(totmat[0]);
2509                                         negate_v3(totmat[0]);
2510                                         
2511                                         /* the z axis is fixed */
2512                                         normalize_v3_v3(totmat[2], cob->matrix[2]);
2513                                         
2514                                         /* the x axis gets mapped onto a third orthogonal vector */
2515                                         cross_v3_v3v3(totmat[1], totmat[2], totmat[0]);
2516                                 }
2517                                         break;
2518                                 case TRACK_nY: /* LOCK Z TRACK -Y */
2519                                 {
2520                                         /* Projection of Vector on the plane */
2521                                         project_v3_v3v3(vec2, vec, cob->matrix[2]);
2522                                         sub_v3_v3v3(totmat[1], vec, vec2);
2523                                         normalize_v3(totmat[1]);
2524                                         negate_v3(totmat[1]);
2525                                         
2526                                         /* the z axis is fixed */
2527                                         normalize_v3_v3(totmat[2], cob->matrix[2]);
2528                                                 
2529                                         /* the x axis gets mapped onto a third orthogonal vector */
2530                                         cross_v3_v3v3(totmat[0], totmat[1], totmat[2]);
2531                                 }
2532                                         break;
2533                                 default:
2534                                 {
2535                                         unit_m3(totmat);
2536                                 }
2537                                         break;
2538                         }
2539                 }
2540                         break;
2541                 default:
2542                 {
2543                         unit_m3(totmat);
2544                 }
2545                         break;
2546                 }
2547                 /* Block to keep matrix heading */
2548                 copy_m3_m4(tmpmat, cob->matrix);
2549                 normalize_m3(tmpmat);
2550                 invert_m3_m3(invmat, tmpmat);
2551                 mul_m3_m3m3(tmpmat, totmat, invmat);
2552                 totmat[0][0] = tmpmat[0][0];totmat[0][1] = tmpmat[0][1];totmat[0][2] = tmpmat[0][2];
2553                 totmat[1][0] = tmpmat[1][0];totmat[1][1] = tmpmat[1][1];totmat[1][2] = tmpmat[1][2];
2554                 totmat[2][0] = tmpmat[2][0];totmat[2][1] = tmpmat[2][1];totmat[2][2] = tmpmat[2][2];
2555                 
2556                 copy_m4_m4(tmat, cob->matrix);
2557                 
2558                 mdet = determinant_m3(  totmat[0][0],totmat[0][1],totmat[0][2],
2559                                                 totmat[1][0],totmat[1][1],totmat[1][2],
2560                                                 totmat[2][0],totmat[2][1],totmat[2][2]);
2561                 if (mdet==0) {
2562                         unit_m3(totmat);
2563                 }
2564                 
2565                 /* apply out transformaton to the object */
2566                 mul_m4_m3m4(cob->matrix, totmat, tmat);
2567         }
2568 }
2569
2570 static bConstraintTypeInfo CTI_LOCKTRACK = {
2571         CONSTRAINT_TYPE_LOCKTRACK, /* type */
2572         sizeof(bLockTrackConstraint), /* size */
2573         "Locked Track", /* name */
2574         "bLockTrackConstraint", /* struct name */
2575         NULL, /* free data */
2576         NULL, /* relink data */
2577         locktrack_id_looper, /* id looper */
2578         NULL, /* copy data */
2579         locktrack_new_data, /* new data */
2580         locktrack_get_tars, /* get constraint targets */
2581         locktrack_flush_tars, /* flush constraint targets */
2582         default_get_tarmat, /* get target matrix */
2583         locktrack_evaluate /* evaluate */
2584 };
2585
2586 /* ---------- Limit Distance Constraint ----------- */
2587
2588 static void distlimit_new_data (void *cdata)
2589 {
2590         bDistLimitConstraint *data= (bDistLimitConstraint *)cdata;
2591         
2592         data->dist= 0.0f;
2593 }
2594
2595 static void distlimit_id_looper (bConstraint *con, ConstraintIDFunc func, void *userdata)
2596 {
2597         bDistLimitConstraint *data= con->data;
2598         
2599         /* target only */
2600         func(con, (ID**)&data->tar, userdata);
2601 }
2602
2603 static int distlimit_get_tars (bConstraint *con, ListBase *list)
2604 {
2605         if (con && list) {
2606                 bDistLimitConstraint *data= con->data;
2607                 bConstraintTarget *ct;
2608                 
2609                 /* standard target-getting macro for single-target constraints */
2610                 SINGLETARGET_GET_TARS(con, data->tar, data->subtarget, ct, list)
2611                 
2612                 return 1;
2613         }
2614         
2615         return 0;
2616 }
2617
2618 static void distlimit_flush_tars (bConstraint *con, ListBase *list, short nocopy)
2619 {
2620         if (con && list) {
2621                 bDistLimitConstraint *data= con->data;
2622                 bConstraintTarget *ct= list->first;
2623                 
2624                 /* the following macro is used for all standard single-target constraints */
2625                 SINGLETARGET_FLUSH_TARS(con, data->tar, data->subtarget, ct, list, nocopy)
2626         }
2627 }
2628
2629 static void distlimit_evaluate (bConstraint *con, bConstraintOb *cob, ListBase *targets)
2630 {
2631         bDistLimitConstraint *data= con->data;
2632         bConstraintTarget *ct= targets->first;
2633         
2634         /* only evaluate if there is a target */
2635         if (VALID_CONS_TARGET(ct)) {
2636                 float dvec[3], dist=0.0f, sfac=1.0f;
2637                 short clamp_surf= 0;
2638                 
2639                 /* calculate our current distance from the target */
2640                 dist= len_v3v3(cob->matrix[3], ct->matrix[3]);
2641                 
2642                 /* set distance (flag is only set when user demands it) */
2643                 if (data->dist == 0)
2644                         data->dist= dist;
2645                 
2646                 /* check if we're which way to clamp from, and calculate interpolation factor (if needed) */
2647                 if (data->mode == LIMITDIST_OUTSIDE) {
2648                         /* if inside, then move to surface */
2649                         if (dist <= data->dist) {
2650                                 clamp_surf= 1;
2651                                 if (dist != 0.0f) sfac= data->dist / dist;
2652                         }
2653                         /* if soft-distance is enabled, start fading once owner is dist+softdist from the target */
2654                         else if (data->flag & LIMITDIST_USESOFT) {
2655                                 if (dist <= (data->dist + data->soft)) {
2656                                         
2657                                 }
2658                         }
2659                 }
2660                 else if (data->mode == LIMITDIST_INSIDE) {
2661                         /* if outside, then move to surface */
2662                         if (dist >= data->dist) {
2663                                 clamp_surf= 1;
2664                                 if (dist != 0.0f) sfac= data->dist / dist;
2665                         }
2666                         /* if soft-distance is enabled, start fading once owner is dist-soft from the target */
2667                         else if (data->flag & LIMITDIST_USESOFT) {
2668                                 // FIXME: there's a problem with "jumping" when this kicks in
2669                                 if (dist >= (data->dist - data->soft)) {
2670                                         sfac = (float)( data->soft*(1.0f - expf(-(dist - data->dist)/data->soft)) + data->dist );
2671                                         if (dist != 0.0f) sfac /= dist;
2672                                         
2673                                         clamp_surf= 1;
2674                                 }
2675                         }
2676                 }
2677                 else {
2678                         if (IS_EQF(dist, data->dist)==0) {
2679                                 clamp_surf= 1;
2680                                 if (dist != 0.0f) sfac= data->dist / dist;
2681                         }
2682                 }
2683                 
2684                 /* clamp to 'surface' (i.e. move owner so that dist == data->dist) */
2685                 if (clamp_surf) {
2686                         /* simply interpolate along line formed by target -> owner */
2687                         interp_v3_v3v3(dvec, ct->matrix[3], cob->matrix[3], sfac);
2688                         
2689                         /* copy new vector onto owner */
2690                         copy_v3_v3(cob->matrix[3], dvec);
2691                 }
2692         }
2693 }
2694
2695 static bConstraintTypeInfo CTI_DISTLIMIT = {
2696         CONSTRAINT_TYPE_DISTLIMIT, /* type */
2697         sizeof(bDistLimitConstraint), /* size */
2698         "Limit Distance", /* name */
2699         "bDistLimitConstraint", /* struct name */
2700         NULL, /* free data */
2701         NULL, /* relink data */
2702         distlimit_id_looper, /* id looper */
2703         NULL, /* copy data */
2704         distlimit_new_data, /* new data */
2705         distlimit_get_tars, /* get constraint targets */
2706         distlimit_flush_tars, /* flush constraint targets */
2707         default_get_tarmat, /* get a target matrix */
2708         distlimit_evaluate /* evaluate */
2709 };
2710
2711 /* ---------- Stretch To ------------ */
2712
2713 static void stretchto_new_data (void *cdata)
2714 {
2715         bStretchToConstraint *data= (bStretchToConstraint *)cdata;
2716         
2717         data->volmode = 0;
2718         data->plane = 0;
2719         data->orglength = 0.0; 
2720         data->bulge = 1.0;
2721 }
2722
2723 static void stretchto_id_looper (bConstraint *con, ConstraintIDFunc func, void *userdata)
2724 {
2725         bStretchToConstraint *data= con->data;
2726         
2727         /* target only */
2728         func(con, (ID**)&data->tar, userdata);
2729 }
2730
2731 static int stretchto_get_tars (bConstraint *con, ListBase *list)
2732 {
2733         if (con && list) {
2734                 bStretchToConstraint *data= con->data;
2735                 bConstraintTarget *ct;
2736                 
2737                 /* standard target-getting macro for single-target constraints */
2738                 SINGLETARGET_GET_TARS(con, data->tar, data->subtarget, ct, list)
2739                 
2740                 return 1;
2741         }
2742         
2743         return 0;
2744 }
2745
2746 static void stretchto_flush_tars (bConstraint *con, ListBase *list, short nocopy)
2747 {
2748         if (con && list) {
2749                 bStretchToConstraint *data= con->data;
2750                 bConstraintTarget *ct= list->first;
2751                 
2752                 /* the following macro is used for all standard single-target constraints */
2753                 SINGLETARGET_FLUSH_TARS(con, data->tar, data->subtarget, ct, list, nocopy)
2754         }
2755 }
2756
2757 static void stretchto_evaluate (bConstraint *con, bConstraintOb *cob, ListBase *targets)
2758 {
2759         bStretchToConstraint *data= con->data;
2760         bConstraintTarget *ct= targets->first;
2761         
2762         /* only evaluate if there is a target */
2763         if (VALID_CONS_TARGET(ct)) {
2764                 float size[3], scale[3], vec[3], xx[3], zz[3], orth[3];
2765                 float totmat[3][3];
2766                 float tmat[4][4];
2767                 float dist;
2768                 
2769                 /* store scaling before destroying obmat */
2770                 mat4_to_size(size, cob->matrix);
2771                 
2772                 /* store X orientation before destroying obmat */
2773                 normalize_v3_v3(xx, cob->matrix[0]);
2774                 
2775                 /* store Z orientation before destroying obmat */
2776                 normalize_v3_v3(zz, cob->matrix[2]);
2777                 
2778                 sub_v3_v3v3(vec, cob->matrix[3], ct->matrix[3]);
2779                 vec[0] /= size[0];
2780                 vec[1] /= size[1];
2781                 vec[2] /= size[2];
2782                 
2783                 dist = normalize_v3(vec);
2784                 //dist = len_v3v3( ob->obmat[3], targetmat[3]);
2785                 
2786                 /* data->orglength==0 occurs on first run, and after 'R' button is clicked */
2787                 if (data->orglength == 0)  
2788                         data->orglength = dist;
2789                 if (data->bulge == 0) 
2790                         data->bulge = 1.0;
2791                 
2792                 scale[1] = dist/data->orglength;
2793                 switch (data->volmode) {
2794                 /* volume preserving scaling */
2795                 case VOLUME_XZ :
2796                         scale[0] = 1.0f - (float)sqrt(data->bulge) + (float)sqrt(data->bulge*(data->orglength/dist));
2797                         scale[2] = scale[0];
2798                         break;
2799                 case VOLUME_X:
2800                         scale[0] = 1.0f + data->bulge * (data->orglength /dist - 1);
2801                         scale[2] = 1.0;
2802                         break;
2803                 case VOLUME_Z:
2804                         scale[0] = 1.0;
2805                         scale[2] = 1.0f + data->bulge * (data->orglength /dist - 1);
2806                         break;
2807                         /* don't care for volume */
2808                 case NO_VOLUME:
2809                         scale[0] = 1.0;
2810                         scale[2] = 1.0;
2811                         break;
2812                 default: /* should not happen, but in case*/
2813                         return;    
2814                 } /* switch (data->volmode) */
2815
2816                 /* Clear the object's rotation and scale */
2817                 cob->matrix[0][0]=size[0]*scale[0];
2818                 cob->matrix[0][1]=0;
2819                 cob->matrix[0][2]=0;
2820                 cob->matrix[1][0]=0;
2821                 cob->matrix[1][1]=size[1]*scale[1];
2822                 cob->matrix[1][2]=0;
2823                 cob->matrix[2][0]=0;
2824                 cob->matrix[2][1]=0;
2825                 cob->matrix[2][2]=size[2]*scale[2];
2826                 
2827                 sub_v3_v3v3(vec, cob->matrix[3], ct->matrix[3]);
2828                 normalize_v3(vec);
2829                 
2830                 /* new Y aligns  object target connection*/
2831                 negate_v3_v3(totmat[1], vec);
2832                 switch (data->plane) {
2833                 case PLANE_X:
2834                         /* build new Z vector */
2835                         /* othogonal to "new Y" "old X! plane */
2836                         cross_v3_v3v3(orth, vec, xx);
2837                         normalize_v3(orth);
2838                         
2839                         /* new Z*/
2840                         copy_v3_v3(totmat[2], orth);
2841                         
2842                         /* we decided to keep X plane*/
2843                         cross_v3_v3v3(xx, orth, vec);
2844                         normalize_v3_v3(totmat[0], xx);
2845                         break;
2846                 case PLANE_Z:
2847                         /* build new X vector */
2848                         /* othogonal to "new Y" "old Z! plane */
2849                         cross_v3_v3v3(orth, vec, zz);
2850                         normalize_v3(orth);
2851                         
2852                         /* new X */
2853                         negate_v3_v3(totmat[0], orth);
2854                         
2855                         /* we decided to keep Z */
2856                         cross_v3_v3v3(zz, orth, vec);
2857                         normalize_v3_v3(totmat[2], zz);
2858                         break;
2859                 } /* switch (data->plane) */
2860                 
2861                 copy_m4_m4(tmat, cob->matrix);
2862                 mul_m4_m3m4(cob->matrix, totmat, tmat);
2863         }
2864 }
2865
2866 static bConstraintTypeInfo CTI_STRETCHTO = {