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