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