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