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