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