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