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