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