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