Pass EvaluationContext argument everywhere
[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(struct EvaluationContext *UNUSED(eval_ctx), 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         /* project the up vector onto the plane specified by n */
1022         project_v3_v3v3(proj, u, n); /* first u onto n... */
1023         sub_v3_v3v3(proj, u, proj); /* then onto the plane */
1024         /* proj specifies the transformation of the up axis */
1025
1026         if (normalize_v3(proj) == 0.0f) { /* degenerate projection */
1027                 proj[0] = 0.0f;
1028                 proj[1] = 1.0f;
1029                 proj[2] = 0.0f;
1030         }
1031
1032         /* Normalized cross product of n and proj specifies transformation of the right axis */
1033         cross_v3_v3v3(right, proj, n);
1034         normalize_v3(right);
1035
1036         if (axis != upflag) {
1037                 right_index = 3 - axis - upflag;
1038                 neg = (float)basis_cross(axis, upflag);
1039                 
1040                 /* account for up direction, track direction */
1041                 m[right_index][0] = neg * right[0];
1042                 m[right_index][1] = neg * right[1];
1043                 m[right_index][2] = neg * right[2];
1044                 
1045                 copy_v3_v3(m[upflag], proj);
1046                 
1047                 copy_v3_v3(m[axis], n);
1048         }
1049         /* identity matrix - don't do anything if the two axes are the same */
1050         else {
1051                 unit_m3(m);
1052         }
1053 }
1054
1055
1056 static void trackto_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *targets)
1057 {
1058         bTrackToConstraint *data = con->data;
1059         bConstraintTarget *ct = targets->first;
1060         
1061         if (VALID_CONS_TARGET(ct)) {
1062                 float size[3], vec[3];
1063                 float totmat[3][3];
1064                 
1065                 /* Get size property, since ob->size is only the object's own relative size, not its global one */
1066                 mat4_to_size(size, cob->matrix);
1067                 
1068                 /* Clear the object's rotation */
1069                 cob->matrix[0][0] = size[0];
1070                 cob->matrix[0][1] = 0;
1071                 cob->matrix[0][2] = 0;
1072                 cob->matrix[1][0] = 0;
1073                 cob->matrix[1][1] = size[1];
1074                 cob->matrix[1][2] = 0;
1075                 cob->matrix[2][0] = 0;
1076                 cob->matrix[2][1] = 0;
1077                 cob->matrix[2][2] = size[2];
1078                 
1079                 /* targetmat[2] instead of ownermat[2] is passed to vectomat
1080                  * for backwards compatibility it seems... (Aligorith)
1081                  */
1082                 sub_v3_v3v3(vec, cob->matrix[3], ct->matrix[3]);
1083                 vectomat(vec, ct->matrix[2], 
1084                          (short)data->reserved1, (short)data->reserved2,
1085                          data->flags, totmat);
1086
1087                 mul_m4_m3m4(cob->matrix, totmat, cob->matrix);
1088         }
1089 }
1090
1091 static bConstraintTypeInfo CTI_TRACKTO = {
1092         CONSTRAINT_TYPE_TRACKTO, /* type */
1093         sizeof(bTrackToConstraint), /* size */
1094         "Track To", /* name */
1095         "bTrackToConstraint", /* struct name */
1096         NULL, /* free data */
1097         trackto_id_looper, /* id looper */
1098         NULL, /* copy data */
1099         trackto_new_data, /* new data */
1100         trackto_get_tars, /* get constraint targets */
1101         trackto_flush_tars, /* flush constraint targets */
1102         default_get_tarmat, /* get target matrix */
1103         trackto_evaluate /* evaluate */
1104 };
1105
1106 /* --------- Inverse-Kinematics --------- */
1107
1108 static void kinematic_new_data(void *cdata)
1109 {
1110         bKinematicConstraint *data = (bKinematicConstraint *)cdata;
1111         
1112         data->weight = 1.0f;
1113         data->orientweight = 1.0f;
1114         data->iterations = 500;
1115         data->dist = 1.0f;
1116         data->flag = CONSTRAINT_IK_TIP | CONSTRAINT_IK_STRETCH | CONSTRAINT_IK_POS;
1117 }
1118
1119 static void kinematic_id_looper(bConstraint *con, ConstraintIDFunc func, void *userdata)
1120 {
1121         bKinematicConstraint *data = con->data;
1122         
1123         /* chain target */
1124         func(con, (ID **)&data->tar, false, userdata);
1125         
1126         /* poletarget */
1127         func(con, (ID **)&data->poletar, false, userdata);
1128 }
1129
1130 static int kinematic_get_tars(bConstraint *con, ListBase *list)
1131 {
1132         if (con && list) {
1133                 bKinematicConstraint *data = con->data;
1134                 bConstraintTarget *ct;
1135                 
1136                 /* standard target-getting macro for single-target constraints is used twice here */
1137                 SINGLETARGET_GET_TARS(con, data->tar, data->subtarget, ct, list);
1138                 SINGLETARGET_GET_TARS(con, data->poletar, data->polesubtarget, ct, list);
1139                 
1140                 return 2;
1141         }
1142         
1143         return 0;
1144 }
1145
1146 static void kinematic_flush_tars(bConstraint *con, ListBase *list, bool no_copy)
1147 {
1148         if (con && list) {
1149                 bKinematicConstraint *data = con->data;
1150                 bConstraintTarget *ct = list->first;
1151                 
1152                 /* the following macro is used for all standard single-target constraints */
1153                 SINGLETARGET_FLUSH_TARS(con, data->tar, data->subtarget, ct, list, no_copy);
1154                 SINGLETARGET_FLUSH_TARS(con, data->poletar, data->polesubtarget, ct, list, no_copy);
1155         }
1156 }
1157
1158 static void kinematic_get_tarmat(struct EvaluationContext *UNUSED(eval_ctx), bConstraint *con, bConstraintOb *cob, bConstraintTarget *ct, float UNUSED(ctime))
1159 {
1160         bKinematicConstraint *data = con->data;
1161         
1162         if (VALID_CONS_TARGET(ct)) 
1163                 constraint_target_to_mat4(ct->tar, ct->subtarget, ct->matrix, CONSTRAINT_SPACE_WORLD, ct->space, con->flag, con->headtail);
1164         else if (ct) {
1165                 if (data->flag & CONSTRAINT_IK_AUTO) {
1166                         Object *ob = cob->ob;
1167                         
1168                         if (ob == NULL) {
1169                                 unit_m4(ct->matrix);
1170                         }
1171                         else {
1172                                 float vec[3];
1173                                 /* move grabtarget into world space */
1174                                 mul_v3_m4v3(vec, ob->obmat, data->grabtarget);
1175                                 copy_m4_m4(ct->matrix, ob->obmat);
1176                                 copy_v3_v3(ct->matrix[3], vec);
1177                         }
1178                 }
1179                 else
1180                         unit_m4(ct->matrix);
1181         }
1182 }
1183
1184 static bConstraintTypeInfo CTI_KINEMATIC = {
1185         CONSTRAINT_TYPE_KINEMATIC, /* type */
1186         sizeof(bKinematicConstraint), /* size */
1187         "IK", /* name */
1188         "bKinematicConstraint", /* struct name */
1189         NULL, /* free data */
1190         kinematic_id_looper, /* id looper */
1191         NULL, /* copy data */
1192         kinematic_new_data, /* new data */
1193         kinematic_get_tars, /* get constraint targets */
1194         kinematic_flush_tars, /* flush constraint targets */
1195         kinematic_get_tarmat, /* get target matrix */
1196         NULL /* evaluate - solved as separate loop */
1197 };
1198
1199 /* -------- Follow-Path Constraint ---------- */
1200
1201 static void followpath_new_data(void *cdata)
1202 {
1203         bFollowPathConstraint *data = (bFollowPathConstraint *)cdata;
1204         
1205         data->trackflag = TRACK_Y;
1206         data->upflag = UP_Z;
1207         data->offset = 0;
1208         data->followflag = 0;
1209 }
1210
1211 static void followpath_id_looper(bConstraint *con, ConstraintIDFunc func, void *userdata)
1212 {
1213         bFollowPathConstraint *data = con->data;
1214         
1215         /* target only */
1216         func(con, (ID **)&data->tar, false, userdata);
1217 }
1218
1219 static int followpath_get_tars(bConstraint *con, ListBase *list)
1220 {
1221         if (con && list) {
1222                 bFollowPathConstraint *data = con->data;
1223                 bConstraintTarget *ct;
1224                 
1225                 /* standard target-getting macro for single-target constraints without subtargets */
1226                 SINGLETARGETNS_GET_TARS(con, data->tar, ct, list);
1227                 
1228                 return 1;
1229         }
1230         
1231         return 0;
1232 }
1233
1234 static void followpath_flush_tars(bConstraint *con, ListBase *list, bool no_copy)
1235 {
1236         if (con && list) {
1237                 bFollowPathConstraint *data = con->data;
1238                 bConstraintTarget *ct = list->first;
1239                 
1240                 /* the following macro is used for all standard single-target constraints */
1241                 SINGLETARGETNS_FLUSH_TARS(con, data->tar, ct, list, no_copy);
1242         }
1243 }
1244
1245 static void followpath_get_tarmat(struct EvaluationContext *eval_ctx, bConstraint *con, bConstraintOb *cob, bConstraintTarget *ct, float UNUSED(ctime))
1246 {
1247         bFollowPathConstraint *data = con->data;
1248         
1249         if (VALID_CONS_TARGET(ct) && (ct->tar->type == OB_CURVE)) {
1250                 Curve *cu = ct->tar->data;
1251                 float vec[4], dir[3], radius;
1252                 float curvetime;
1253
1254                 unit_m4(ct->matrix);
1255
1256                 /* note: when creating constraints that follow path, the curve gets the CU_PATH set now,
1257                  *              currently for paths to work it needs to go through the bevlist/displist system (ton) 
1258                  */
1259
1260 #ifdef CYCLIC_DEPENDENCY_WORKAROUND
1261                 if (ct->tar->curve_cache == NULL) {
1262                         BKE_displist_make_curveTypes(eval_ctx, cob->scene, ct->tar, false);
1263                 }
1264 #endif
1265
1266                 if (ct->tar->curve_cache->path && ct->tar->curve_cache->path->data) {
1267                         float quat[4];
1268                         if ((data->followflag & FOLLOWPATH_STATIC) == 0) {
1269                                 /* animated position along curve depending on time */
1270                                 Nurb *nu = cu->nurb.first;
1271                                 curvetime = cu->ctime - data->offset;
1272                                 
1273                                 /* ctime is now a proper var setting of Curve which gets set by Animato like any other var that's animated,
1274                                  * but this will only work if it actually is animated... 
1275                                  *
1276                                  * we divide the curvetime calculated in the previous step by the length of the path, to get a time
1277                                  * factor, which then gets clamped to lie within 0.0 - 1.0 range
1278                                  */
1279                                 curvetime /= cu->pathlen;
1280
1281                                 if (nu && nu->flagu & CU_NURB_CYCLIC) {
1282                                         /* If the curve is cyclic, enable looping around if the time is
1283                                          * outside the bounds 0..1 */
1284                                         if ((curvetime < 0.0f) || (curvetime > 1.0f)) {
1285                                                 curvetime -= floorf(curvetime);
1286                                         }
1287                                 }
1288                                 else {
1289                                         /* The curve is not cyclic, so clamp to the begin/end points. */
1290                                         CLAMP(curvetime, 0.0f, 1.0f);
1291                                 }
1292                         }
1293                         else {
1294                                 /* fixed position along curve */
1295                                 curvetime = data->offset_fac;
1296                         }
1297                         
1298                         if (where_on_path(ct->tar, curvetime, vec, dir, (data->followflag & FOLLOWPATH_FOLLOW) ? quat : NULL, &radius, NULL) ) {  /* quat_pt is quat or NULL*/
1299                                 float totmat[4][4];
1300                                 unit_m4(totmat);
1301
1302                                 if (data->followflag & FOLLOWPATH_FOLLOW) {
1303 #if 0
1304                                         float x1, q[4];
1305                                         vec_to_quat(quat, dir, (short)data->trackflag, (short)data->upflag);
1306                                         
1307                                         normalize_v3(dir);
1308                                         q[0] = cosf(0.5 * vec[3]);
1309                                         x1 = sinf(0.5 * vec[3]);
1310                                         q[1] = -x1 * dir[0];
1311                                         q[2] = -x1 * dir[1];
1312                                         q[3] = -x1 * dir[2];
1313                                         mul_qt_qtqt(quat, q, quat);
1314 #else
1315                                         quat_apply_track(quat, data->trackflag, data->upflag);
1316 #endif
1317
1318                                         quat_to_mat4(totmat, quat);
1319                                 }
1320
1321                                 if (data->followflag & FOLLOWPATH_RADIUS) {
1322                                         float tmat[4][4], rmat[4][4];
1323                                         scale_m4_fl(tmat, radius);
1324                                         mul_m4_m4m4(rmat, tmat, totmat);
1325                                         copy_m4_m4(totmat, rmat);
1326                                 }
1327                                 
1328                                 copy_v3_v3(totmat[3], vec);
1329                                 
1330                                 mul_m4_m4m4(ct->matrix, ct->tar->obmat, totmat);
1331                         }
1332                 }
1333         }
1334         else if (ct)
1335                 unit_m4(ct->matrix);
1336 }
1337
1338 static void followpath_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *targets)
1339 {
1340         bConstraintTarget *ct = targets->first;
1341         
1342         /* only evaluate if there is a target */
1343         if (VALID_CONS_TARGET(ct)) {
1344                 float obmat[4][4];
1345                 float size[3];
1346                 bFollowPathConstraint *data = con->data;
1347                 
1348                 /* get Object transform (loc/rot/size) to determine transformation from path */
1349                 /* TODO: this used to be local at one point, but is probably more useful as-is */
1350                 copy_m4_m4(obmat, cob->matrix);
1351                 
1352                 /* get scaling of object before applying constraint */
1353                 mat4_to_size(size, cob->matrix);
1354                 
1355                 /* apply targetmat - containing location on path, and rotation */
1356                 mul_m4_m4m4(cob->matrix, ct->matrix, obmat);
1357                 
1358                 /* un-apply scaling caused by path */
1359                 if ((data->followflag & FOLLOWPATH_RADIUS) == 0) { /* XXX - assume that scale correction means that radius will have some scale error in it - Campbell */
1360                         float obsize[3];
1361                         
1362                         mat4_to_size(obsize, cob->matrix);
1363                         if (obsize[0])
1364                                 mul_v3_fl(cob->matrix[0], size[0] / obsize[0]);
1365                         if (obsize[1])
1366                                 mul_v3_fl(cob->matrix[1], size[1] / obsize[1]);
1367                         if (obsize[2])
1368                                 mul_v3_fl(cob->matrix[2], size[2] / obsize[2]);
1369                 }
1370         }
1371 }
1372
1373 static bConstraintTypeInfo CTI_FOLLOWPATH = {
1374         CONSTRAINT_TYPE_FOLLOWPATH, /* type */
1375         sizeof(bFollowPathConstraint), /* size */
1376         "Follow Path", /* name */
1377         "bFollowPathConstraint", /* struct name */
1378         NULL, /* free data */
1379         followpath_id_looper, /* id looper */
1380         NULL, /* copy data */
1381         followpath_new_data, /* new data */
1382         followpath_get_tars, /* get constraint targets */
1383         followpath_flush_tars, /* flush constraint targets */
1384         followpath_get_tarmat, /* get target matrix */
1385         followpath_evaluate /* evaluate */
1386 };
1387
1388 /* --------- Limit Location --------- */
1389
1390
1391 static void loclimit_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *UNUSED(targets))
1392 {
1393         bLocLimitConstraint *data = con->data;
1394         
1395         if (data->flag & LIMIT_XMIN) {
1396                 if (cob->matrix[3][0] < data->xmin)
1397                         cob->matrix[3][0] = data->xmin;
1398         }
1399         if (data->flag & LIMIT_XMAX) {
1400                 if (cob->matrix[3][0] > data->xmax)
1401                         cob->matrix[3][0] = data->xmax;
1402         }
1403         if (data->flag & LIMIT_YMIN) {
1404                 if (cob->matrix[3][1] < data->ymin)
1405                         cob->matrix[3][1] = data->ymin;
1406         }
1407         if (data->flag & LIMIT_YMAX) {
1408                 if (cob->matrix[3][1] > data->ymax)
1409                         cob->matrix[3][1] = data->ymax;
1410         }
1411         if (data->flag & LIMIT_ZMIN) {
1412                 if (cob->matrix[3][2] < data->zmin) 
1413                         cob->matrix[3][2] = data->zmin;
1414         }
1415         if (data->flag & LIMIT_ZMAX) {
1416                 if (cob->matrix[3][2] > data->zmax)
1417                         cob->matrix[3][2] = data->zmax;
1418         }
1419 }
1420
1421 static bConstraintTypeInfo CTI_LOCLIMIT = {
1422         CONSTRAINT_TYPE_LOCLIMIT, /* type */
1423         sizeof(bLocLimitConstraint), /* size */
1424         "Limit Location", /* name */
1425         "bLocLimitConstraint", /* struct name */
1426         NULL, /* free data */
1427         NULL, /* id looper */
1428         NULL, /* copy data */
1429         NULL, /* new data */
1430         NULL, /* get constraint targets */
1431         NULL, /* flush constraint targets */
1432         NULL, /* get target matrix */
1433         loclimit_evaluate /* evaluate */
1434 };
1435
1436 /* -------- Limit Rotation --------- */
1437
1438 static void rotlimit_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *UNUSED(targets))
1439 {
1440         bRotLimitConstraint *data = con->data;
1441         float loc[3];
1442         float eul[3];
1443         float size[3];
1444         
1445         copy_v3_v3(loc, cob->matrix[3]);
1446         mat4_to_size(size, cob->matrix);
1447
1448         mat4_to_eulO(eul, cob->rotOrder, cob->matrix);
1449
1450         /* constraint data uses radians internally */
1451         
1452         /* limiting of euler values... */
1453         if (data->flag & LIMIT_XROT) {
1454                 if (eul[0] < data->xmin) 
1455                         eul[0] = data->xmin;
1456                         
1457                 if (eul[0] > data->xmax)
1458                         eul[0] = data->xmax;
1459         }
1460         if (data->flag & LIMIT_YROT) {
1461                 if (eul[1] < data->ymin)
1462                         eul[1] = data->ymin;
1463                         
1464                 if (eul[1] > data->ymax)
1465                         eul[1] = data->ymax;
1466         }
1467         if (data->flag & LIMIT_ZROT) {
1468                 if (eul[2] < data->zmin)
1469                         eul[2] = data->zmin;
1470                         
1471                 if (eul[2] > data->zmax)
1472                         eul[2] = data->zmax;
1473         }
1474                 
1475         loc_eulO_size_to_mat4(cob->matrix, loc, eul, size, cob->rotOrder);
1476 }
1477
1478 static bConstraintTypeInfo CTI_ROTLIMIT = {
1479         CONSTRAINT_TYPE_ROTLIMIT, /* type */
1480         sizeof(bRotLimitConstraint), /* size */
1481         "Limit Rotation", /* name */
1482         "bRotLimitConstraint", /* struct name */
1483         NULL, /* free data */
1484         NULL, /* id looper */
1485         NULL, /* copy data */
1486         NULL, /* new data */
1487         NULL, /* get constraint targets */
1488         NULL, /* flush constraint targets */
1489         NULL, /* get target matrix */
1490         rotlimit_evaluate /* evaluate */
1491 };
1492
1493 /* --------- Limit Scale --------- */
1494
1495
1496 static void sizelimit_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *UNUSED(targets))
1497 {
1498         bSizeLimitConstraint *data = con->data;
1499         float obsize[3], size[3];
1500         
1501         mat4_to_size(size, cob->matrix);
1502         mat4_to_size(obsize, cob->matrix);
1503         
1504         if (data->flag & LIMIT_XMIN) {
1505                 if (size[0] < data->xmin) 
1506                         size[0] = data->xmin;
1507         }
1508         if (data->flag & LIMIT_XMAX) {
1509                 if (size[0] > data->xmax) 
1510                         size[0] = data->xmax;
1511         }
1512         if (data->flag & LIMIT_YMIN) {
1513                 if (size[1] < data->ymin) 
1514                         size[1] = data->ymin;
1515         }
1516         if (data->flag & LIMIT_YMAX) {
1517                 if (size[1] > data->ymax) 
1518                         size[1] = data->ymax;
1519         }
1520         if (data->flag & LIMIT_ZMIN) {
1521                 if (size[2] < data->zmin) 
1522                         size[2] = data->zmin;
1523         }
1524         if (data->flag & LIMIT_ZMAX) {
1525                 if (size[2] > data->zmax) 
1526                         size[2] = data->zmax;
1527         }
1528         
1529         if (obsize[0]) 
1530                 mul_v3_fl(cob->matrix[0], size[0] / obsize[0]);
1531         if (obsize[1]) 
1532                 mul_v3_fl(cob->matrix[1], size[1] / obsize[1]);
1533         if (obsize[2]) 
1534                 mul_v3_fl(cob->matrix[2], size[2] / obsize[2]);
1535 }
1536
1537 static bConstraintTypeInfo CTI_SIZELIMIT = {
1538         CONSTRAINT_TYPE_SIZELIMIT, /* type */
1539         sizeof(bSizeLimitConstraint), /* size */
1540         "Limit Scale", /* name */
1541         "bSizeLimitConstraint", /* struct name */
1542         NULL, /* free data */
1543         NULL, /* id looper */
1544         NULL, /* copy data */
1545         NULL, /* new data */
1546         NULL, /* get constraint targets */
1547         NULL, /* flush constraint targets */
1548         NULL, /* get target matrix */
1549         sizelimit_evaluate /* evaluate */
1550 };
1551
1552 /* ----------- Copy Location ------------- */
1553
1554 static void loclike_new_data(void *cdata)
1555 {
1556         bLocateLikeConstraint *data = (bLocateLikeConstraint *)cdata;
1557         
1558         data->flag = LOCLIKE_X | LOCLIKE_Y | LOCLIKE_Z;
1559 }
1560
1561 static void loclike_id_looper(bConstraint *con, ConstraintIDFunc func, void *userdata)
1562 {
1563         bLocateLikeConstraint *data = con->data;
1564         
1565         /* target only */
1566         func(con, (ID **)&data->tar, false, userdata);
1567 }
1568
1569 static int loclike_get_tars(bConstraint *con, ListBase *list)
1570 {
1571         if (con && list) {
1572                 bLocateLikeConstraint *data = con->data;
1573                 bConstraintTarget *ct;
1574                 
1575                 /* standard target-getting macro for single-target constraints */
1576                 SINGLETARGET_GET_TARS(con, data->tar, data->subtarget, ct, list);
1577                 
1578                 return 1;
1579         }
1580         
1581         return 0;
1582 }
1583
1584 static void loclike_flush_tars(bConstraint *con, ListBase *list, bool no_copy)
1585 {
1586         if (con && list) {
1587                 bLocateLikeConstraint *data = con->data;
1588                 bConstraintTarget *ct = list->first;
1589                 
1590                 /* the following macro is used for all standard single-target constraints */
1591                 SINGLETARGET_FLUSH_TARS(con, data->tar, data->subtarget, ct, list, no_copy);
1592         }
1593 }
1594
1595 static void loclike_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *targets)
1596 {
1597         bLocateLikeConstraint *data = con->data;
1598         bConstraintTarget *ct = targets->first;
1599         
1600         if (VALID_CONS_TARGET(ct)) {
1601                 float offset[3] = {0.0f, 0.0f, 0.0f};
1602                 
1603                 if (data->flag & LOCLIKE_OFFSET)
1604                         copy_v3_v3(offset, cob->matrix[3]);
1605                         
1606                 if (data->flag & LOCLIKE_X) {
1607                         cob->matrix[3][0] = ct->matrix[3][0];
1608                         
1609                         if (data->flag & LOCLIKE_X_INVERT) cob->matrix[3][0] *= -1;
1610                         cob->matrix[3][0] += offset[0];
1611                 }
1612                 if (data->flag & LOCLIKE_Y) {
1613                         cob->matrix[3][1] = ct->matrix[3][1];
1614                         
1615                         if (data->flag & LOCLIKE_Y_INVERT) cob->matrix[3][1] *= -1;
1616                         cob->matrix[3][1] += offset[1];
1617                 }
1618                 if (data->flag & LOCLIKE_Z) {
1619                         cob->matrix[3][2] = ct->matrix[3][2];
1620                         
1621                         if (data->flag & LOCLIKE_Z_INVERT) cob->matrix[3][2] *= -1;
1622                         cob->matrix[3][2] += offset[2];
1623                 }
1624         }
1625 }
1626
1627 static bConstraintTypeInfo CTI_LOCLIKE = {
1628         CONSTRAINT_TYPE_LOCLIKE, /* type */
1629         sizeof(bLocateLikeConstraint), /* size */
1630         "Copy Location", /* name */
1631         "bLocateLikeConstraint", /* struct name */
1632         NULL, /* free data */
1633         loclike_id_looper, /* id looper */
1634         NULL, /* copy data */
1635         loclike_new_data, /* new data */
1636         loclike_get_tars, /* get constraint targets */
1637         loclike_flush_tars, /* flush constraint targets */
1638         default_get_tarmat, /* get target matrix */
1639         loclike_evaluate /* evaluate */
1640 };
1641
1642 /* ----------- Copy Rotation ------------- */
1643
1644 static void rotlike_new_data(void *cdata)
1645 {
1646         bRotateLikeConstraint *data = (bRotateLikeConstraint *)cdata;
1647         
1648         data->flag = ROTLIKE_X | ROTLIKE_Y | ROTLIKE_Z;
1649 }
1650
1651 static void rotlike_id_looper(bConstraint *con, ConstraintIDFunc func, void *userdata)
1652 {
1653         bRotateLikeConstraint *data = con->data;
1654         
1655         /* target only */
1656         func(con, (ID **)&data->tar, false, userdata);
1657 }
1658
1659 static int rotlike_get_tars(bConstraint *con, ListBase *list)
1660 {
1661         if (con && list) {
1662                 bRotateLikeConstraint *data = con->data;
1663                 bConstraintTarget *ct;
1664                 
1665                 /* standard target-getting macro for single-target constraints */
1666                 SINGLETARGET_GET_TARS(con, data->tar, data->subtarget, ct, list);
1667                 
1668                 return 1;
1669         }
1670         
1671         return 0;
1672 }
1673
1674 static void rotlike_flush_tars(bConstraint *con, ListBase *list, bool no_copy)
1675 {
1676         if (con && list) {
1677                 bRotateLikeConstraint *data = con->data;
1678                 bConstraintTarget *ct = list->first;
1679                 
1680                 /* the following macro is used for all standard single-target constraints */
1681                 SINGLETARGET_FLUSH_TARS(con, data->tar, data->subtarget, ct, list, no_copy);
1682         }
1683 }
1684
1685 static void rotlike_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *targets)
1686 {
1687         bRotateLikeConstraint *data = con->data;
1688         bConstraintTarget *ct = targets->first;
1689         
1690         if (VALID_CONS_TARGET(ct)) {
1691                 float loc[3];
1692                 float eul[3], obeul[3];
1693                 float size[3];
1694                 
1695                 copy_v3_v3(loc, cob->matrix[3]);
1696                 mat4_to_size(size, cob->matrix);
1697                 
1698                 /* to allow compatible rotations, must get both rotations in the order of the owner... */
1699                 mat4_to_eulO(obeul, cob->rotOrder, cob->matrix);
1700                 /* we must get compatible eulers from the beginning because some of them can be modified below (see bug #21875) */
1701                 mat4_to_compatible_eulO(eul, obeul, cob->rotOrder, ct->matrix);
1702                 
1703                 if ((data->flag & ROTLIKE_X) == 0)
1704                         eul[0] = obeul[0];
1705                 else {
1706                         if (data->flag & ROTLIKE_OFFSET)
1707                                 rotate_eulO(eul, cob->rotOrder, 'X', obeul[0]);
1708                         
1709                         if (data->flag & ROTLIKE_X_INVERT)
1710                                 eul[0] *= -1;
1711                 }
1712                 
1713                 if ((data->flag & ROTLIKE_Y) == 0)
1714                         eul[1] = obeul[1];
1715                 else {
1716                         if (data->flag & ROTLIKE_OFFSET)
1717                                 rotate_eulO(eul, cob->rotOrder, 'Y', obeul[1]);
1718                         
1719                         if (data->flag & ROTLIKE_Y_INVERT)
1720                                 eul[1] *= -1;
1721                 }
1722                 
1723                 if ((data->flag & ROTLIKE_Z) == 0)
1724                         eul[2] = obeul[2];
1725                 else {
1726                         if (data->flag & ROTLIKE_OFFSET)
1727                                 rotate_eulO(eul, cob->rotOrder, 'Z', obeul[2]);
1728                         
1729                         if (data->flag & ROTLIKE_Z_INVERT)
1730                                 eul[2] *= -1;
1731                 }
1732                 
1733                 /* good to make eulers compatible again, since we don't know how much they were changed above */
1734                 compatible_eul(eul, obeul);
1735                 loc_eulO_size_to_mat4(cob->matrix, loc, eul, size, cob->rotOrder);
1736         }
1737 }
1738
1739 static bConstraintTypeInfo CTI_ROTLIKE = {
1740         CONSTRAINT_TYPE_ROTLIKE, /* type */
1741         sizeof(bRotateLikeConstraint), /* size */
1742         "Copy Rotation", /* name */
1743         "bRotateLikeConstraint", /* struct name */
1744         NULL, /* free data */
1745         rotlike_id_looper, /* id looper */
1746         NULL, /* copy data */
1747         rotlike_new_data, /* new data */
1748         rotlike_get_tars, /* get constraint targets */
1749         rotlike_flush_tars, /* flush constraint targets */
1750         default_get_tarmat, /* get target matrix */
1751         rotlike_evaluate /* evaluate */
1752 };
1753
1754 /* ---------- Copy Scale ---------- */
1755
1756 static void sizelike_new_data(void *cdata)
1757 {
1758         bSizeLikeConstraint *data = (bSizeLikeConstraint *)cdata;
1759         
1760         data->flag = SIZELIKE_X | SIZELIKE_Y | SIZELIKE_Z;
1761 }
1762
1763 static void sizelike_id_looper(bConstraint *con, ConstraintIDFunc func, void *userdata)
1764 {
1765         bSizeLikeConstraint *data = con->data;
1766         
1767         /* target only */
1768         func(con, (ID **)&data->tar, false, userdata);
1769 }
1770
1771 static int sizelike_get_tars(bConstraint *con, ListBase *list)
1772 {
1773         if (con && list) {
1774                 bSizeLikeConstraint *data = con->data;
1775                 bConstraintTarget *ct;
1776                 
1777                 /* standard target-getting macro for single-target constraints */
1778                 SINGLETARGET_GET_TARS(con, data->tar, data->subtarget, ct, list);
1779                 
1780                 return 1;
1781         }
1782         
1783         return 0;
1784 }
1785
1786 static void sizelike_flush_tars(bConstraint *con, ListBase *list, bool no_copy)
1787 {
1788         if (con && list) {
1789                 bSizeLikeConstraint *data = con->data;
1790                 bConstraintTarget *ct = list->first;
1791                 
1792                 /* the following macro is used for all standard single-target constraints */
1793                 SINGLETARGET_FLUSH_TARS(con, data->tar, data->subtarget, ct, list, no_copy);
1794         }
1795 }
1796
1797 static void sizelike_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *targets)
1798 {
1799         bSizeLikeConstraint *data = con->data;
1800         bConstraintTarget *ct = targets->first;
1801         
1802         if (VALID_CONS_TARGET(ct)) {
1803                 float obsize[3], size[3];
1804                 
1805                 mat4_to_size(size, ct->matrix);
1806                 mat4_to_size(obsize, cob->matrix);
1807                 
1808                 if ((data->flag & SIZELIKE_X) && (obsize[0] != 0)) {
1809                         if (data->flag & SIZELIKE_OFFSET) {
1810                                 size[0] += (obsize[0] - 1.0f);
1811                                 mul_v3_fl(cob->matrix[0], size[0] / obsize[0]);
1812                         }
1813                         else
1814                                 mul_v3_fl(cob->matrix[0], size[0] / obsize[0]);
1815                 }
1816                 if ((data->flag & SIZELIKE_Y) && (obsize[1] != 0)) {
1817                         if (data->flag & SIZELIKE_OFFSET) {
1818                                 size[1] += (obsize[1] - 1.0f);
1819                                 mul_v3_fl(cob->matrix[1], size[1] / obsize[1]);
1820                         }
1821                         else
1822                                 mul_v3_fl(cob->matrix[1], size[1] / obsize[1]);
1823                 }
1824                 if ((data->flag & SIZELIKE_Z) && (obsize[2] != 0)) {
1825                         if (data->flag & SIZELIKE_OFFSET) {
1826                                 size[2] += (obsize[2] - 1.0f);
1827                                 mul_v3_fl(cob->matrix[2], size[2] / obsize[2]);
1828                         }
1829                         else
1830                                 mul_v3_fl(cob->matrix[2], size[2] / obsize[2]);
1831                 }
1832         }
1833 }
1834
1835 static bConstraintTypeInfo CTI_SIZELIKE = {
1836         CONSTRAINT_TYPE_SIZELIKE, /* type */
1837         sizeof(bSizeLikeConstraint), /* size */
1838         "Copy Scale", /* name */
1839         "bSizeLikeConstraint", /* struct name */
1840         NULL, /* free data */
1841         sizelike_id_looper, /* id looper */
1842         NULL, /* copy data */
1843         sizelike_new_data, /* new data */
1844         sizelike_get_tars, /* get constraint targets */
1845         sizelike_flush_tars, /* flush constraint targets */
1846         default_get_tarmat, /* get target matrix */
1847         sizelike_evaluate /* evaluate */
1848 };
1849
1850 /* ----------- Copy Transforms ------------- */
1851
1852 static void translike_id_looper(bConstraint *con, ConstraintIDFunc func, void *userdata)
1853 {
1854         bTransLikeConstraint *data = con->data;
1855         
1856         /* target only */
1857         func(con, (ID **)&data->tar, false, userdata);
1858 }
1859
1860 static int translike_get_tars(bConstraint *con, ListBase *list)
1861 {
1862         if (con && list) {
1863                 bTransLikeConstraint *data = con->data;
1864                 bConstraintTarget *ct;
1865                 
1866                 /* standard target-getting macro for single-target constraints */
1867                 SINGLETARGET_GET_TARS(con, data->tar, data->subtarget, ct, list);
1868                 
1869                 return 1;
1870         }
1871         
1872         return 0;
1873 }
1874
1875 static void translike_flush_tars(bConstraint *con, ListBase *list, bool no_copy)
1876 {
1877         if (con && list) {
1878                 bTransLikeConstraint *data = con->data;
1879                 bConstraintTarget *ct = list->first;
1880                 
1881                 /* the following macro is used for all standard single-target constraints */
1882                 SINGLETARGET_FLUSH_TARS(con, data->tar, data->subtarget, ct, list, no_copy);
1883         }
1884 }
1885
1886 static void translike_evaluate(bConstraint *UNUSED(con), bConstraintOb *cob, ListBase *targets)
1887 {
1888         bConstraintTarget *ct = targets->first;
1889         
1890         if (VALID_CONS_TARGET(ct)) {
1891                 /* just copy the entire transform matrix of the target */
1892                 copy_m4_m4(cob->matrix, ct->matrix);
1893         }
1894 }
1895
1896 static bConstraintTypeInfo CTI_TRANSLIKE = {
1897         CONSTRAINT_TYPE_TRANSLIKE, /* type */
1898         sizeof(bTransLikeConstraint), /* size */
1899         "Copy Transforms", /* name */
1900         "bTransLikeConstraint", /* struct name */
1901         NULL, /* free data */
1902         translike_id_looper, /* id looper */
1903         NULL, /* copy data */
1904         NULL, /* new data */
1905         translike_get_tars, /* get constraint targets */
1906         translike_flush_tars, /* flush constraint targets */
1907         default_get_tarmat, /* get target matrix */
1908         translike_evaluate /* evaluate */
1909 };
1910
1911 /* ---------- Maintain Volume ---------- */
1912
1913 static void samevolume_new_data(void *cdata)
1914 {
1915         bSameVolumeConstraint *data = (bSameVolumeConstraint *)cdata;
1916
1917         data->flag = SAMEVOL_Y;
1918         data->volume = 1.0f;
1919 }
1920
1921 static void samevolume_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *UNUSED(targets))
1922 {
1923         bSameVolumeConstraint *data = con->data;
1924
1925         float volume = data->volume;
1926         float fac = 1.0f;
1927         float obsize[3];
1928
1929         mat4_to_size(obsize, cob->matrix);
1930         
1931         /* calculate normalizing scale factor for non-essential values */
1932         if (obsize[data->flag] != 0) 
1933                 fac = sqrtf(volume / obsize[data->flag]) / obsize[data->flag];
1934         
1935         /* apply scaling factor to the channels not being kept */
1936         switch (data->flag) {
1937                 case SAMEVOL_X:
1938                         mul_v3_fl(cob->matrix[1], fac);
1939                         mul_v3_fl(cob->matrix[2], fac);
1940                         break;
1941                 case SAMEVOL_Y:
1942                         mul_v3_fl(cob->matrix[0], fac);
1943                         mul_v3_fl(cob->matrix[2], fac);
1944                         break;
1945                 case SAMEVOL_Z:
1946                         mul_v3_fl(cob->matrix[0], fac);
1947                         mul_v3_fl(cob->matrix[1], fac);
1948                         break;
1949         }
1950 }
1951
1952 static bConstraintTypeInfo CTI_SAMEVOL = {
1953         CONSTRAINT_TYPE_SAMEVOL, /* type */
1954         sizeof(bSameVolumeConstraint), /* size */
1955         "Maintain Volume", /* name */
1956         "bSameVolumeConstraint", /* struct name */
1957         NULL, /* free data */
1958         NULL, /* id looper */
1959         NULL, /* copy data */
1960         samevolume_new_data, /* new data */
1961         NULL, /* get constraint targets */
1962         NULL, /* flush constraint targets */
1963         NULL, /* get target matrix */
1964         samevolume_evaluate /* evaluate */
1965 };
1966
1967 /* ----------- Python Constraint -------------- */
1968
1969 static void pycon_free(bConstraint *con)
1970 {
1971         bPythonConstraint *data = con->data;
1972         
1973         /* id-properties */
1974         IDP_FreeProperty(data->prop);
1975         MEM_freeN(data->prop);
1976         
1977         /* multiple targets */
1978         BLI_freelistN(&data->targets);
1979 }       
1980
1981 static void pycon_copy(bConstraint *con, bConstraint *srccon)
1982 {
1983         bPythonConstraint *pycon = (bPythonConstraint *)con->data;
1984         bPythonConstraint *opycon = (bPythonConstraint *)srccon->data;
1985         
1986         pycon->prop = IDP_CopyProperty(opycon->prop);
1987         BLI_duplicatelist(&pycon->targets, &opycon->targets);
1988 }
1989
1990 static void pycon_new_data(void *cdata)
1991 {
1992         bPythonConstraint *data = (bPythonConstraint *)cdata;
1993         
1994         /* everything should be set correctly by calloc, except for the prop->type constant.*/
1995         data->prop = MEM_callocN(sizeof(IDProperty), "PyConstraintProps");
1996         data->prop->type = IDP_GROUP;
1997 }
1998
1999 static int pycon_get_tars(bConstraint *con, ListBase *list)
2000 {
2001         if (con && list) {
2002                 bPythonConstraint *data = con->data;
2003                 
2004                 list->first = data->targets.first;
2005                 list->last = data->targets.last;
2006                 
2007                 return data->tarnum;
2008         }
2009         
2010         return 0;
2011 }
2012
2013 static void pycon_id_looper(bConstraint *con, ConstraintIDFunc func, void *userdata)
2014 {
2015         bPythonConstraint *data = con->data;
2016         bConstraintTarget *ct;
2017         
2018         /* targets */
2019         for (ct = data->targets.first; ct; ct = ct->next)
2020                 func(con, (ID **)&ct->tar, false, userdata);
2021                 
2022         /* script */
2023         func(con, (ID **)&data->text, true, userdata);
2024 }
2025
2026 /* Whether this approach is maintained remains to be seen (aligorith) */
2027 static void pycon_get_tarmat(struct EvaluationContext *eval_ctx, bConstraint *con, bConstraintOb *cob, bConstraintTarget *ct, float UNUSED(ctime))
2028 {
2029 #ifdef WITH_PYTHON
2030         bPythonConstraint *data = con->data;
2031 #endif
2032
2033         if (VALID_CONS_TARGET(ct)) {
2034 #ifdef CYCLIC_DEPENDENCY_WORKAROUND
2035                 /* special exception for curves - depsgraph issues */
2036                 if (ct->tar->type == OB_CURVE) {
2037                         if (ct->tar->curve_cache == NULL) {
2038                                 BKE_displist_make_curveTypes(eval_ctx, cob->scene, ct->tar, false);
2039                         }
2040                 }
2041 #endif
2042
2043                 /* firstly calculate the matrix the normal way, then let the py-function override
2044                  * this matrix if it needs to do so
2045                  */
2046                 constraint_target_to_mat4(ct->tar, ct->subtarget, ct->matrix, CONSTRAINT_SPACE_WORLD, ct->space, con->flag, con->headtail);
2047                 
2048                 /* only execute target calculation if allowed */
2049 #ifdef WITH_PYTHON
2050                 if (G.f & G_SCRIPT_AUTOEXEC)
2051                         BPY_pyconstraint_target(data, ct);
2052 #endif
2053         }
2054         else if (ct)
2055                 unit_m4(ct->matrix);
2056 }
2057
2058 static void pycon_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *targets)
2059 {
2060 #ifndef WITH_PYTHON
2061         UNUSED_VARS(con, cob, targets);
2062         return;
2063 #else
2064         bPythonConstraint *data = con->data;
2065         
2066         /* only evaluate in python if we're allowed to do so */
2067         if ((G.f & G_SCRIPT_AUTOEXEC) == 0) return;
2068         
2069 /* currently removed, until I this can be re-implemented for multiple targets */
2070 #if 0
2071         /* Firstly, run the 'driver' function which has direct access to the objects involved 
2072          * Technically, this is potentially dangerous as users may abuse this and cause dependency-problems,
2073          * but it also allows certain 'clever' rigging hacks to work.
2074          */
2075         BPY_pyconstraint_driver(data, cob, targets);
2076 #endif
2077         
2078         /* Now, run the actual 'constraint' function, which should only access the matrices */
2079         BPY_pyconstraint_exec(data, cob, targets);
2080 #endif /* WITH_PYTHON */
2081 }
2082
2083 static bConstraintTypeInfo CTI_PYTHON = {
2084         CONSTRAINT_TYPE_PYTHON, /* type */
2085         sizeof(bPythonConstraint), /* size */
2086         "Script", /* name */
2087         "bPythonConstraint", /* struct name */
2088         pycon_free, /* free data */
2089         pycon_id_looper, /* id looper */
2090         pycon_copy, /* copy data */
2091         pycon_new_data, /* new data */
2092         pycon_get_tars, /* get constraint targets */
2093         NULL, /* flush constraint targets */
2094         pycon_get_tarmat, /* get target matrix */
2095         pycon_evaluate /* evaluate */
2096 };
2097
2098 /* -------- Action Constraint ----------- */
2099
2100 static void actcon_new_data(void *cdata)
2101 {
2102         bActionConstraint *data = (bActionConstraint *)cdata;
2103         
2104         /* set type to 20 (Loc X), as 0 is Rot X for backwards compatibility */
2105         data->type = 20;
2106 }
2107
2108 static void actcon_id_looper(bConstraint *con, ConstraintIDFunc func, void *userdata)
2109 {
2110         bActionConstraint *data = con->data;
2111         
2112         /* target */
2113         func(con, (ID **)&data->tar, false, userdata);
2114         
2115         /* action */
2116         func(con, (ID **)&data->act, true, userdata);
2117 }
2118
2119 static int actcon_get_tars(bConstraint *con, ListBase *list)
2120 {
2121         if (con && list) {
2122                 bActionConstraint *data = con->data;
2123                 bConstraintTarget *ct;
2124                 
2125                 /* standard target-getting macro for single-target constraints */
2126                 SINGLETARGET_GET_TARS(con, data->tar, data->subtarget, ct, list);
2127                 
2128                 return 1;
2129         }
2130         
2131         return 0;
2132 }
2133
2134 static void actcon_flush_tars(bConstraint *con, ListBase *list, bool no_copy)
2135 {
2136         if (con && list) {
2137                 bActionConstraint *data = con->data;
2138                 bConstraintTarget *ct = list->first;
2139                 
2140                 /* the following macro is used for all standard single-target constraints */
2141                 SINGLETARGET_FLUSH_TARS(con, data->tar, data->subtarget, ct, list, no_copy);
2142         }
2143 }
2144
2145 static void actcon_get_tarmat(struct EvaluationContext *UNUSED(eval_ctx), bConstraint *con, bConstraintOb *cob, bConstraintTarget *ct, float UNUSED(ctime))
2146 {
2147         bActionConstraint *data = con->data;
2148         
2149         if (VALID_CONS_TARGET(ct)) {
2150                 float tempmat[4][4], vec[3];
2151                 float s, t;
2152                 short axis;
2153                 
2154                 /* initialize return matrix */
2155                 unit_m4(ct->matrix);
2156                 
2157                 /* get the transform matrix of the target */
2158                 constraint_target_to_mat4(ct->tar, ct->subtarget, tempmat, CONSTRAINT_SPACE_WORLD, ct->space, con->flag, con->headtail);
2159                 
2160                 /* determine where in transform range target is */
2161                 /* data->type is mapped as follows for backwards compatibility:
2162                  *      00,01,02        - rotation (it used to be like this)
2163                  *  10,11,12    - scaling
2164                  *      20,21,22        - location
2165                  */
2166                 if (data->type < 10) {
2167                         /* extract rotation (is in whatever space target should be in) */
2168                         mat4_to_eul(vec, tempmat);
2169                         mul_v3_fl(vec, RAD2DEGF(1.0f)); /* rad -> deg */
2170                         axis = data->type;
2171                 }
2172                 else if (data->type < 20) {
2173                         /* extract scaling (is in whatever space target should be in) */
2174                         mat4_to_size(vec, tempmat);
2175                         axis = data->type - 10;
2176                 }
2177                 else {
2178                         /* extract location */
2179                         copy_v3_v3(vec, tempmat[3]);
2180                         axis = data->type - 20;
2181                 }
2182                 
2183                 BLI_assert((unsigned int)axis < 3);
2184
2185                 /* Target defines the animation */
2186                 s = (vec[axis] - data->min) / (data->max - data->min);
2187                 CLAMP(s, 0, 1);
2188                 t = (s * (data->end - data->start)) + data->start;
2189                 
2190                 if (G.debug & G_DEBUG)
2191                         printf("do Action Constraint %s - Ob %s Pchan %s\n", con->name, cob->ob->id.name + 2, (cob->pchan) ? cob->pchan->name : NULL);
2192                 
2193                 /* Get the appropriate information from the action */
2194                 if (cob->type == CONSTRAINT_OBTYPE_OBJECT || (data->flag & ACTCON_BONE_USE_OBJECT_ACTION)) {
2195                         Object workob;
2196                         
2197                         /* evaluate using workob */
2198                         /* FIXME: we don't have any consistent standards on limiting effects on object... */
2199                         what_does_obaction(cob->ob, &workob, NULL, data->act, NULL, t);
2200                         BKE_object_to_mat4(&workob, ct->matrix);
2201                 }
2202                 else if (cob->type == CONSTRAINT_OBTYPE_BONE) {
2203                         Object workob;
2204                         bPose pose = {{0}};
2205                         bPoseChannel *pchan, *tchan;
2206
2207                         /* make a copy of the bone of interest in the temp pose before evaluating action, so that it can get set 
2208                          *      - we need to manually copy over a few settings, including rotation order, otherwise this fails
2209                          */
2210                         pchan = cob->pchan;
2211                         
2212                         tchan = BKE_pose_channel_verify(&pose, pchan->name);
2213                         tchan->rotmode = pchan->rotmode;
2214                         
2215                         /* evaluate action using workob (it will only set the PoseChannel in question) */
2216                         what_does_obaction(cob->ob, &workob, &pose, data->act, pchan->name, t);
2217                         
2218                         /* convert animation to matrices for use here */
2219                         BKE_pchan_calc_mat(tchan);
2220                         copy_m4_m4(ct->matrix, tchan->chan_mat);
2221                         
2222                         /* Clean up */
2223                         BKE_pose_free_data(&pose);
2224                 }
2225                 else {
2226                         /* behavior undefined... */
2227                         puts("Error: unknown owner type for Action Constraint");
2228                 }
2229         }
2230 }
2231
2232 static void actcon_evaluate(bConstraint *UNUSED(con), bConstraintOb *cob, ListBase *targets)
2233 {
2234         bConstraintTarget *ct = targets->first;
2235         
2236         if (VALID_CONS_TARGET(ct)) {
2237                 float temp[4][4];
2238                 
2239                 /* Nice and simple... we just need to multiply the matrices, as the get_target_matrix
2240                  * function has already taken care of everything else.
2241                  */
2242                 copy_m4_m4(temp, cob->matrix);
2243                 mul_m4_m4m4(cob->matrix, temp, ct->matrix);
2244         }
2245 }
2246
2247 static bConstraintTypeInfo CTI_ACTION = {
2248         CONSTRAINT_TYPE_ACTION, /* type */
2249         sizeof(bActionConstraint), /* size */
2250         "Action", /* name */
2251         "bActionConstraint", /* struct name */
2252         NULL, /* free data */
2253         actcon_id_looper, /* id looper */
2254         NULL, /* copy data */
2255         actcon_new_data, /* new data */
2256         actcon_get_tars, /* get constraint targets */
2257         actcon_flush_tars, /* flush constraint targets */
2258         actcon_get_tarmat, /* get target matrix */
2259         actcon_evaluate /* evaluate */
2260 };
2261
2262 /* --------- Locked Track ---------- */
2263
2264 static void locktrack_new_data(void *cdata)
2265 {
2266         bLockTrackConstraint *data = (bLockTrackConstraint *)cdata;
2267         
2268         data->trackflag = TRACK_Y;
2269         data->lockflag = LOCK_Z;
2270 }       
2271
2272 static void locktrack_id_looper(bConstraint *con, ConstraintIDFunc func, void *userdata)
2273 {
2274         bLockTrackConstraint *data = con->data;
2275         
2276         /* target only */
2277         func(con, (ID **)&data->tar, false, userdata);
2278 }
2279
2280 static int locktrack_get_tars(bConstraint *con, ListBase *list)
2281 {
2282         if (con && list) {
2283                 bLockTrackConstraint *data = con->data;
2284                 bConstraintTarget *ct;
2285                 
2286                 /* the following macro is used for all standard single-target constraints */
2287                 SINGLETARGET_GET_TARS(con, data->tar, data->subtarget, ct, list);
2288                 
2289                 return 1;
2290         }
2291         
2292         return 0;
2293 }
2294
2295 static void locktrack_flush_tars(bConstraint *con, ListBase *list, bool no_copy)
2296 {
2297         if (con && list) {
2298                 bLockTrackConstraint *data = con->data;
2299                 bConstraintTarget *ct = list->first;
2300                 
2301                 /* the following macro is used for all standard single-target constraints */
2302                 SINGLETARGET_FLUSH_TARS(con, data->tar, data->subtarget, ct, list, no_copy);
2303         }
2304 }
2305
2306 static void locktrack_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *targets)
2307 {
2308         bLockTrackConstraint *data = con->data;
2309         bConstraintTarget *ct = targets->first;
2310         
2311         if (VALID_CONS_TARGET(ct)) {
2312                 float vec[3], vec2[3];
2313                 float totmat[3][3];
2314                 float tmpmat[3][3];
2315                 float invmat[3][3];
2316                 float mdet;
2317                 
2318                 /* Vector object -> target */
2319                 sub_v3_v3v3(vec, ct->matrix[3], cob->matrix[3]);
2320                 switch (data->lockflag) {
2321                         case LOCK_X: /* LOCK X */
2322                         {
2323                                 switch (data->trackflag) {
2324                                         case TRACK_Y: /* LOCK X TRACK Y */
2325                                         {
2326                                                 /* Projection of Vector on the plane */
2327                                                 project_v3_v3v3(vec2, vec, cob->matrix[0]);
2328                                                 sub_v3_v3v3(totmat[1], vec, vec2);
2329                                                 normalize_v3(totmat[1]);
2330                                         
2331                                                 /* the x axis is fixed */
2332                                                 normalize_v3_v3(totmat[0], cob->matrix[0]);
2333                                         
2334                                                 /* the z axis gets mapped onto a third orthogonal vector */
2335                                                 cross_v3_v3v3(totmat[2], totmat[0], totmat[1]);
2336                                                 break;
2337                                         }
2338                                         case TRACK_Z: /* LOCK X TRACK Z */
2339                                         {
2340                                                 /* Projection of Vector on the plane */
2341                                                 project_v3_v3v3(vec2, vec, cob->matrix[0]);
2342                                                 sub_v3_v3v3(totmat[2], vec, vec2);
2343                                                 normalize_v3(totmat[2]);
2344                                         
2345                                                 /* the x axis is fixed */
2346                                                 normalize_v3_v3(totmat[0], cob->matrix[0]);
2347                                         
2348                                                 /* the z axis gets mapped onto a third orthogonal vector */
2349                                                 cross_v3_v3v3(totmat[1], totmat[2], totmat[0]);
2350                                                 break;
2351                                         }
2352                                         case TRACK_nY: /* LOCK X TRACK -Y */
2353                                         {
2354                                                 /* Projection of Vector on the plane */
2355                                                 project_v3_v3v3(vec2, vec, cob->matrix[0]);
2356                                                 sub_v3_v3v3(totmat[1], vec, vec2);
2357                                                 normalize_v3(totmat[1]);
2358                                                 negate_v3(totmat[1]);
2359                                         
2360                                                 /* the x axis is fixed */
2361                                                 normalize_v3_v3(totmat[0], cob->matrix[0]);
2362                                         
2363                                                 /* the z axis gets mapped onto a third orthogonal vector */
2364                                                 cross_v3_v3v3(totmat[2], totmat[0], totmat[1]);
2365                                                 break;
2366                                         }
2367                                         case TRACK_nZ: /* LOCK X TRACK -Z */
2368                                         {
2369                                                 /* Projection of Vector on the plane */
2370                                                 project_v3_v3v3(vec2, vec, cob->matrix[0]);
2371                                                 sub_v3_v3v3(totmat[2], vec, vec2);
2372                                                 normalize_v3(totmat[2]);
2373                                                 negate_v3(totmat[2]);
2374                                                 
2375                                                 /* the x axis is fixed */
2376                                                 normalize_v3_v3(totmat[0], cob->matrix[0]);
2377                                                 
2378                                                 /* the z axis gets mapped onto a third orthogonal vector */
2379                                                 cross_v3_v3v3(totmat[1], totmat[2], totmat[0]);
2380                                                 break;
2381                                         }
2382                                         default:
2383                                         {
2384                                                 unit_m3(totmat);
2385                                                 break;
2386                                         }
2387                                 }
2388                                 break;
2389                         }
2390                         case LOCK_Y: /* LOCK Y */
2391                         {
2392                                 switch (data->trackflag) {
2393                                         case TRACK_X: /* LOCK Y TRACK X */
2394                                         {
2395                                                 /* Projection of Vector on the plane */
2396                                                 project_v3_v3v3(vec2, vec, cob->matrix[1]);
2397                                                 sub_v3_v3v3(totmat[0], vec, vec2);
2398                                                 normalize_v3(totmat[0]);
2399                                         
2400                                                 /* the y axis is fixed */
2401                                                 normalize_v3_v3(totmat[1], cob->matrix[1]);
2402
2403                                                 /* the z axis gets mapped onto a third orthogonal vector */
2404                                                 cross_v3_v3v3(totmat[2], totmat[0], totmat[1]);
2405                                                 break;
2406                                         }
2407                                         case TRACK_Z: /* LOCK Y TRACK Z */
2408                                         {
2409                                                 /* Projection of Vector on the plane */
2410                                                 project_v3_v3v3(vec2, vec, cob->matrix[1]);
2411                                                 sub_v3_v3v3(totmat[2], vec, vec2);
2412                                                 normalize_v3(totmat[2]);
2413                                         
2414                                                 /* the y axis is fixed */
2415                                                 normalize_v3_v3(totmat[1], cob->matrix[1]);
2416                                         
2417                                                 /* the z axis gets mapped onto a third orthogonal vector */
2418                                                 cross_v3_v3v3(totmat[0], totmat[1], totmat[2]);
2419                                                 break;
2420                                         }
2421                                         case TRACK_nX: /* LOCK Y TRACK -X */
2422                                         {
2423                                                 /* Projection of Vector on the plane */
2424                                                 project_v3_v3v3(vec2, vec, cob->matrix[1]);
2425                                                 sub_v3_v3v3(totmat[0], vec, vec2);
2426                                                 normalize_v3(totmat[0]);
2427                                                 negate_v3(totmat[0]);
2428                                         
2429                                                 /* the y axis is fixed */
2430                                                 normalize_v3_v3(totmat[1], cob->matrix[1]);
2431                                         
2432                                                 /* the z axis gets mapped onto a third orthogonal vector */
2433                                                 cross_v3_v3v3(totmat[2], totmat[0], totmat[1]);
2434                                                 break;
2435                                         }
2436                                         case TRACK_nZ: /* LOCK Y TRACK -Z */
2437                                         {
2438                                                 /* Projection of Vector on the plane */
2439                                                 project_v3_v3v3(vec2, vec, cob->matrix[1]);
2440                                                 sub_v3_v3v3(totmat[2], vec, vec2);
2441                                                 normalize_v3(totmat[2]);
2442                                                 negate_v3(totmat[2]);
2443                                         
2444                                                 /* the y axis is fixed */
2445                                                 normalize_v3_v3(totmat[1], cob->matrix[1]);
2446                                         
2447                                                 /* the z axis gets mapped onto a third orthogonal vector */
2448                                                 cross_v3_v3v3(totmat[0], totmat[1], totmat[2]);
2449                                                 break;
2450                                         }
2451                                         default:
2452                                         {
2453                                                 unit_m3(totmat);
2454                                                 break;
2455                                         }
2456                                 }
2457                                 break;
2458                         }
2459                         case LOCK_Z: /* LOCK Z */
2460                         {
2461                                 switch (data->trackflag) {
2462                                         case TRACK_X: /* LOCK Z TRACK X */
2463                                         {
2464                                                 /* Projection of Vector on the plane */
2465                                                 project_v3_v3v3(vec2, vec, cob->matrix[2]);
2466                                                 sub_v3_v3v3(totmat[0], vec, vec2);
2467                                                 normalize_v3(totmat[0]);
2468                                         
2469                                                 /* the z axis is fixed */
2470                                                 normalize_v3_v3(totmat[2], cob->matrix[2]);
2471                                         
2472                                                 /* the x axis gets mapped onto a third orthogonal vector */
2473                                                 cross_v3_v3v3(totmat[1], totmat[2], totmat[0]);
2474                                                 break;
2475                                         }
2476                                         case TRACK_Y: /* LOCK Z TRACK Y */
2477                                         {
2478                                                 /* Projection of Vector on the plane */
2479                                                 project_v3_v3v3(vec2, vec, cob->matrix[2]);
2480                                                 sub_v3_v3v3(totmat[1], vec, vec2);
2481                                                 normalize_v3(totmat[1]);
2482                                         
2483                                                 /* the z axis is fixed */
2484                                                 normalize_v3_v3(totmat[2], cob->matrix[2]);
2485                                                 
2486                                                 /* the x axis gets mapped onto a third orthogonal vector */
2487                                                 cross_v3_v3v3(totmat[0], totmat[1], totmat[2]);
2488                                                 break;
2489                                         }
2490                                         case TRACK_nX: /* LOCK Z TRACK -X */
2491                                         {
2492                                                 /* Projection of Vector on the plane */
2493                                                 project_v3_v3v3(vec2, vec, cob->matrix[2]);
2494                                                 sub_v3_v3v3(totmat[0], vec, vec2);
2495                                                 normalize_v3(totmat[0]);
2496                                                 negate_v3(totmat[0]);
2497                                         
2498                                                 /* the z axis is fixed */
2499                                                 normalize_v3_v3(totmat[2], cob->matrix[2]);
2500                                         
2501                                                 /* the x axis gets mapped onto a third orthogonal vector */
2502                                                 cross_v3_v3v3(totmat[1], totmat[2], totmat[0]);
2503                                                 break;
2504                                         }
2505                                         case TRACK_nY: /* LOCK Z TRACK -Y */
2506                                         {
2507                                                 /* Projection of Vector on the plane */
2508                                                 project_v3_v3v3(vec2, vec, cob->matrix[2]);
2509                                                 sub_v3_v3v3(totmat[1], vec, vec2);
2510                                                 normalize_v3(totmat[1]);
2511                                                 negate_v3(totmat[1]);
2512                                         
2513                                                 /* the z axis is fixed */
2514                                                 normalize_v3_v3(totmat[2], cob->matrix[2]);
2515                                                 
2516                                                 /* the x axis gets mapped onto a third orthogonal vector */
2517                                                 cross_v3_v3v3(totmat[0], totmat[1], totmat[2]);
2518                                                 break;
2519                                         }
2520                                         default:
2521                                         {
2522                                                 unit_m3(totmat);
2523                                                 break;
2524                                         }
2525                                 }
2526                                 break;
2527                         }
2528                         default:
2529                         {
2530                                 unit_m3(totmat);
2531                                 break;
2532                         }
2533                 }
2534                 /* Block to keep matrix heading */
2535                 copy_m3_m4(tmpmat, cob->matrix);
2536                 normalize_m3(tmpmat);
2537                 invert_m3_m3(invmat, tmpmat);
2538                 mul_m3_m3m3(tmpmat, totmat, invmat);
2539                 totmat[0][0] = tmpmat[0][0]; totmat[0][1] = tmpmat[0][1]; totmat[0][2] = tmpmat[0][2];
2540                 totmat[1][0] = tmpmat[1][0]; totmat[1][1] = tmpmat[1][1]; totmat[1][2] = tmpmat[1][2];
2541                 totmat[2][0] = tmpmat[2][0]; totmat[2][1] = tmpmat[2][1]; totmat[2][2] = tmpmat[2][2];
2542                 
2543                 mdet = determinant_m3(totmat[0][0], totmat[0][1], totmat[0][2],
2544                                       totmat[1][0], totmat[1][1], totmat[1][2],
2545                                       totmat[2][0], totmat[2][1], totmat[2][2]);
2546                 if (mdet == 0) {
2547                         unit_m3(totmat);
2548                 }
2549                 
2550                 /* apply out transformaton to the object */
2551                 mul_m4_m3m4(cob->matrix, totmat, cob->matrix);
2552         }
2553 }
2554
2555 static bConstraintTypeInfo CTI_LOCKTRACK = {
2556         CONSTRAINT_TYPE_LOCKTRACK, /* type */
2557         sizeof(bLockTrackConstraint), /* size */
2558         "Locked Track", /* name */
2559         "bLockTrackConstraint", /* struct name */
2560         NULL, /* free data */
2561         locktrack_id_looper, /* id looper */
2562         NULL, /* copy data */
2563         locktrack_new_data, /* new data */
2564         locktrack_get_tars, /* get constraint targets */
2565         locktrack_flush_tars, /* flush constraint targets */
2566         default_get_tarmat, /* get target matrix */
2567         locktrack_evaluate /* evaluate */
2568 };
2569
2570 /* ---------- Limit Distance Constraint ----------- */
2571
2572 static void distlimit_new_data(void *cdata)
2573 {
2574         bDistLimitConstraint *data = (bDistLimitConstraint *)cdata;
2575         
2576         data->dist = 0.0f;
2577 }
2578
2579 static void distlimit_id_looper(bConstraint *con, ConstraintIDFunc func, void *userdata)
2580 {
2581         bDistLimitConstraint *data = con->data;
2582         
2583         /* target only */
2584         func(con, (ID **)&data->tar, false, userdata);
2585 }
2586
2587 static int distlimit_get_tars(bConstraint *con, ListBase *list)
2588 {
2589         if (con && list) {
2590                 bDistLimitConstraint *data = con->data;
2591                 bConstraintTarget *ct;
2592                 
2593                 /* standard target-getting macro for single-target constraints */
2594                 SINGLETARGET_GET_TARS(con, data->tar, data->subtarget, ct, list);
2595                 
2596                 return 1;
2597         }
2598         
2599         return 0;
2600 }
2601
2602 static void distlimit_flush_tars(bConstraint *con, ListBase *list, bool no_copy)
2603 {
2604         if (con && list) {
2605                 bDistLimitConstraint *data = con->data;
2606                 bConstraintTarget *ct = list->first;
2607                 
2608                 /* the following macro is used for all standard single-target constraints */
2609                 SINGLETARGET_FLUSH_TARS(con, data->tar, data->subtarget, ct, list, no_copy);
2610         }
2611 }
2612
2613 static void distlimit_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *targets)
2614 {
2615         bDistLimitConstraint *data = con->data;
2616         bConstraintTarget *ct = targets->first;
2617         
2618         /* only evaluate if there is a target */
2619         if (VALID_CONS_TARGET(ct)) {
2620                 float dvec[3], dist, sfac = 1.0f;
2621                 short clamp_surf = 0;
2622                 
2623                 /* calculate our current distance from the target */
2624                 dist = len_v3v3(cob->matrix[3], ct->matrix[3]);
2625                 
2626                 /* set distance (flag is only set when user demands it) */
2627                 if (data->dist == 0)
2628                         data->dist = dist;
2629                 
2630                 /* check if we're which way to clamp from, and calculate interpolation factor (if needed) */
2631                 if (data->mode == LIMITDIST_OUTSIDE) {
2632                         /* if inside, then move to surface */
2633                         if (dist <= data->dist) {
2634                                 clamp_surf = 1;
2635                                 if (dist != 0.0f) sfac = data->dist / dist;
2636                         }
2637                         /* if soft-distance is enabled, start fading once owner is dist+softdist from the target */
2638                         else if (data->flag & LIMITDIST_USESOFT) {
2639                                 if (dist <= (data->dist + data->soft)) {
2640                                         
2641                                 }
2642                         }
2643                 }
2644                 else if (data->mode == LIMITDIST_INSIDE) {
2645                         /* if outside, then move to surface */
2646                         if (dist >= data->dist) {
2647                                 clamp_surf = 1;
2648                                 if (dist != 0.0f) sfac = data->dist / dist;
2649                         }
2650                         /* if soft-distance is enabled, start fading once owner is dist-soft from the target */
2651                         else if (data->flag & LIMITDIST_USESOFT) {
2652                                 /* FIXME: there's a problem with "jumping" when this kicks in */
2653                                 if (dist >= (data->dist - data->soft)) {
2654                                         sfac = (float)(data->soft * (1.0f - expf(-(dist - data->dist) / data->soft)) + data->dist);
2655                                         if (dist != 0.0f) sfac /= dist;
2656                                         
2657                                         clamp_surf = 1;
2658                                 }
2659                         }
2660                 }
2661                 else {
2662                         if (IS_EQF(dist, data->dist) == 0) {
2663                                 clamp_surf = 1;
2664                                 if (dist != 0.0f) sfac = data->dist / dist;
2665                         }
2666                 }
2667                 
2668                 /* clamp to 'surface' (i.e. move owner so that dist == data->dist) */
2669                 if (clamp_surf) {
2670                         /* simply interpolate along line formed by target -> owner */
2671                         interp_v3_v3v3(dvec, ct->matrix[3], cob->matrix[3], sfac);
2672                         
2673                         /* copy new vector onto owner */
2674                         copy_v3_v3(cob->matrix[3], dvec);
2675                 }
2676         }
2677 }
2678
2679 static bConstraintTypeInfo CTI_DISTLIMIT = {
2680         CONSTRAINT_TYPE_DISTLIMIT, /* type */
2681         sizeof(bDistLimitConstraint), /* size */
2682         "Limit Distance", /* name */
2683         "bDistLimitConstraint", /* struct name */
2684         NULL, /* free data */
2685         distlimit_id_looper, /* id looper */
2686         NULL, /* copy data */
2687         distlimit_new_data, /* new data */
2688         distlimit_get_tars, /* get constraint targets */
2689         distlimit_flush_tars, /* flush constraint targets */
2690         default_get_tarmat, /* get a target matrix */
2691         distlimit_evaluate /* evaluate */
2692 };
2693
2694 /* ---------- Stretch To ------------ */
2695
2696 static void stretchto_new_data(void *cdata)
2697 {
2698         bStretchToConstraint *data = (bStretchToConstraint *)cdata;
2699         
2700         data->volmode = 0;
2701         data->plane = 0;
2702         data->orglength = 0.0; 
2703         data->bulge = 1.0;
2704         data->bulge_max = 1.0f;
2705         data->bulge_min = 1.0f;
2706 }
2707
2708 static void stretchto_id_looper(bConstraint *con, ConstraintIDFunc func, void *userdata)
2709 {
2710         bStretchToConstraint *data = con->data;
2711         
2712         /* target only */
2713         func(con, (ID **)&data->tar, false, userdata);
2714 }
2715
2716 static int stretchto_get_tars(bConstraint *con, ListBase *list)
2717 {
2718         if (con && list) {
2719                 bStretchToConstraint *data = con->data;
2720                 bConstraintTarget *ct;
2721                 
2722                 /* standard target-getting macro for single-target constraints */
2723                 SINGLETARGET_GET_TARS(con, data->tar, data->subtarget, ct, list);
2724                 
2725                 return 1;
2726         }
2727         
2728         return 0;
2729 }
2730
2731 static void stretchto_flush_tars(bConstraint *con, ListBase *list, bool no_copy)
2732 {
2733         if (con && list) {
2734                 bStretchToConstraint *data = con->data;
2735                 bConstraintTarget *ct = list->first;
2736                 
2737                 /* the following macro is used for all standard single-target constraints */
2738                 SINGLETARGET_FLUSH_TARS(con, data->tar, data->subtarget, ct, list, no_copy);
2739         }
2740 }
2741
2742 static void stretchto_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *targets)
2743 {
2744         bStretchToConstraint *data = con->data;
2745         bConstraintTarget *ct = targets->first;
2746         
2747         /* only evaluate if there is a target */
2748         if (VALID_CONS_TARGET(ct)) {
2749                 float size[3], scale[3], vec[3], xx[3], zz[3], orth[3];
2750                 float totmat[3][3];
2751                 float dist, bulge;
2752                 
2753                 /* store scaling before destroying obmat */
2754                 mat4_to_size(size, cob->matrix);
2755                 
2756                 /* store X orientation before destroying obmat */
2757                 normalize_v3_v3(xx, cob->matrix[0]);
2758                 
2759                 /* store Z orientation before destroying obmat */
2760                 normalize_v3_v3(zz, cob->matrix[2]);
2761                 
2762                 /* XXX That makes the constraint buggy with asymmetrically scaled objects, see #29940. */
2763 /*              sub_v3_v3v3(vec, cob->matrix[3], ct->matrix[3]);*/
2764 /*              vec[0] /= size[0];*/
2765 /*              vec[1] /= size[1];*/
2766 /*              vec[2] /= size[2];*/
2767                 
2768 /*              dist = normalize_v3(vec);*/
2769
2770                 dist = len_v3v3(cob->matrix[3], ct->matrix[3]);
2771                 /* Only Y constrained object axis scale should be used, to keep same length when scaling it. */
2772                 dist /= size[1];
2773                 
2774                 /* data->orglength==0 occurs on first run, and after 'R' button is clicked */
2775                 if (data->orglength == 0)
2776                         data->orglength = dist;
2777
2778                 scale[1] = dist / data->orglength;
2779                 
2780                 bulge = powf(data->orglength / dist, data->bulge);
2781                 
2782                 if (bulge > 1.0f) {
2783                         if (data->flag & STRETCHTOCON_USE_BULGE_MAX) {
2784                                 float bulge_max = max_ff(data->bulge_max, 1.0f);
2785                                 float hard = min_ff(bulge, bulge_max);
2786                                 
2787                                 float range = bulge_max - 1.0f;
2788                                 float scale_fac = (range > 0.0f) ? 1.0f / range : 0.0f;
2789                                 float soft = 1.0f + range * atanf((bulge - 1.0f) * scale_fac) / (float)M_PI_2;
2790                                 
2791                                 bulge = interpf(soft, hard, data->bulge_smooth);
2792                         }
2793                 }
2794                 if (bulge < 1.0f) {
2795                         if (data->flag & STRETCHTOCON_USE_BULGE_MIN) {
2796                                 float bulge_min = CLAMPIS(data->bulge_min, 0.0f, 1.0f);
2797                                 float hard = max_ff(bulge, bulge_min);
2798                                 
2799                                 float range = 1.0f - bulge_min;
2800                                 float scale_fac = (range > 0.0f) ? 1.0f / range : 0.0f;
2801                                 float soft = 1.0f - range * atanf((1.0f - bulge) * scale_fac) / (float)M_PI_2;
2802                                 
2803                                 bulge = interpf(soft, hard, data->bulge_smooth);
2804                         }
2805                 }
2806                 
2807                 switch (data->volmode) {
2808                         /* volume preserving scaling */
2809                         case VOLUME_XZ:
2810                                 scale[0] = sqrtf(bulge);
2811                                 scale[2] = scale[0];
2812                                 break;
2813                         case VOLUME_X:
2814                                 scale[0] = bulge;
2815                                 scale[2] = 1.0;
2816                                 break;
2817                         case VOLUME_Z:
2818                                 scale[0] = 1.0;
2819                                 scale[2] = bulge;
2820                                 break;
2821                         /* don't care for volume */
2822                         case NO_VOLUME:
2823                                 scale[0] = 1.0;
2824                                 scale[2] = 1.0;
2825                                 break;
2826                         default: /* should not happen, but in case*/
2827                                 return;
2828                 } /* switch (data->volmode) */
2829                 
2830                 /* Clear the object's rotation and scale */
2831                 cob->matrix[0][0] = size[0] * scale[0];
2832                 cob->matrix[0][1] = 0;
2833                 cob->matrix[0][2] = 0;
2834                 cob->matrix[1][0] = 0;
2835                 cob->matrix[1][1] = size[1] * scale[1];
2836                 cob->matrix[1][2] = 0;
2837                 cob->matrix[2][0] = 0;
2838                 cob->matrix[2][1] = 0;
2839                 cob->matrix[2][2] = size[2] * scale[2];
2840                 
2841                 sub_v3_v3v3(vec, cob->matrix[3], ct->matrix[3]);
2842                 normalize_v3(vec);
2843                 
2844                 /* new Y aligns  object target connection*/
2845                 negate_v3_v3(totmat[1], vec);
2846                 switch (data->plane) {
2847                         case PLANE_X:
2848                                 /* build new Z vector */
2849                                 /* othogonal to "new Y" "old X! plane */
2850                                 cross_v3_v3v3(orth, vec, xx);
2851                                 normalize_v3(orth);
2852                                 
2853                                 /* new Z*/
2854                                 copy_v3_v3(totmat[2], orth);
2855                                 
2856                                 /* we decided to keep X plane*/
2857                                 cross_v3_v3v3(xx, orth, vec);
2858                                 normalize_v3_v3(totmat[0], xx);
2859                                 break;
2860                         case PLANE_Z:
2861                                 /* build new X vector */
2862                                 /* othogonal to "new Y" "old Z! plane */
2863                                 cross_v3_v3v3(orth, vec, zz);
2864                                 normalize_v3(orth);
2865                                 
2866                                 /* new X */
2867                                 negate_v3_v3(totmat[0], orth);
2868                                 
2869                                 /* we decided to keep Z */
2870                                 cross_v3_v3v3(zz, orth, vec);
2871                                 normalize_v3_v3(totmat[2], zz);
2872                                 break;
2873                 } /* switch (data->plane) */
2874                 
2875                 mul_m4_m3m4(cob->matrix, totmat, cob->matrix);
2876         }
2877 }
2878
2879 static bConstraintTypeInfo CTI_STRETCHTO = {
2880         CONSTRAINT_TYPE_STRETCHTO, /* type */
2881         sizeof(bStretchToConstraint), /* size */
2882         "Stretch To", /* name */
2883         "bStretchToConstraint", /* struct name */
2884         NULL, /* free data */
2885         stretchto_id_looper, /* id looper */
2886         NULL, /* copy data */
2887         stretchto_new_data, /* new data */
2888         stretchto_get_tars, /* get constraint targets */
2889         stretchto_flush_tars, /* flush constraint targets */
2890         default_get_tarmat, /* get target matrix */
2891         stretchto_evaluate /* evaluate */
2892 };
2893
2894 /* ---------- Floor ------------ */
2895
2896 static void minmax_new_data(void *cdata)
2897 {
2898         bMinMaxConstraint *data = (bMinMaxConstraint *)cdata;
2899         
2900         data->minmaxflag = TRACK_Z;
2901         data->offset = 0.0f;
2902         zero_v3(data->cache);
2903         data->flag = 0;
2904 }
2905
2906 static void minmax_id_looper(bConstraint *con, ConstraintIDFunc func, void *userdata)
2907 {
2908         bMinMaxConstraint *data = con->data;
2909         
2910         /* target only */
2911         func(con, (ID **)&data->tar, false, userdata);
2912 }
2913
2914 static int minmax_get_tars(bConstraint *con, ListBase *list)
2915 {
2916         if (con && list) {
2917                 bMinMaxConstraint *data = con->data;
2918                 bConstraintTarget *ct;
2919                 
2920                 /* standard target-getting macro for single-target constraints */
2921                 SINGLETARGET_GET_TARS(con, data->tar, data->subtarget, ct, list);
2922                 
2923                 return 1;
2924         }
2925         
2926        &nb