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