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