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