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