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