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