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