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