style cleanup, brackets in else/if, some indentation.
[blender.git] / source / blender / editors / transform / transform_conversions.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): none yet.
24  *
25  * ***** END GPL LICENSE BLOCK *****
26  */
27
28 /** \file blender/editors/transform/transform_conversions.c
29  *  \ingroup edtransform
30  */
31
32
33 #ifndef WIN32
34 #include <unistd.h>
35 #else
36 #include <io.h>
37 #endif
38 #include <string.h>
39 #include <math.h>
40
41 #include "DNA_anim_types.h"
42 #include "DNA_armature_types.h"
43 #include "DNA_lattice_types.h"
44 #include "DNA_mesh_types.h"
45 #include "DNA_meta_types.h"
46 #include "DNA_node_types.h"
47 #include "DNA_screen_types.h"
48 #include "DNA_space_types.h"
49 #include "DNA_sequence_types.h"
50 #include "DNA_view3d_types.h"
51 #include "DNA_constraint_types.h"
52 #include "DNA_scene_types.h"
53 #include "DNA_meshdata_types.h"
54 #include "DNA_gpencil_types.h"
55 #include "DNA_movieclip_types.h"
56
57 #include "MEM_guardedalloc.h"
58
59 #include "BKE_DerivedMesh.h"
60 #include "BKE_action.h"
61 #include "BKE_armature.h"
62 #include "BKE_bmesh.h"
63 #include "BKE_constraint.h"
64 #include "BKE_context.h"
65 #include "BKE_curve.h"
66 #include "BKE_depsgraph.h"
67 #include "BKE_fcurve.h"
68 #include "BKE_global.h"
69 #include "BKE_gpencil.h"
70 #include "BKE_key.h"
71 #include "BKE_main.h"
72 #include "BKE_modifier.h"
73 #include "BKE_movieclip.h"
74 #include "BKE_nla.h"
75 #include "BKE_node.h"
76 #include "BKE_object.h"
77 #include "BKE_particle.h"
78 #include "BKE_pointcache.h"
79 #include "BKE_report.h"
80 #include "BKE_scene.h"
81 #include "BKE_sequencer.h"
82 #include "BKE_tessmesh.h"
83 #include "BKE_tracking.h"
84
85
86 #include "ED_anim_api.h"
87 #include "ED_armature.h"
88 #include "ED_particle.h"
89 #include "ED_image.h"
90 #include "ED_keyframing.h"
91 #include "ED_keyframes_edit.h"
92 #include "ED_object.h"
93 #include "ED_markers.h"
94 #include "ED_mesh.h"
95 #include "ED_node.h"
96 #include "ED_types.h"
97 #include "ED_uvedit.h"
98 #include "ED_clip.h"
99 #include "ED_util.h"  /* for crazyspace correction */
100
101 #include "WM_api.h"             /* for WM_event_add_notifier to deal with stabilization nodes */
102 #include "WM_types.h"
103
104 #include "UI_view2d.h"
105
106 #include "BLI_math.h"
107 #include "BLI_blenlib.h"
108 #include "BLI_array.h"
109 #include "BLI_utildefines.h"
110 #include "BLI_smallhash.h"
111
112 #include "RNA_access.h"
113
114 extern ListBase editelems;
115
116 #include "transform.h"
117 #include "bmesh.h"
118
119 #include "BLO_sys_types.h" // for intptr_t support
120
121 /* local function prototype - for Object/Bone Constraints */
122 static short constraints_list_needinv(TransInfo *t, ListBase *list);
123
124 /* ************************** Functions *************************** */
125
126 static void qsort_trans_data(TransInfo *t, TransData *head, TransData *tail, TransData *temp)
127 {
128         TransData *ihead = head;
129         TransData *itail = tail;
130         *temp = *head;
131
132         while (head < tail)
133         {
134                 if (t->flag & T_PROP_CONNECTED) {
135                         while ((tail->dist >= temp->dist) && (head < tail))
136                                 tail--;
137                 }
138                 else {
139                         while ((tail->rdist >= temp->rdist) && (head < tail))
140                                 tail--;
141                 }
142
143                 if (head != tail)
144                 {
145                         *head = *tail;
146                         head++;
147                 }
148
149                 if (t->flag & T_PROP_CONNECTED) {
150                         while ((head->dist <= temp->dist) && (head < tail))
151                                 head++;
152                 }
153                 else {
154                         while ((head->rdist <= temp->rdist) && (head < tail))
155                                 head++;
156                 }
157
158                 if (head != tail)
159                 {
160                         *tail = *head;
161                         tail--;
162                 }
163         }
164
165         *head = *temp;
166         if (ihead < head) {
167                 qsort_trans_data(t, ihead, head-1, temp);
168         }
169         if (itail > head) {
170                 qsort_trans_data(t, head+1, itail, temp);
171         }
172 }
173
174 void sort_trans_data_dist(TransInfo *t)
175 {
176         TransData temp;
177         TransData *start = t->data;
178         int i = 1;
179
180         while(i < t->total && start->flag & TD_SELECTED) {
181                 start++;
182                 i++;
183         }
184         qsort_trans_data(t, start, t->data + t->total - 1, &temp);
185 }
186
187 static void sort_trans_data(TransInfo *t)
188 {
189         TransData *sel, *unsel;
190         TransData temp;
191         unsel = t->data;
192         sel = t->data;
193         sel += t->total - 1;
194         while (sel > unsel) {
195                 while (unsel->flag & TD_SELECTED) {
196                         unsel++;
197                         if (unsel == sel) {
198                                 return;
199                         }
200                 }
201                 while (!(sel->flag & TD_SELECTED)) {
202                         sel--;
203                         if (unsel == sel) {
204                                 return;
205                         }
206                 }
207                 temp = *unsel;
208                 *unsel = *sel;
209                 *sel = temp;
210                 sel--;
211                 unsel++;
212         }
213 }
214
215 /* distance calculated from not-selected vertex to nearest selected vertex
216  * warning; this is loops inside loop, has minor N^2 issues, but by sorting list it is OK */
217 static void set_prop_dist(TransInfo *t, short with_dist)
218 {
219         TransData *tob;
220         int a;
221
222         for(a=0, tob= t->data; a<t->total; a++, tob++) {
223
224                 tob->rdist= 0.0f; // init, it was mallocced
225
226                 if((tob->flag & TD_SELECTED)==0) {
227                         TransData *td;
228                         int i;
229                         float dist, vec[3];
230
231                         tob->rdist = -1.0f; // signal for next loop
232
233                         for (i = 0, td= t->data; i < t->total; i++, td++) {
234                                 if(td->flag & TD_SELECTED) {
235                                         sub_v3_v3v3(vec, tob->center, td->center);
236                                         mul_m3_v3(tob->mtx, vec);
237                                         dist = normalize_v3(vec);
238                                         if (tob->rdist == -1.0f) {
239                                                 tob->rdist = dist;
240                                         }
241                                         else if (dist < tob->rdist) {
242                                                 tob->rdist = dist;
243                                         }
244                                 }
245                                 else break;     // by definition transdata has selected items in beginning
246                         }
247                         if (with_dist) {
248                                 tob->dist = tob->rdist;
249                         }
250                 }
251         }
252 }
253
254 /* ************************** CONVERSIONS ************************* */
255
256 /* ********************* texture space ********* */
257
258 static void createTransTexspace(TransInfo *t)
259 {
260         Scene *scene = t->scene;
261         TransData *td;
262         Object *ob;
263         ID *id;
264         short *texflag;
265
266         ob = OBACT;
267
268         if (ob == NULL) { // Shouldn't logically happen, but still...
269                 t->total = 0;
270                 return;
271         }
272
273         id = ob->data;
274         if(id == NULL || !ELEM3( GS(id->name), ID_ME, ID_CU, ID_MB )) {
275                 t->total = 0;
276                 return;
277         }
278
279         t->total = 1;
280         td= t->data= MEM_callocN(sizeof(TransData), "TransTexspace");
281         td->ext= t->ext= MEM_callocN(sizeof(TransDataExtension), "TransTexspace");
282
283         td->flag= TD_SELECTED;
284         copy_v3_v3(td->center, ob->obmat[3]);
285         td->ob = ob;
286
287         copy_m3_m4(td->mtx, ob->obmat);
288         copy_m3_m4(td->axismtx, ob->obmat);
289         normalize_m3(td->axismtx);
290         invert_m3_m3(td->smtx, td->mtx);
291
292         if (give_obdata_texspace(ob, &texflag, &td->loc, &td->ext->size, &td->ext->rot)) {
293                 ob->dtx |= OB_TEXSPACE;
294                 *texflag &= ~ME_AUTOSPACE;
295         }
296
297         copy_v3_v3(td->iloc, td->loc);
298         copy_v3_v3(td->ext->irot, td->ext->rot);
299         copy_v3_v3(td->ext->isize, td->ext->size);
300 }
301
302 /* ********************* edge (for crease) ***** */
303
304 static void createTransEdge(TransInfo *t)
305 {
306         BMEditMesh *em = BMEdit_FromObject(t->obedit);
307         TransData *td = NULL;
308         BMEdge *eed;
309         BMIter iter;
310         float mtx[3][3], smtx[3][3];
311         int count=0, countsel=0;
312         int propmode = t->flag & T_PROP_EDIT;
313
314         BM_ITER(eed, &iter, em->bm, BM_EDGES_OF_MESH, NULL) {
315                 if (!BM_elem_flag_test(eed, BM_ELEM_HIDDEN)) {
316                         if (BM_elem_flag_test(eed, BM_ELEM_SELECT)) countsel++;
317                         if (propmode) count++;
318                 }
319         }
320
321         if (countsel == 0)
322                 return;
323
324         if(propmode) {
325                 t->total = count;
326         }
327         else {
328                 t->total = countsel;
329         }
330
331         td= t->data= MEM_callocN(t->total * sizeof(TransData), "TransCrease");
332
333         copy_m3_m4(mtx, t->obedit->obmat);
334         invert_m3_m3(smtx, mtx);
335
336         BM_ITER(eed, &iter, em->bm, BM_EDGES_OF_MESH, NULL) {
337                 if(!BM_elem_flag_test(eed, BM_ELEM_HIDDEN) && (BM_elem_flag_test(eed, BM_ELEM_SELECT) || propmode)) { 
338                         float *bweight = CustomData_bmesh_get(&em->bm->edata, eed->head.data, CD_BWEIGHT);
339                         float *crease = CustomData_bmesh_get(&em->bm->edata, eed->head.data, CD_CREASE);
340                         
341                         /* need to set center for center calculations */
342                         add_v3_v3v3(td->center, eed->v1->co, eed->v2->co);
343                         mul_v3_fl(td->center, 0.5f);
344
345                         td->loc= NULL;
346                         if (BM_elem_flag_test(eed, BM_ELEM_SELECT))
347                                 td->flag= TD_SELECTED;
348                         else
349                                 td->flag= 0;
350
351
352                         copy_m3_m3(td->smtx, smtx);
353                         copy_m3_m3(td->mtx, mtx);
354
355                         td->ext = NULL;
356                         if (t->mode == TFM_BWEIGHT) {
357                                 td->val = bweight;
358                                 td->ival = bweight ? *bweight : 1.0f;
359                         }
360                         else {
361                                 td->val = crease;
362                                 td->ival = crease ? *crease : 0.0f;
363                         }
364
365                         td++;
366                 }
367         }
368 }
369
370 /* ********************* pose mode ************* */
371
372 static bKinematicConstraint *has_targetless_ik(bPoseChannel *pchan)
373 {
374         bConstraint *con= pchan->constraints.first;
375
376         for(;con; con= con->next) {
377                 if(con->type==CONSTRAINT_TYPE_KINEMATIC && (con->enforce!=0.0f)) {
378                         bKinematicConstraint *data= con->data;
379
380                         if(data->tar==NULL)
381                                 return data;
382                         if(data->tar->type==OB_ARMATURE && data->subtarget[0]==0)
383                                 return data;
384                 }
385         }
386         return NULL;
387 }
388
389 static short apply_targetless_ik(Object *ob)
390 {
391         bPoseChannel *pchan, *parchan, *chanlist[256];
392         bKinematicConstraint *data;
393         int segcount, apply= 0;
394
395         /* now we got a difficult situation... we have to find the
396          * target-less IK pchans, and apply transformation to the all
397          * pchans that were in the chain */
398
399         for (pchan=ob->pose->chanbase.first; pchan; pchan=pchan->next) {
400                 data= has_targetless_ik(pchan);
401                 if(data && (data->flag & CONSTRAINT_IK_AUTO)) {
402
403                         /* fill the array with the bones of the chain (armature.c does same, keep it synced) */
404                         segcount= 0;
405
406                         /* exclude tip from chain? */
407                         if(!(data->flag & CONSTRAINT_IK_TIP))
408                                 parchan= pchan->parent;
409                         else
410                                 parchan= pchan;
411
412                         /* Find the chain's root & count the segments needed */
413                         for (; parchan; parchan=parchan->parent) {
414                                 chanlist[segcount]= parchan;
415                                 segcount++;
416
417                                 if(segcount==data->rootbone || segcount>255) break; // 255 is weak
418                         }
419                         for(;segcount;segcount--) {
420                                 Bone *bone;
421                                 float rmat[4][4]/*, tmat[4][4], imat[4][4]*/;
422
423                                 /* pose_mat(b) = pose_mat(b-1) * offs_bone * channel * constraint * IK  */
424                                 /* we put in channel the entire result of rmat= (channel * constraint * IK) */
425                                 /* pose_mat(b) = pose_mat(b-1) * offs_bone * rmat  */
426                                 /* rmat = pose_mat(b) * inv( pose_mat(b-1) * offs_bone ) */
427
428                                 parchan= chanlist[segcount-1];
429                                 bone= parchan->bone;
430                                 bone->flag |= BONE_TRANSFORM;   /* ensures it gets an auto key inserted */
431
432         /* XXX Old code. Will remove it later. */
433 #if 0
434                                 if(parchan->parent) {
435                                         Bone *parbone= parchan->parent->bone;
436                                         float offs_bone[4][4];
437
438                                         /* offs_bone =  yoffs(b-1) + root(b) + bonemat(b) */
439                                         copy_m4_m3(offs_bone, bone->bone_mat);
440
441                                         /* The bone's root offset (is in the parent's coordinate system) */
442                                         copy_v3_v3(offs_bone[3], bone->head);
443
444                                         /* Get the length translation of parent (length along y axis) */
445                                         offs_bone[3][1]+= parbone->length;
446
447                                         /* pose_mat(b-1) * offs_bone */
448                                         if(parchan->bone->flag & BONE_HINGE) {
449                                                 /* the rotation of the parent restposition */
450                                                 copy_m4_m4(rmat, parbone->arm_mat);     /* rmat used as temp */
451
452                                                 /* the location of actual parent transform */
453                                                 copy_v3_v3(rmat[3], offs_bone[3]);
454                                                 offs_bone[3][0]= offs_bone[3][1]= offs_bone[3][2]= 0.0f;
455                                                 mul_m4_v3(parchan->parent->pose_mat, rmat[3]);
456
457                                                 mult_m4_m4m4(tmat, rmat, offs_bone);
458                                         }
459                                         else if(parchan->bone->flag & BONE_NO_SCALE) {
460                                                 mult_m4_m4m4(tmat, parchan->parent->pose_mat, offs_bone);
461                                                 normalize_m4(tmat);
462                                         }
463                                         else
464                                                 mult_m4_m4m4(tmat, parchan->parent->pose_mat, offs_bone);
465
466                                         invert_m4_m4(imat, tmat);
467                                 }
468                                 else {
469                                         copy_m4_m3(tmat, bone->bone_mat);
470
471                                         copy_v3_v3(tmat[3], bone->head);
472                                         invert_m4_m4(imat, tmat);
473                                 }
474                                 /* result matrix */
475                                 mult_m4_m4m4(rmat, imat, parchan->pose_mat);
476 #endif
477                                 armature_mat_pose_to_bone(parchan, parchan->pose_mat, rmat);
478
479                                 /* apply and decompose, doesn't work for constraints or non-uniform scale well */
480                                 {
481                                         float rmat3[3][3], qrmat[3][3], imat3[3][3], smat[3][3];
482                                         
483                                         copy_m3_m4(rmat3, rmat);
484                                         
485                                         /* rotation */
486                                                 /* [#22409] is partially caused by this, as slight numeric error introduced during 
487                                                  * the solving process leads to locked-axis values changing. However, we cannot modify
488                                                  * the values here, or else there are huge discreptancies between IK-solver (interactive)
489                                                  * and applied poses.
490                                                  */
491                                         if (parchan->rotmode > 0)
492                                                 mat3_to_eulO(parchan->eul, parchan->rotmode,rmat3);
493                                         else if (parchan->rotmode == ROT_MODE_AXISANGLE)
494                                                 mat3_to_axis_angle(parchan->rotAxis, &parchan->rotAngle,rmat3);
495                                         else
496                                                 mat3_to_quat(parchan->quat,rmat3);
497                                         
498                                         /* for size, remove rotation */
499                                         /* causes problems with some constraints (so apply only if needed) */
500                                         if (data->flag & CONSTRAINT_IK_STRETCH) {
501                                                 if (parchan->rotmode > 0)
502                                                         eulO_to_mat3( qrmat,parchan->eul, parchan->rotmode);
503                                                 else if (parchan->rotmode == ROT_MODE_AXISANGLE)
504                                                         axis_angle_to_mat3( qrmat,parchan->rotAxis, parchan->rotAngle);
505                                                 else
506                                                         quat_to_mat3( qrmat,parchan->quat);
507                                                 
508                                                 invert_m3_m3(imat3, qrmat);
509                                                 mul_m3_m3m3(smat, rmat3, imat3);
510                                                 mat3_to_size( parchan->size,smat);
511                                         }
512                                         
513                                         /* causes problems with some constraints (e.g. childof), so disable this */
514                                         /* as it is IK shouldn't affect location directly */
515                                         /* copy_v3_v3(parchan->loc, rmat[3]); */
516                                 }
517
518                         }
519
520                         apply= 1;
521                         data->flag &= ~CONSTRAINT_IK_AUTO;
522                 }
523         }
524
525         return apply;
526 }
527
528 static void add_pose_transdata(TransInfo *t, bPoseChannel *pchan, Object *ob, TransData *td)
529 {
530         Bone *bone= pchan->bone;
531         float pmat[3][3], omat[3][3];
532         float cmat[3][3], tmat[3][3];
533         float vec[3];
534
535         copy_v3_v3(vec, pchan->pose_mat[3]);
536         copy_v3_v3(td->center, vec);
537
538         td->ob = ob;
539         td->flag = TD_SELECTED;
540         if (bone->flag & BONE_HINGE_CHILD_TRANSFORM)
541         {
542                 td->flag |= TD_NOCENTER;
543         }
544
545         if (bone->flag & BONE_TRANSFORM_CHILD)
546         {
547                 td->flag |= TD_NOCENTER;
548                 td->flag |= TD_NO_LOC;
549         }
550
551         td->protectflag= pchan->protectflag;
552
553         td->loc = pchan->loc;
554         copy_v3_v3(td->iloc, pchan->loc);
555
556         td->ext->size= pchan->size;
557         copy_v3_v3(td->ext->isize, pchan->size);
558
559         if (pchan->rotmode > 0) {
560                 td->ext->rot= pchan->eul;
561                 td->ext->rotAxis= NULL;
562                 td->ext->rotAngle= NULL;
563                 td->ext->quat= NULL;
564                 
565                 copy_v3_v3(td->ext->irot, pchan->eul);
566         }
567         else if (pchan->rotmode == ROT_MODE_AXISANGLE) {
568                 td->ext->rot= NULL;
569                 td->ext->rotAxis= pchan->rotAxis;
570                 td->ext->rotAngle= &pchan->rotAngle;
571                 td->ext->quat= NULL;
572                 
573                 td->ext->irotAngle= pchan->rotAngle;
574                 copy_v3_v3(td->ext->irotAxis, pchan->rotAxis);
575         }
576         else {
577                 td->ext->rot= NULL;
578                 td->ext->rotAxis= NULL;
579                 td->ext->rotAngle= NULL;
580                 td->ext->quat= pchan->quat;
581                 
582                 copy_qt_qt(td->ext->iquat, pchan->quat);
583         }
584         td->ext->rotOrder= pchan->rotmode;
585
586
587         /* proper way to get parent transform + own transform + constraints transform */
588         copy_m3_m4(omat, ob->obmat);
589
590         /* New code, using "generic" pchan_to_pose_mat(). */
591         {
592                 float rotscale_mat[4][4], loc_mat[4][4];
593
594                 pchan_to_pose_mat(pchan, rotscale_mat, loc_mat);
595                 if (t->mode == TFM_TRANSLATION)
596                         copy_m3_m4(pmat, loc_mat);
597                 else
598                         copy_m3_m4(pmat, rotscale_mat);
599
600                 if (constraints_list_needinv(t, &pchan->constraints)) {
601                         copy_m3_m4(tmat, pchan->constinv);
602                         invert_m3_m3(cmat, tmat);
603                         mul_serie_m3(td->mtx, pmat, omat, cmat, NULL,NULL,NULL,NULL,NULL);
604                 }
605                 else
606                         mul_serie_m3(td->mtx, pmat, omat, NULL, NULL,NULL,NULL,NULL,NULL);
607         }
608
609         /* XXX Old code. Will remove it later. */
610 #if 0
611         if (ELEM(t->mode, TFM_TRANSLATION, TFM_RESIZE) && (pchan->bone->flag & BONE_NO_LOCAL_LOCATION))
612                 unit_m3(bmat);
613         else
614                 copy_m3_m3(bmat, pchan->bone->bone_mat);
615
616         if (pchan->parent) {
617                 if(pchan->bone->flag & BONE_HINGE) {
618                         copy_m3_m4(pmat, pchan->parent->bone->arm_mat);
619                         if(!(pchan->bone->flag & BONE_NO_SCALE)) {
620                                 float tsize[3], tsmat[3][3];
621                                 mat4_to_size(tsize, pchan->parent->pose_mat);
622                                 size_to_mat3(tsmat, tsize);
623                                 mul_m3_m3m3(pmat, tsmat, pmat);
624                         }
625                 }
626                 else {
627                         copy_m3_m4(pmat, pchan->parent->pose_mat);
628                         if(pchan->bone->flag & BONE_NO_SCALE)
629                                 normalize_m3(pmat);
630                 }
631
632                 if (constraints_list_needinv(t, &pchan->constraints)) {
633                         copy_m3_m4(tmat, pchan->constinv);
634                         invert_m3_m3(cmat, tmat);
635                         mul_serie_m3(td->mtx, bmat, pmat, omat, cmat, NULL,NULL,NULL,NULL);
636                 }
637                 else
638                         mul_serie_m3(td->mtx, bmat, pmat, omat, NULL,NULL,NULL,NULL,NULL);
639         }
640         else {
641                 if (constraints_list_needinv(t, &pchan->constraints)) {
642                         copy_m3_m4(tmat, pchan->constinv);
643                         invert_m3_m3(cmat, tmat);
644                         mul_serie_m3(td->mtx, bmat, omat, cmat, NULL,NULL,NULL,NULL,NULL);
645                 }
646                 else
647                         mul_m3_m3m3(td->mtx, omat, bmat);
648         }
649 # endif
650
651         invert_m3_m3(td->smtx, td->mtx);
652
653         /* exceptional case: rotate the pose bone which also applies transformation
654          * when a parentless bone has BONE_NO_LOCAL_LOCATION [] */
655         if (!ELEM(t->mode, TFM_TRANSLATION, TFM_RESIZE) && (pchan->bone->flag & BONE_NO_LOCAL_LOCATION)) {
656                 if(pchan->parent) {
657                         /* same as td->smtx but without pchan->bone->bone_mat */
658                         td->flag |= TD_PBONE_LOCAL_MTX_C;
659                         mul_m3_m3m3(td->ext->l_smtx, pchan->bone->bone_mat, td->smtx);
660                 }
661                 else {
662                         td->flag |= TD_PBONE_LOCAL_MTX_P;
663                 }
664         }
665         
666         /* for axismat we use bone's own transform */
667         copy_m3_m4(pmat, pchan->pose_mat);
668         mul_m3_m3m3(td->axismtx, omat, pmat);
669         normalize_m3(td->axismtx);
670
671         if (t->mode==TFM_BONESIZE) {
672                 bArmature *arm= t->poseobj->data;
673
674                 if(arm->drawtype==ARM_ENVELOPE) {
675                         td->loc= NULL;
676                         td->val= &bone->dist;
677                         td->ival= bone->dist;
678                 }
679                 else {
680                         // abusive storage of scale in the loc pointer :)
681                         td->loc= &bone->xwidth;
682                         copy_v3_v3(td->iloc, td->loc);
683                         td->val= NULL;
684                 }
685         }
686
687         /* in this case we can do target-less IK grabbing */
688         if (t->mode==TFM_TRANSLATION) {
689                 bKinematicConstraint *data= has_targetless_ik(pchan);
690                 if(data) {
691                         if(data->flag & CONSTRAINT_IK_TIP) {
692                                 copy_v3_v3(data->grabtarget, pchan->pose_tail);
693                         }
694                         else {
695                                 copy_v3_v3(data->grabtarget, pchan->pose_head);
696                         }
697                         td->loc = data->grabtarget;
698                         copy_v3_v3(td->iloc, td->loc);
699                         data->flag |= CONSTRAINT_IK_AUTO;
700
701                         /* only object matrix correction */
702                         copy_m3_m3(td->mtx, omat);
703                         invert_m3_m3(td->smtx, td->mtx);
704                 }
705         }
706
707         /* store reference to first constraint */
708         td->con= pchan->constraints.first;
709 }
710
711 static void bone_children_clear_transflag(int mode, short around, ListBase *lb)
712 {
713         Bone *bone= lb->first;
714
715         for(;bone;bone= bone->next) {
716                 if((bone->flag & BONE_HINGE) && (bone->flag & BONE_CONNECTED))
717                 {
718                         bone->flag |= BONE_HINGE_CHILD_TRANSFORM;
719                 }
720                 else if (bone->flag & BONE_TRANSFORM && (mode == TFM_ROTATION || mode == TFM_TRACKBALL) && around == V3D_LOCAL)
721                 {
722                         bone->flag |= BONE_TRANSFORM_CHILD;
723                 }
724                 else {
725                         bone->flag &= ~BONE_TRANSFORM;
726                 }
727
728                 bone_children_clear_transflag(mode, around, &bone->childbase);
729         }
730 }
731
732 /* sets transform flags in the bones
733  * returns total number of bones with BONE_TRANSFORM */
734 int count_set_pose_transflags(int *out_mode, short around, Object *ob)
735 {
736         bArmature *arm= ob->data;
737         bPoseChannel *pchan;
738         Bone *bone;
739         int mode = *out_mode;
740         int hastranslation = 0;
741         int total = 0;
742
743         for (pchan = ob->pose->chanbase.first; pchan; pchan = pchan->next) {
744                 bone = pchan->bone;
745                 if (PBONE_VISIBLE(arm, bone)) {
746                         if ((bone->flag & BONE_SELECTED))
747                                 bone->flag |= BONE_TRANSFORM;
748                         else
749                                 bone->flag &= ~BONE_TRANSFORM;
750                         
751                         bone->flag &= ~BONE_HINGE_CHILD_TRANSFORM;
752                         bone->flag &= ~BONE_TRANSFORM_CHILD;
753                 }
754                 else
755                         bone->flag &= ~BONE_TRANSFORM;
756         }
757
758         /* make sure no bone can be transformed when a parent is transformed */
759         /* since pchans are depsgraph sorted, the parents are in beginning of list */
760         if(mode != TFM_BONESIZE) {
761                 for(pchan = ob->pose->chanbase.first; pchan; pchan = pchan->next) {
762                         bone = pchan->bone;
763                         if(bone->flag & BONE_TRANSFORM)
764                                 bone_children_clear_transflag(mode, around, &bone->childbase);
765                 }
766         }
767         /* now count, and check if we have autoIK or have to switch from translate to rotate */
768         hastranslation = 0;
769
770         for(pchan = ob->pose->chanbase.first; pchan; pchan = pchan->next) {
771                 bone = pchan->bone;
772                 if(bone->flag & BONE_TRANSFORM) {
773                         total++;
774                         
775                         if(mode == TFM_TRANSLATION) {
776                                 if( has_targetless_ik(pchan)==NULL ) {
777                                         if(pchan->parent && (pchan->bone->flag & BONE_CONNECTED)) {
778                                                 if(pchan->bone->flag & BONE_HINGE_CHILD_TRANSFORM)
779                                                         hastranslation = 1;
780                                         }
781                                         else if((pchan->protectflag & OB_LOCK_LOC)!=OB_LOCK_LOC)
782                                                 hastranslation = 1;
783                                 }
784                                 else
785                                         hastranslation = 1;
786                         }
787                 }
788         }
789
790         /* if there are no translatable bones, do rotation */
791         if(mode == TFM_TRANSLATION && !hastranslation)
792         {
793                 *out_mode = TFM_ROTATION;
794         }
795
796         return total;
797 }
798
799
800 /* -------- Auto-IK ---------- */
801
802 /* adjust pose-channel's auto-ik chainlen */
803 static void pchan_autoik_adjust (bPoseChannel *pchan, short chainlen)
804 {
805         bConstraint *con;
806
807         /* don't bother to search if no valid constraints */
808         if ((pchan->constflag & (PCHAN_HAS_IK|PCHAN_HAS_TARGET))==0)
809                 return;
810
811         /* check if pchan has ik-constraint */
812         for (con= pchan->constraints.first; con; con= con->next) {
813                 if (con->type == CONSTRAINT_TYPE_KINEMATIC && (con->enforce!=0.0f)) {
814                         bKinematicConstraint *data= con->data;
815                         
816                         /* only accept if a temporary one (for auto-ik) */
817                         if (data->flag & CONSTRAINT_IK_TEMP) {
818                                 /* chainlen is new chainlen, but is limited by maximum chainlen */
819                                 if ((chainlen==0) || (chainlen > data->max_rootbone))
820                                         data->rootbone= data->max_rootbone;
821                                 else
822                                         data->rootbone= chainlen;
823                         }
824                 }
825         }
826 }
827
828 /* change the chain-length of auto-ik */
829 void transform_autoik_update (TransInfo *t, short mode)
830 {
831         short *chainlen= &t->settings->autoik_chainlen;
832         bPoseChannel *pchan;
833
834         /* mode determines what change to apply to chainlen */
835         if (mode == 1) {
836                 /* mode=1 is from WHEELMOUSEDOWN... increases len */
837                 (*chainlen)++;
838         }
839         else if (mode == -1) {
840                 /* mode==-1 is from WHEELMOUSEUP... decreases len */
841                 if (*chainlen > 0) (*chainlen)--;
842         }
843
844         /* sanity checks (don't assume t->poseobj is set, or that it is an armature) */
845         if (ELEM(NULL, t->poseobj, t->poseobj->pose))
846                 return;
847
848         /* apply to all pose-channels */
849         for (pchan=t->poseobj->pose->chanbase.first; pchan; pchan=pchan->next) {
850                 pchan_autoik_adjust(pchan, *chainlen);
851         }
852 }
853
854 /* frees temporal IKs */
855 static void pose_grab_with_ik_clear(Object *ob)
856 {
857         bKinematicConstraint *data;
858         bPoseChannel *pchan;
859         bConstraint *con, *next;
860
861         for (pchan= ob->pose->chanbase.first; pchan; pchan= pchan->next) {
862                 /* clear all temporary lock flags */
863                 pchan->ikflag &= ~(BONE_IK_NO_XDOF_TEMP|BONE_IK_NO_YDOF_TEMP|BONE_IK_NO_ZDOF_TEMP);
864                 
865                 pchan->constflag &= ~(PCHAN_HAS_IK|PCHAN_HAS_TARGET);
866                 
867                 /* remove all temporary IK-constraints added */
868                 for (con= pchan->constraints.first; con; con= next) {
869                         next= con->next;
870                         if (con->type==CONSTRAINT_TYPE_KINEMATIC) {
871                                 data= con->data;
872                                 if (data->flag & CONSTRAINT_IK_TEMP) {
873                                         BLI_remlink(&pchan->constraints, con);
874                                         MEM_freeN(con->data);
875                                         MEM_freeN(con);
876                                         continue;
877                                 }
878                                 pchan->constflag |= PCHAN_HAS_IK;
879                                 if(data->tar==NULL || (data->tar->type==OB_ARMATURE && data->subtarget[0]==0))
880                                         pchan->constflag |= PCHAN_HAS_TARGET;
881                         }
882                 }
883         }
884 }
885
886 /* adds the IK to pchan - returns if added */
887 static short pose_grab_with_ik_add(bPoseChannel *pchan)
888 {
889         bKinematicConstraint *targetless = NULL;
890         bKinematicConstraint *data;
891         bConstraint *con;
892
893         /* Sanity check */
894         if (pchan == NULL)
895                 return 0;
896
897         /* Rule: not if there's already an IK on this channel */
898         for (con= pchan->constraints.first; con; con= con->next) {
899                 if (con->type==CONSTRAINT_TYPE_KINEMATIC) {
900                         data= con->data;
901                         
902                         if (data->tar==NULL || (data->tar->type==OB_ARMATURE && data->subtarget[0]=='\0')) {
903                                 /* make reference to constraint to base things off later (if it's the last targetless constraint encountered) */
904                                 targetless = (bKinematicConstraint *)con->data;
905                                 
906                                 /* but, if this is a targetless IK, we make it auto anyway (for the children loop) */
907                                 if (con->enforce!=0.0f) {
908                                         data->flag |= CONSTRAINT_IK_AUTO;
909                                         
910                                         /* if no chain length has been specified, just make things obey standard rotation locks too */
911                                         if (data->rootbone == 0) {
912                                                 for (; pchan; pchan=pchan->parent) {
913                                                         /* here, we set ik-settings for bone from pchan->protectflag */
914                                                         // XXX: careful with quats/axis-angle rotations where we're locking 4d components
915                                                         if (pchan->protectflag & OB_LOCK_ROTX) pchan->ikflag |= BONE_IK_NO_XDOF_TEMP;
916                                                         if (pchan->protectflag & OB_LOCK_ROTY) pchan->ikflag |= BONE_IK_NO_YDOF_TEMP;
917                                                         if (pchan->protectflag & OB_LOCK_ROTZ) pchan->ikflag |= BONE_IK_NO_ZDOF_TEMP;
918                                                 }
919                                         }
920                                         
921                                         return 0; 
922                                 }
923                         }
924                         
925                         if ((con->flag & CONSTRAINT_DISABLE)==0 && (con->enforce!=0.0f))
926                                 return 0;
927                 }
928         }
929
930         con = add_pose_constraint(NULL, pchan, "TempConstraint", CONSTRAINT_TYPE_KINEMATIC);
931         pchan->constflag |= (PCHAN_HAS_IK|PCHAN_HAS_TARGET);    /* for draw, but also for detecting while pose solving */
932         data= con->data;
933         if (targetless) { 
934                 /* if exists, use values from last targetless (but disabled) IK-constraint as base */
935                 *data = *targetless;
936         }
937         else
938                 data->flag= CONSTRAINT_IK_TIP;
939         data->flag |= CONSTRAINT_IK_TEMP|CONSTRAINT_IK_AUTO;
940         copy_v3_v3(data->grabtarget, pchan->pose_tail);
941         data->rootbone= 0; /* watch-it! has to be 0 here, since we're still on the same bone for the first time through the loop [#25885] */
942         
943         /* we only include bones that are part of a continual connected chain */
944         while (pchan) {
945                 /* here, we set ik-settings for bone from pchan->protectflag */
946                 // XXX: careful with quats/axis-angle rotations where we're locking 4d components
947                 if (pchan->protectflag & OB_LOCK_ROTX) pchan->ikflag |= BONE_IK_NO_XDOF_TEMP;
948                 if (pchan->protectflag & OB_LOCK_ROTY) pchan->ikflag |= BONE_IK_NO_YDOF_TEMP;
949                 if (pchan->protectflag & OB_LOCK_ROTZ) pchan->ikflag |= BONE_IK_NO_ZDOF_TEMP;
950                 
951                 /* now we count this pchan as being included */
952                 data->rootbone++;
953                 
954                 /* continue to parent, but only if we're connected to it */
955                 if (pchan->bone->flag & BONE_CONNECTED)
956                         pchan = pchan->parent;
957                 else
958                         pchan = NULL;
959         }
960
961         /* make a copy of maximum chain-length */
962         data->max_rootbone= data->rootbone;
963
964         return 1;
965 }
966
967 /* bone is a candidate to get IK, but we don't do it if it has children connected */
968 static short pose_grab_with_ik_children(bPose *pose, Bone *bone)
969 {
970         Bone *bonec;
971         short wentdeeper=0, added=0;
972
973         /* go deeper if children & children are connected */
974         for (bonec= bone->childbase.first; bonec; bonec= bonec->next) {
975                 if (bonec->flag & BONE_CONNECTED) {
976                         wentdeeper= 1;
977                         added+= pose_grab_with_ik_children(pose, bonec);
978                 }
979         }
980         if (wentdeeper==0) {
981                 bPoseChannel *pchan= get_pose_channel(pose, bone->name);
982                 if (pchan)
983                         added+= pose_grab_with_ik_add(pchan);
984         }
985
986         return added;
987 }
988
989 /* main call which adds temporal IK chains */
990 static short pose_grab_with_ik(Object *ob)
991 {
992         bArmature *arm;
993         bPoseChannel *pchan, *parent;
994         Bone *bonec;
995         short tot_ik= 0;
996
997         if ((ob==NULL) || (ob->pose==NULL) || (ob->mode & OB_MODE_POSE)==0)
998                 return 0;
999
1000         arm = ob->data;
1001
1002         /* Rule: allow multiple Bones (but they must be selected, and only one ik-solver per chain should get added) */
1003         for (pchan= ob->pose->chanbase.first; pchan; pchan= pchan->next) {
1004                 if (pchan->bone->layer & arm->layer) {
1005                         if (pchan->bone->flag & BONE_SELECTED) {
1006                                 /* Rule: no IK for solitatry (unconnected) bones */
1007                                 for (bonec=pchan->bone->childbase.first; bonec; bonec=bonec->next) {
1008                                         if (bonec->flag & BONE_CONNECTED) {
1009                                                 break;
1010                                         }
1011                                 }
1012                                 if ((pchan->bone->flag & BONE_CONNECTED)==0 && (bonec == NULL))
1013                                         continue;
1014
1015                                 /* rule: if selected Bone is not a root bone, it gets a temporal IK */
1016                                 if (pchan->parent) {
1017                                         /* only adds if there's no IK yet (and no parent bone was selected) */
1018                                         for (parent= pchan->parent; parent; parent= parent->parent) {
1019                                                 if (parent->bone->flag & BONE_SELECTED)
1020                                                         break;
1021                                         }
1022                                         if (parent == NULL)
1023                                                 tot_ik += pose_grab_with_ik_add(pchan);
1024                                 }
1025                                 else {
1026                                         /* rule: go over the children and add IK to the tips */
1027                                         tot_ik += pose_grab_with_ik_children(ob->pose, pchan->bone);
1028                                 }
1029                         }
1030                 }
1031         }
1032
1033         return (tot_ik) ? 1 : 0;
1034 }
1035
1036
1037 /* only called with pose mode active object now */
1038 static void createTransPose(TransInfo *t, Object *ob)
1039 {
1040         bArmature *arm;
1041         bPoseChannel *pchan;
1042         TransData *td;
1043         TransDataExtension *tdx;
1044         short ik_on= 0;
1045         int i;
1046
1047         t->total= 0;
1048
1049         /* check validity of state */
1050         arm= get_armature(ob);
1051         if ((arm==NULL) || (ob->pose==NULL)) return;
1052
1053         if (arm->flag & ARM_RESTPOS) {
1054                 if (ELEM(t->mode, TFM_DUMMY, TFM_BONESIZE)==0) {
1055                         // XXX use transform operator reports
1056                         // BKE_report(op->reports, RPT_ERROR, "Can't select linked when sync selection is enabled");
1057                         return;
1058                 }
1059         }
1060
1061         /* do we need to add temporal IK chains? */
1062         if ((arm->flag & ARM_AUTO_IK) && t->mode==TFM_TRANSLATION) {
1063                 ik_on= pose_grab_with_ik(ob);
1064                 if (ik_on) t->flag |= T_AUTOIK;
1065         }
1066
1067         /* set flags and count total (warning, can change transform to rotate) */
1068         t->total = count_set_pose_transflags(&t->mode, t->around, ob);
1069
1070         if(t->total == 0) return;
1071
1072         t->flag |= T_POSE;
1073         t->poseobj= ob; /* we also allow non-active objects to be transformed, in weightpaint */
1074
1075         /* init trans data */
1076         td = t->data = MEM_callocN(t->total*sizeof(TransData), "TransPoseBone");
1077         tdx = t->ext = MEM_callocN(t->total*sizeof(TransDataExtension), "TransPoseBoneExt");
1078         for(i=0; i<t->total; i++, td++, tdx++) {
1079                 td->ext= tdx;
1080                 td->val = NULL;
1081         }
1082
1083         /* use pose channels to fill trans data */
1084         td= t->data;
1085         for (pchan= ob->pose->chanbase.first; pchan; pchan= pchan->next) {
1086                 if (pchan->bone->flag & BONE_TRANSFORM) {
1087                         add_pose_transdata(t, pchan, ob, td);
1088                         td++;
1089                 }
1090         }
1091
1092         if(td != (t->data+t->total)) {
1093                 // XXX use transform operator reports
1094                 // BKE_report(op->reports, RPT_DEBUG, "Bone selection count error");
1095         }
1096
1097         /* initialize initial auto=ik chainlen's? */
1098         if (ik_on) transform_autoik_update(t, 0);
1099 }
1100
1101 /* ********************* armature ************** */
1102
1103 static void createTransArmatureVerts(TransInfo *t)
1104 {
1105         EditBone *ebo;
1106         bArmature *arm= t->obedit->data;
1107         ListBase *edbo = arm->edbo;
1108         TransData *td;
1109         float mtx[3][3], smtx[3][3], delta[3], bonemat[3][3];
1110         
1111         /* special hack for envelope drawmode and scaling:
1112          *      to allow scaling the size of the envelope around single points,
1113          *      mode should become TFM_BONE_ENVELOPE in this case
1114          */
1115         // TODO: maybe we need a separate hotkey for it, but this is consistent with 2.4x for now
1116         if ((t->mode == TFM_RESIZE) && (arm->drawtype==ARM_ENVELOPE))
1117                 t->mode= TFM_BONE_ENVELOPE;
1118         
1119         t->total = 0;
1120         for (ebo = edbo->first; ebo; ebo = ebo->next)
1121         {
1122                 if (EBONE_VISIBLE(arm, ebo) && !(ebo->flag & BONE_EDITMODE_LOCKED)) 
1123                 {
1124                         if (t->mode==TFM_BONESIZE)
1125                         {
1126                                 if (ebo->flag & BONE_SELECTED)
1127                                         t->total++;
1128                         }
1129                         else if (t->mode==TFM_BONE_ROLL)
1130                         {
1131                                 if (ebo->flag & BONE_SELECTED)
1132                                         t->total++;
1133                         }
1134                         else {
1135                                 if (ebo->flag & BONE_TIPSEL)
1136                                         t->total++;
1137                                 if (ebo->flag & BONE_ROOTSEL)
1138                                         t->total++;
1139                         }
1140                 }
1141         }
1142
1143         if (!t->total) return;
1144
1145         copy_m3_m4(mtx, t->obedit->obmat);
1146         invert_m3_m3(smtx, mtx);
1147
1148         td = t->data = MEM_callocN(t->total*sizeof(TransData), "TransEditBone");
1149
1150         for (ebo = edbo->first; ebo; ebo = ebo->next)
1151         {
1152                 ebo->oldlength = ebo->length;   // length==0.0 on extrude, used for scaling radius of bone points
1153
1154                 if (EBONE_VISIBLE(arm, ebo) && !(ebo->flag & BONE_EDITMODE_LOCKED)) 
1155                 {
1156                         if (t->mode==TFM_BONE_ENVELOPE)
1157                         {
1158                                 if (ebo->flag & BONE_ROOTSEL)
1159                                 {
1160                                         td->val= &ebo->rad_head;
1161                                         td->ival= *td->val;
1162
1163                                         copy_v3_v3(td->center, ebo->head);
1164                                         td->flag= TD_SELECTED;
1165
1166                                         copy_m3_m3(td->smtx, smtx);
1167                                         copy_m3_m3(td->mtx, mtx);
1168
1169                                         td->loc = NULL;
1170                                         td->ext = NULL;
1171                                         td->ob = t->obedit;
1172
1173                                         td++;
1174                                 }
1175                                 if (ebo->flag & BONE_TIPSEL)
1176                                 {
1177                                         td->val= &ebo->rad_tail;
1178                                         td->ival= *td->val;
1179                                         copy_v3_v3(td->center, ebo->tail);
1180                                         td->flag= TD_SELECTED;
1181
1182                                         copy_m3_m3(td->smtx, smtx);
1183                                         copy_m3_m3(td->mtx, mtx);
1184
1185                                         td->loc = NULL;
1186                                         td->ext = NULL;
1187                                         td->ob = t->obedit;
1188
1189                                         td++;
1190                                 }
1191
1192                         }
1193                         else if (t->mode==TFM_BONESIZE)
1194                         {
1195                                 if (ebo->flag & BONE_SELECTED) {
1196                                         if(arm->drawtype==ARM_ENVELOPE)
1197                                         {
1198                                                 td->loc= NULL;
1199                                                 td->val= &ebo->dist;
1200                                                 td->ival= ebo->dist;
1201                                         }
1202                                         else {
1203                                                 // abusive storage of scale in the loc pointer :)
1204                                                 td->loc= &ebo->xwidth;
1205                                                 copy_v3_v3(td->iloc, td->loc);
1206                                                 td->val= NULL;
1207                                         }
1208                                         copy_v3_v3(td->center, ebo->head);
1209                                         td->flag= TD_SELECTED;
1210
1211                                         /* use local bone matrix */
1212                                         sub_v3_v3v3(delta, ebo->tail, ebo->head);
1213                                         vec_roll_to_mat3(delta, ebo->roll, bonemat);
1214                                         mul_m3_m3m3(td->mtx, mtx, bonemat);
1215                                         invert_m3_m3(td->smtx, td->mtx);
1216
1217                                         copy_m3_m3(td->axismtx, td->mtx);
1218                                         normalize_m3(td->axismtx);
1219
1220                                         td->ext = NULL;
1221                                         td->ob = t->obedit;
1222
1223                                         td++;
1224                                 }
1225                         }
1226                         else if (t->mode==TFM_BONE_ROLL)
1227                         {
1228                                 if (ebo->flag & BONE_SELECTED)
1229                                 {
1230                                         td->loc= NULL;
1231                                         td->val= &(ebo->roll);
1232                                         td->ival= ebo->roll;
1233
1234                                         copy_v3_v3(td->center, ebo->head);
1235                                         td->flag= TD_SELECTED;
1236
1237                                         td->ext = NULL;
1238                                         td->ob = t->obedit;
1239
1240                                         td++;
1241                                 }
1242                         }
1243                         else {
1244                                 if (ebo->flag & BONE_TIPSEL)
1245                                 {
1246                                         copy_v3_v3(td->iloc, ebo->tail);
1247                                         copy_v3_v3(td->center, (t->around==V3D_LOCAL) ? ebo->head : td->iloc);
1248                                         td->loc= ebo->tail;
1249                                         td->flag= TD_SELECTED;
1250                                         if (ebo->flag & BONE_EDITMODE_LOCKED)
1251                                                 td->protectflag = OB_LOCK_LOC|OB_LOCK_ROT|OB_LOCK_SCALE;
1252
1253                                         copy_m3_m3(td->smtx, smtx);
1254                                         copy_m3_m3(td->mtx, mtx);
1255
1256                                         sub_v3_v3v3(delta, ebo->tail, ebo->head);
1257                                         vec_roll_to_mat3(delta, ebo->roll, td->axismtx);
1258
1259                                         if ((ebo->flag & BONE_ROOTSEL) == 0)
1260                                         {
1261                                                 td->extra = ebo;
1262                                         }
1263
1264                                         td->ext = NULL;
1265                                         td->val = NULL;
1266                                         td->ob = t->obedit;
1267
1268                                         td++;
1269                                 }
1270                                 if (ebo->flag & BONE_ROOTSEL)
1271                                 {
1272                                         copy_v3_v3(td->iloc, ebo->head);
1273                                         copy_v3_v3(td->center, td->iloc);
1274                                         td->loc= ebo->head;
1275                                         td->flag= TD_SELECTED;
1276                                         if (ebo->flag & BONE_EDITMODE_LOCKED)
1277                                                 td->protectflag = OB_LOCK_LOC|OB_LOCK_ROT|OB_LOCK_SCALE;
1278
1279                                         copy_m3_m3(td->smtx, smtx);
1280                                         copy_m3_m3(td->mtx, mtx);
1281
1282                                         sub_v3_v3v3(delta, ebo->tail, ebo->head);
1283                                         vec_roll_to_mat3(delta, ebo->roll, td->axismtx);
1284
1285                                         td->extra = ebo; /* to fix roll */
1286
1287                                         td->ext = NULL;
1288                                         td->val = NULL;
1289                                         td->ob = t->obedit;
1290
1291                                         td++;
1292                                 }
1293                         }
1294                 }
1295         }
1296 }
1297
1298 /* ********************* meta elements ********* */
1299
1300 static void createTransMBallVerts(TransInfo *t)
1301 {
1302         MetaBall *mb = (MetaBall*)t->obedit->data;
1303         MetaElem *ml;
1304         TransData *td;
1305         TransDataExtension *tx;
1306         float mtx[3][3], smtx[3][3];
1307         int count=0, countsel=0;
1308         int propmode = t->flag & T_PROP_EDIT;
1309
1310         /* count totals */
1311         for(ml= mb->editelems->first; ml; ml= ml->next) {
1312                 if(ml->flag & SELECT) countsel++;
1313                 if(propmode) count++;
1314         }
1315
1316         /* note: in prop mode we need at least 1 selected */
1317         if (countsel==0) return;
1318
1319         if(propmode) t->total = count;
1320         else t->total = countsel;
1321
1322         td = t->data= MEM_callocN(t->total*sizeof(TransData), "TransObData(MBall EditMode)");
1323         tx = t->ext = MEM_callocN(t->total*sizeof(TransDataExtension), "MetaElement_TransExtension");
1324
1325         copy_m3_m4(mtx, t->obedit->obmat);
1326         invert_m3_m3(smtx, mtx);
1327
1328         for(ml= mb->editelems->first; ml; ml= ml->next) {
1329                 if(propmode || (ml->flag & SELECT)) {
1330                         td->loc= &ml->x;
1331                         copy_v3_v3(td->iloc, td->loc);
1332                         copy_v3_v3(td->center, td->loc);
1333
1334                         if(ml->flag & SELECT) td->flag= TD_SELECTED | TD_USEQUAT | TD_SINGLESIZE;
1335                         else td->flag= TD_USEQUAT;
1336
1337                         copy_m3_m3(td->smtx, smtx);
1338                         copy_m3_m3(td->mtx, mtx);
1339
1340                         td->ext = tx;
1341
1342                         /* Radius of MetaElem (mass of MetaElem influence) */
1343                         if(ml->flag & MB_SCALE_RAD) {
1344                                 td->val = &ml->rad;
1345                                 td->ival = ml->rad;
1346                         }
1347                         else{
1348                                 td->val = &ml->s;
1349                                 td->ival = ml->s;
1350                         }
1351
1352                         /* expx/expy/expz determine "shape" of some MetaElem types */
1353                         tx->size = &ml->expx;
1354                         tx->isize[0] = ml->expx;
1355                         tx->isize[1] = ml->expy;
1356                         tx->isize[2] = ml->expz;
1357
1358                         /* quat is used for rotation of MetaElem */
1359                         tx->quat = ml->quat;
1360                         copy_qt_qt(tx->iquat, ml->quat);
1361
1362                         tx->rot = NULL;
1363
1364                         td++;
1365                         tx++;
1366                 }
1367         }
1368 }
1369
1370 /* ********************* curve/surface ********* */
1371
1372 static void calc_distanceCurveVerts(TransData *head, TransData *tail)
1373 {
1374         TransData *td, *td_near = NULL;
1375         for (td = head; td<=tail; td++) {
1376                 if (td->flag & TD_SELECTED) {
1377                         td_near = td;
1378                         td->dist = 0.0f;
1379                 }
1380                 else if(td_near) {
1381                         float dist;
1382                         dist = len_v3v3(td_near->center, td->center);
1383                         if (dist < (td-1)->dist) {
1384                                 td->dist = (td-1)->dist;
1385                         }
1386                         else {
1387                                 td->dist = dist;
1388                         }
1389                 }
1390                 else {
1391                         td->dist = MAXFLOAT;
1392                         td->flag |= TD_NOTCONNECTED;
1393                 }
1394         }
1395         td_near = NULL;
1396         for (td = tail; td>=head; td--) {
1397                 if (td->flag & TD_SELECTED) {
1398                         td_near = td;
1399                         td->dist = 0.0f;
1400                 }
1401                 else if(td_near) {
1402                         float dist;
1403                         dist = len_v3v3(td_near->center, td->center);
1404                         if (td->flag & TD_NOTCONNECTED || dist < td->dist || (td+1)->dist < td->dist) {
1405                                 td->flag &= ~TD_NOTCONNECTED;
1406                                 if (dist < (td+1)->dist) {
1407                                         td->dist = (td+1)->dist;
1408                                 }
1409                                 else {
1410                                         td->dist = dist;
1411                                 }
1412                         }
1413                 }
1414         }
1415 }
1416
1417 /* Utility function for getting the handle data from bezier's */
1418 static TransDataCurveHandleFlags *initTransDataCurveHandles(TransData *td, struct BezTriple *bezt)
1419 {
1420         TransDataCurveHandleFlags *hdata;
1421         td->flag |= TD_BEZTRIPLE;
1422         hdata = td->hdata = MEM_mallocN(sizeof(TransDataCurveHandleFlags), "CuHandle Data");
1423         hdata->ih1 = bezt->h1;
1424         hdata->h1 = &bezt->h1;
1425         hdata->ih2 = bezt->h2; /* incase the second is not selected */
1426         hdata->h2 = &bezt->h2;
1427         return hdata;
1428 }
1429
1430 static void createTransCurveVerts(bContext *C, TransInfo *t)
1431 {
1432         Object *obedit= CTX_data_edit_object(C);
1433         Curve *cu= obedit->data;
1434         TransData *td = NULL;
1435           Nurb *nu;
1436         BezTriple *bezt;
1437         BPoint *bp;
1438         float mtx[3][3], smtx[3][3];
1439         int a;
1440         int count=0, countsel=0;
1441         int propmode = t->flag & T_PROP_EDIT;
1442         short hide_handles = (cu->drawflag & CU_HIDE_HANDLES);
1443         ListBase *nurbs;
1444
1445         /* to be sure */
1446         if(cu->editnurb==NULL) return;
1447
1448         /* count total of vertices, check identical as in 2nd loop for making transdata! */
1449         nurbs= curve_editnurbs(cu);
1450         for(nu= nurbs->first; nu; nu= nu->next) {
1451                 if(nu->type == CU_BEZIER) {
1452                         for(a=0, bezt= nu->bezt; a<nu->pntsu; a++, bezt++) {
1453                                 if(bezt->hide==0) {
1454                                         if (hide_handles) {
1455                                                 if(bezt->f2 & SELECT) countsel+=3;
1456                                                 if(propmode) count+= 3;
1457                                         } else {
1458                                                 if(bezt->f1 & SELECT) countsel++;
1459                                                 if(bezt->f2 & SELECT) countsel++;
1460                                                 if(bezt->f3 & SELECT) countsel++;
1461                                                 if(propmode) count+= 3;
1462                                         }
1463                                 }
1464                         }
1465                 }
1466                 else {
1467                         for(a= nu->pntsu*nu->pntsv, bp= nu->bp; a>0; a--, bp++) {
1468                                 if(bp->hide==0) {
1469                                         if(propmode) count++;
1470                                         if(bp->f1 & SELECT) countsel++;
1471                                 }
1472                         }
1473                 }
1474         }
1475         /* note: in prop mode we need at least 1 selected */
1476         if (countsel==0) return;
1477
1478         if(propmode) t->total = count;
1479         else t->total = countsel;
1480         t->data= MEM_callocN(t->total*sizeof(TransData), "TransObData(Curve EditMode)");
1481
1482         copy_m3_m4(mtx, t->obedit->obmat);
1483         invert_m3_m3(smtx, mtx);
1484
1485         td = t->data;
1486         for(nu= nurbs->first; nu; nu= nu->next) {
1487                 if(nu->type == CU_BEZIER) {
1488                         TransData *head, *tail;
1489                         head = tail = td;
1490                         for(a=0, bezt= nu->bezt; a<nu->pntsu; a++, bezt++) {
1491                                 if(bezt->hide==0) {
1492                                         TransDataCurveHandleFlags *hdata = NULL;
1493
1494                                         if(             propmode ||
1495                                                         ((bezt->f2 & SELECT) && hide_handles) ||
1496                                                         ((bezt->f1 & SELECT) && hide_handles == 0)
1497                                           ) {
1498                                                 copy_v3_v3(td->iloc, bezt->vec[0]);
1499                                                 td->loc= bezt->vec[0];
1500                                                 copy_v3_v3(td->center, bezt->vec[(hide_handles || bezt->f2 & SELECT) ? 1:0]);
1501                                                 if (hide_handles) {
1502                                                         if(bezt->f2 & SELECT) td->flag= TD_SELECTED;
1503                                                         else td->flag= 0;
1504                                                 } else {
1505                                                         if(bezt->f1 & SELECT) td->flag= TD_SELECTED;
1506                                                         else td->flag= 0;
1507                                                 }
1508                                                 td->ext = NULL;
1509                                                 td->val = NULL;
1510
1511                                                 hdata = initTransDataCurveHandles(td, bezt);
1512
1513                                                 copy_m3_m3(td->smtx, smtx);
1514                                                 copy_m3_m3(td->mtx, mtx);
1515
1516                                                 td++;
1517                                                 count++;
1518                                                 tail++;
1519                                         }
1520
1521                                         /* This is the Curve Point, the other two are handles */
1522                                         if(propmode || (bezt->f2 & SELECT)) {
1523                                                 copy_v3_v3(td->iloc, bezt->vec[1]);
1524                                                 td->loc= bezt->vec[1];
1525                                                 copy_v3_v3(td->center, td->loc);
1526                                                 if(bezt->f2 & SELECT) td->flag= TD_SELECTED;
1527                                                 else td->flag= 0;
1528                                                 td->ext = NULL;
1529
1530                                                 if (t->mode==TFM_CURVE_SHRINKFATTEN) { /* || t->mode==TFM_RESIZE) {*/ /* TODO - make points scale */
1531                                                         td->val = &(bezt->radius);
1532                                                         td->ival = bezt->radius;
1533                                                 } else if (t->mode==TFM_TILT) {
1534                                                         td->val = &(bezt->alfa);
1535                                                         td->ival = bezt->alfa;
1536                                                 } else {
1537                                                         td->val = NULL;
1538                                                 }
1539
1540                                                 copy_m3_m3(td->smtx, smtx);
1541                                                 copy_m3_m3(td->mtx, mtx);
1542
1543                                                 if ((bezt->f1&SELECT)==0 && (bezt->f3&SELECT)==0)
1544                                                 /* If the middle is selected but the sides arnt, this is needed */
1545                                                 if (hdata==NULL) { /* if the handle was not saved by the previous handle */
1546                                                         hdata = initTransDataCurveHandles(td, bezt);
1547                                                 }
1548
1549                                                 td++;
1550                                                 count++;
1551                                                 tail++;
1552                                         }
1553                                         if(             propmode ||
1554                                                         ((bezt->f2 & SELECT) && hide_handles) ||
1555                                                         ((bezt->f3 & SELECT) && hide_handles == 0)
1556                                           ) {
1557                                                 copy_v3_v3(td->iloc, bezt->vec[2]);
1558                                                 td->loc= bezt->vec[2];
1559                                                 copy_v3_v3(td->center, bezt->vec[(hide_handles || bezt->f2 & SELECT) ? 1:2]);
1560                                                 if (hide_handles) {
1561                                                         if(bezt->f2 & SELECT) td->flag= TD_SELECTED;
1562                                                         else td->flag= 0;
1563                                                 } else {
1564                                                         if(bezt->f3 & SELECT) td->flag= TD_SELECTED;
1565                                                         else td->flag= 0;
1566                                                 }
1567                                                 td->ext = NULL;
1568                                                 td->val = NULL;
1569
1570                                                 if (hdata==NULL) { /* if the handle was not saved by the previous handle */
1571                                                         hdata = initTransDataCurveHandles(td, bezt);
1572                                                 }
1573
1574                                                 copy_m3_m3(td->smtx, smtx);
1575                                                 copy_m3_m3(td->mtx, mtx);
1576
1577                                                 td++;
1578                                                 count++;
1579                                                 tail++;
1580                                         }
1581                                 }
1582                                 else if (propmode && head != tail) {
1583                                         calc_distanceCurveVerts(head, tail-1);
1584                                         head = tail;
1585                                 }
1586                         }
1587                         if (propmode && head != tail)
1588                                 calc_distanceCurveVerts(head, tail-1);
1589
1590                         /* TODO - in the case of tilt and radius we can also avoid allocating the initTransDataCurveHandles
1591                          * but for now just dont change handle types */
1592                         if (ELEM(t->mode, TFM_CURVE_SHRINKFATTEN, TFM_TILT) == 0) {
1593                                 /* sets the handles based on their selection, do this after the data is copied to the TransData */
1594                                 testhandlesNurb(nu);
1595                         }
1596                 }
1597                 else {
1598                         TransData *head, *tail;
1599                         head = tail = td;
1600                         for(a= nu->pntsu*nu->pntsv, bp= nu->bp; a>0; a--, bp++) {
1601                                 if(bp->hide==0) {
1602                                         if(propmode || (bp->f1 & SELECT)) {
1603                                                 copy_v3_v3(td->iloc, bp->vec);
1604                                                 td->loc= bp->vec;
1605                                                 copy_v3_v3(td->center, td->loc);
1606                                                 if(bp->f1 & SELECT) td->flag= TD_SELECTED;
1607                                                 else td->flag= 0;
1608                                                 td->ext = NULL;
1609
1610                                                 if (t->mode==TFM_CURVE_SHRINKFATTEN || t->mode==TFM_RESIZE) {
1611                                                         td->val = &(bp->radius);
1612                                                         td->ival = bp->radius;
1613                                                 } else {
1614                                                         td->val = &(bp->alfa);
1615                                                         td->ival = bp->alfa;
1616                                                 }
1617
1618                                                 copy_m3_m3(td->smtx, smtx);
1619                                                 copy_m3_m3(td->mtx, mtx);
1620
1621                                                 td++;
1622                                                 count++;
1623                                                 tail++;
1624                                         }
1625                                 }
1626                                 else if (propmode && head != tail) {
1627                                         calc_distanceCurveVerts(head, tail-1);
1628                                         head = tail;
1629                                 }
1630                         }
1631                         if (propmode && head != tail)
1632                                 calc_distanceCurveVerts(head, tail-1);
1633                 }
1634         }
1635 }
1636
1637 /* ********************* lattice *************** */
1638
1639 static void createTransLatticeVerts(TransInfo *t)
1640 {
1641         Lattice *latt = ((Lattice*)t->obedit->data)->editlatt->latt;
1642         TransData *td = NULL;
1643         BPoint *bp;
1644         float mtx[3][3], smtx[3][3];
1645         int a;
1646         int count=0, countsel=0;
1647         int propmode = t->flag & T_PROP_EDIT;
1648
1649         bp = latt->def;
1650         a  = latt->pntsu * latt->pntsv * latt->pntsw;
1651         while(a--) {
1652                 if(bp->hide==0) {
1653                         if(bp->f1 & SELECT) countsel++;
1654                         if(propmode) count++;
1655                 }
1656                 bp++;
1657         }
1658
1659          /* note: in prop mode we need at least 1 selected */
1660         if (countsel==0) return;
1661
1662         if(propmode) t->total = count;
1663         else t->total = countsel;
1664         t->data= MEM_callocN(t->total*sizeof(TransData), "TransObData(Lattice EditMode)");
1665
1666         copy_m3_m4(mtx, t->obedit->obmat);
1667         invert_m3_m3(smtx, mtx);
1668
1669         td = t->data;
1670         bp = latt->def;
1671         a  = latt->pntsu * latt->pntsv * latt->pntsw;
1672         while(a--) {
1673                 if(propmode || (bp->f1 & SELECT)) {
1674                         if(bp->hide==0) {
1675                                 copy_v3_v3(td->iloc, bp->vec);
1676                                 td->loc= bp->vec;
1677                                 copy_v3_v3(td->center, td->loc);
1678                                 if(bp->f1 & SELECT) td->flag= TD_SELECTED;
1679                                 else td->flag= 0;
1680                                 copy_m3_m3(td->smtx, smtx);
1681                                 copy_m3_m3(td->mtx, mtx);
1682
1683                                 td->ext = NULL;
1684                                 td->val = NULL;
1685
1686                                 td++;
1687                                 count++;
1688                         }
1689                 }
1690                 bp++;
1691         }
1692 }
1693
1694 /* ******************* particle edit **************** */
1695 static void createTransParticleVerts(bContext *C, TransInfo *t)
1696 {
1697         TransData *td = NULL;
1698         TransDataExtension *tx;
1699         Base *base = CTX_data_active_base(C);
1700         Object *ob = CTX_data_active_object(C);
1701         ParticleEditSettings *pset = PE_settings(t->scene);
1702         PTCacheEdit *edit = PE_get_current(t->scene, ob);
1703         ParticleSystem *psys = NULL;
1704         ParticleSystemModifierData *psmd = NULL;
1705         PTCacheEditPoint *point;
1706         PTCacheEditKey *key;
1707         float mat[4][4];
1708         int i,k, transformparticle;
1709         int count = 0, hasselected = 0;
1710         int propmode = t->flag & T_PROP_EDIT;
1711
1712         if(edit==NULL || t->settings->particle.selectmode==SCE_SELECT_PATH) return;
1713
1714         psys = edit->psys;
1715
1716         if(psys)
1717                 psmd = psys_get_modifier(ob,psys);
1718
1719         base->flag |= BA_HAS_RECALC_DATA;
1720
1721         for(i=0, point=edit->points; i<edit->totpoint; i++, point++) {
1722                 point->flag &= ~PEP_TRANSFORM;
1723                 transformparticle= 0;
1724
1725                 if((point->flag & PEP_HIDE)==0) {
1726                         for(k=0, key=point->keys; k<point->totkey; k++, key++) {
1727                                 if((key->flag&PEK_HIDE)==0) {
1728                                         if(key->flag&PEK_SELECT) {
1729                                                 hasselected= 1;
1730                                                 transformparticle= 1;
1731                                         }
1732                                         else if(propmode)
1733                                                 transformparticle= 1;
1734                                 }
1735                         }
1736                 }
1737
1738                 if(transformparticle) {
1739                         count += point->totkey;
1740                         point->flag |= PEP_TRANSFORM;
1741                 }
1742         }
1743
1744          /* note: in prop mode we need at least 1 selected */
1745         if (hasselected==0) return;
1746
1747         t->total = count;
1748         td = t->data = MEM_callocN(t->total * sizeof(TransData), "TransObData(Particle Mode)");
1749
1750         if(t->mode == TFM_BAKE_TIME)
1751                 tx = t->ext = MEM_callocN(t->total * sizeof(TransDataExtension), "Particle_TransExtension");
1752         else
1753                 tx = t->ext = NULL;
1754
1755         unit_m4(mat);
1756
1757         invert_m4_m4(ob->imat,ob->obmat);
1758
1759         for(i=0, point=edit->points; i<edit->totpoint; i++, point++) {
1760                 TransData *head, *tail;
1761                 head = tail = td;
1762
1763                 if(!(point->flag & PEP_TRANSFORM)) continue;
1764
1765                 if(psys && !(psys->flag & PSYS_GLOBAL_HAIR))
1766                         psys_mat_hair_to_global(ob, psmd->dm, psys->part->from, psys->particles + i, mat);
1767
1768                 for(k=0, key=point->keys; k<point->totkey; k++, key++) {
1769                         if(key->flag & PEK_USE_WCO) {
1770                                 copy_v3_v3(key->world_co, key->co);
1771                                 mul_m4_v3(mat, key->world_co);
1772                                 td->loc = key->world_co;
1773                         }
1774                         else
1775                                 td->loc = key->co;
1776
1777                         copy_v3_v3(td->iloc, td->loc);
1778                         copy_v3_v3(td->center, td->loc);
1779
1780                         if(key->flag & PEK_SELECT)
1781                                 td->flag |= TD_SELECTED;
1782                         else if(!propmode)
1783                                 td->flag |= TD_SKIP;
1784
1785                         unit_m3(td->mtx);
1786                         unit_m3(td->smtx);
1787
1788                         /* don't allow moving roots */
1789                         if(k==0 && pset->flag & PE_LOCK_FIRST && (!psys || !(psys->flag & PSYS_GLOBAL_HAIR)))
1790                                 td->protectflag |= OB_LOCK_LOC;
1791
1792                         td->ob = ob;
1793                         td->ext = tx;
1794                         if(t->mode == TFM_BAKE_TIME) {
1795                                 td->val = key->time;
1796                                 td->ival = *(key->time);
1797                                 /* abuse size and quat for min/max values */
1798                                 td->flag |= TD_NO_EXT;
1799                                 if(k==0) tx->size = NULL;
1800                                 else tx->size = (key - 1)->time;
1801
1802                                 if(k == point->totkey - 1) tx->quat = NULL;
1803                                 else tx->quat = (key + 1)->time;
1804                         }
1805
1806                         td++;
1807                         if(tx)
1808                                 tx++;
1809                         tail++;
1810                 }
1811                 if (propmode && head != tail)
1812                         calc_distanceCurveVerts(head, tail - 1);
1813         }
1814 }
1815
1816 void flushTransParticles(TransInfo *t)
1817 {
1818         Scene *scene = t->scene;
1819         Object *ob = OBACT;
1820         PTCacheEdit *edit = PE_get_current(scene, ob);
1821         ParticleSystem *psys = edit->psys;
1822         ParticleSystemModifierData *psmd = NULL;
1823         PTCacheEditPoint *point;
1824         PTCacheEditKey *key;
1825         TransData *td;
1826         float mat[4][4], imat[4][4], co[3];
1827         int i, k, propmode = t->flag & T_PROP_EDIT;
1828
1829         if(psys)
1830                 psmd = psys_get_modifier(ob, psys);
1831
1832         /* we do transform in world space, so flush world space position
1833          * back to particle local space (only for hair particles) */
1834         td= t->data;
1835         for(i=0, point=edit->points; i<edit->totpoint; i++, point++, td++) {
1836                 if(!(point->flag & PEP_TRANSFORM)) continue;
1837
1838                 if(psys && !(psys->flag & PSYS_GLOBAL_HAIR)) {
1839                         psys_mat_hair_to_global(ob, psmd->dm, psys->part->from, psys->particles + i, mat);
1840                         invert_m4_m4(imat,mat);
1841
1842                         for(k=0, key=point->keys; k<point->totkey; k++, key++) {
1843                                 copy_v3_v3(co, key->world_co);
1844                                 mul_m4_v3(imat, co);
1845
1846
1847                                 /* optimization for proportional edit */
1848                                 if(!propmode || !compare_v3v3(key->co, co, 0.0001f)) {
1849                                         copy_v3_v3(key->co, co);
1850                                         point->flag |= PEP_EDIT_RECALC;
1851                                 }
1852                         }
1853                 }
1854                 else
1855                         point->flag |= PEP_EDIT_RECALC;
1856         }
1857
1858         PE_update_object(scene, OBACT, 1);
1859 }
1860
1861 /* ********************* mesh ****************** */
1862
1863 /* proportional distance based on connectivity  */
1864 #define THRESHOLDFACTOR (1.0f-0.0001f)
1865
1866 /* I did this wrong, it should be a breadth-first search
1867  * but instead it's a depth-first search, fudged
1868  * to report shortest distances.  I have no idea how fast
1869  * or slow this is. */
1870 static void editmesh_set_connectivity_distance(BMEditMesh *em, float mtx[][3], float *dists)
1871 {
1872         BMVert **queue = NULL;
1873         float *dqueue = NULL;
1874         int *tots = MEM_callocN(sizeof(int)*em->bm->totvert, "tots editmesh_set_connectivity_distance");
1875         BLI_array_declare(queue);
1876         BLI_array_declare(dqueue);
1877         SmallHash svisit, *visit=&svisit;
1878         BMVert *v;
1879         BMIter viter;
1880         int i, start;
1881         
1882         fill_vn_fl(dists, em->bm->totvert, FLT_MAX);
1883
1884         BM_mesh_elem_index_ensure(em->bm, BM_VERT);
1885
1886         BLI_smallhash_init(visit);
1887
1888         BM_ITER(v, &viter, em->bm, BM_VERTS_OF_MESH, NULL) {
1889                 if (BM_elem_flag_test(v, BM_ELEM_SELECT)==0 || BM_elem_flag_test(v, BM_ELEM_HIDDEN))
1890                         continue;
1891                         
1892                 
1893                 BLI_smallhash_insert(visit, (uintptr_t)v, NULL);
1894                 BLI_array_append(queue, v);
1895                 BLI_array_append(dqueue, 0.0f);
1896                 dists[BM_elem_index_get(v)] = 0.0f;
1897         }
1898         
1899         start = 0;
1900         while (start < BLI_array_count(queue)) {
1901                 BMIter eiter;
1902                 BMEdge *e;
1903                 BMVert *v3, *v2;
1904                 float d, vec[3];
1905                 
1906                 v2 = queue[start];
1907                 d = dqueue[start];
1908                 
1909                 BM_ITER(e, &eiter, em->bm, BM_EDGES_OF_VERT, v2) {
1910                         float d2;
1911                         v3 = BM_edge_other_vert(e, v2);
1912                         
1913                         if (BM_elem_flag_test(v3, BM_ELEM_SELECT) || BM_elem_flag_test(v3, BM_ELEM_HIDDEN))
1914                                 continue;
1915                         
1916                         sub_v3_v3v3(vec, v2->co, v3->co);
1917                         mul_m3_v3(mtx, vec);
1918                         
1919                         d2 = d + len_v3(vec);
1920                         
1921                         if (dists[BM_elem_index_get(v3)] != FLT_MAX)
1922                                 dists[BM_elem_index_get(v3)] = MIN2(d2, dists[BM_elem_index_get(v3)]);
1923                         else
1924                                 dists[BM_elem_index_get(v3)] = d2;
1925                         
1926                         tots[BM_elem_index_get(v3)] = 1;
1927
1928                         if (BLI_smallhash_haskey(visit, (uintptr_t)v3))
1929                                 continue;
1930                         
1931                         BLI_smallhash_insert(visit, (uintptr_t)v3, NULL);
1932                         
1933                         BLI_array_append(queue, v3);
1934                         BLI_array_append(dqueue, d2);
1935                 }
1936                 
1937                 start++;
1938         }
1939
1940         BLI_smallhash_release(visit);
1941         
1942         for (i=0; i<em->bm->totvert; i++) {
1943                 if (tots[i])
1944                         dists[i] /= (float)tots[i];
1945         }
1946         
1947         BLI_array_free(queue);
1948         BLI_array_free(dqueue);
1949         MEM_freeN(tots);
1950 }
1951
1952 /* loop-in-a-loop I know, but we need it! (ton) */
1953  static void get_face_center(float cent_r[3], BMesh *bm, BMVert *eve)
1954
1955 {
1956         BMFace *efa;
1957         BMIter iter;
1958
1959         BM_ITER(efa, &iter, bm, BM_FACES_OF_VERT, eve) {
1960                 if (BM_elem_flag_test(efa, BM_ELEM_SELECT)) {
1961                         BM_face_center_mean_calc(bm, efa, cent_r);
1962                         break;
1963                 }
1964         }
1965 }
1966
1967 static void get_edge_center(float cent_r[3], BMesh *bm, BMVert *eve)
1968 {
1969         BMEdge *eed;
1970         BMIter iter;
1971
1972         BM_ITER(eed, &iter, bm, BM_EDGES_OF_VERT, eve) {
1973                 if (BM_elem_flag_test(eed, BM_ELEM_SELECT)) {
1974                         mid_v3_v3v3(cent_r, eed->v1->co, eed->v2->co);
1975                         break;
1976                 }
1977         }
1978 }
1979
1980 /* way to overwrite what data is edited with transform */
1981 static void VertsToTransData(TransInfo *t, TransData *td, BMEditMesh *em, BMVert *eve, float *bweight)
1982 {
1983         td->flag = 0;
1984         //if(key)
1985         //      td->loc = key->co;
1986         //else
1987         td->loc = eve->co;
1988
1989         copy_v3_v3(td->center, td->loc);
1990
1991         if(t->around==V3D_LOCAL) {
1992                 if(em->selectmode & SCE_SELECT_FACE)
1993                         get_face_center(td->center, em->bm, eve);
1994                 else if(em->selectmode & SCE_SELECT_EDGE)
1995                         get_edge_center(td->center, em->bm, eve);
1996         }
1997         copy_v3_v3(td->iloc, td->loc);
1998
1999         // Setting normals
2000         copy_v3_v3(td->axismtx[2], eve->no);
2001         td->axismtx[0][0]               =
2002                 td->axismtx[0][1]       =
2003                 td->axismtx[0][2]       =
2004                 td->axismtx[1][0]       =
2005                 td->axismtx[1][1]       =
2006                 td->axismtx[1][2]       = 0.0f;
2007
2008         td->ext = NULL;
2009         td->val = NULL;
2010         td->extra = NULL;
2011         if (t->mode == TFM_BWEIGHT) {
2012                 td->val = bweight;
2013                 td->ival = bweight ? *(bweight) : 1.0f;
2014         }
2015 }
2016
2017 static void createTransEditVerts(bContext *C, TransInfo *t)
2018 {
2019         ToolSettings *ts = CTX_data_tool_settings(C);
2020         TransData *tob = NULL;
2021         BMEditMesh *em = BMEdit_FromObject(t->obedit);
2022         BMesh *bm = em->bm;
2023         BMVert *eve;
2024         BMIter iter;
2025         BMVert *eve_act = NULL;
2026         float *mappedcos = NULL, *quats= NULL;
2027         float mtx[3][3], smtx[3][3], (*defmats)[3][3] = NULL, (*defcos)[3] = NULL;
2028         float *dists=NULL;
2029         int count=0, countsel=0, a, totleft;
2030         int propmode = (t->flag & T_PROP_EDIT) ? (t->flag & (T_PROP_EDIT | T_PROP_CONNECTED)) : 0;
2031         int mirror = 0;
2032         char *selstate = NULL;
2033         short selectmode = ts->selectmode;
2034
2035         if (t->flag & T_MIRROR)
2036         {
2037                 EDBM_CacheMirrorVerts(em, TRUE);
2038                 mirror = 1;
2039         }
2040
2041         /* edge slide forces edge select */
2042         if (t->mode == TFM_EDGE_SLIDE) {
2043                 selectmode = SCE_SELECT_EDGE;
2044         }
2045
2046         /* BMESH_TODO, writing into the index values is BAD!, means we cant
2047          * use the values for vertex mirror - campbell */
2048
2049         // transform now requires awareness for select mode, so we tag the f1 flags in verts
2050         if(selectmode & SCE_SELECT_VERTEX) {
2051                 BM_ITER(eve, &iter, bm, BM_VERTS_OF_MESH, NULL) {
2052                         BM_elem_flag_set(eve, BM_ELEM_TAG, BM_elem_flag_test(eve, BM_ELEM_SELECT));
2053                 }
2054         }
2055         else if(selectmode & SCE_SELECT_EDGE) {
2056                 BMEdge *eed;
2057
2058                 eve = BM_iter_new(&iter, bm, BM_VERTS_OF_MESH, NULL);
2059                 for( ; eve; eve=BM_iter_step(&iter)) BM_elem_flag_disable(eve, BM_ELEM_TAG);
2060
2061                 eed = BM_iter_new(&iter, bm, BM_EDGES_OF_MESH, NULL);
2062                 for( ; eed; eed=BM_iter_step(&iter)) {
2063                         if (BM_elem_flag_test(eed, BM_ELEM_SELECT)) {
2064                                 BM_elem_flag_enable(eed->v1, BM_ELEM_TAG);
2065                                 BM_elem_flag_enable(eed->v2, BM_ELEM_TAG);
2066                         }
2067                 }
2068         }
2069         else {
2070                 BMFace *efa;
2071                 eve = BM_iter_new(&iter, bm, BM_VERTS_OF_MESH, NULL);
2072                 for( ; eve; eve=BM_iter_step(&iter)) BM_elem_flag_disable(eve, BM_ELEM_TAG);
2073
2074                 efa = BM_iter_new(&iter, bm, BM_FACES_OF_MESH, NULL);
2075                 for( ; efa; efa=BM_iter_step(&iter)) {
2076                         if (BM_elem_flag_test(efa, BM_ELEM_SELECT)) {
2077                                 BMIter liter;
2078                                 BMLoop *l;
2079
2080                                 l = BM_iter_new(&liter, bm, BM_LOOPS_OF_FACE, efa);
2081                                 for (; l; l=BM_iter_step(&liter)) {
2082                                         BM_elem_flag_enable(l->v, BM_ELEM_TAG);
2083                                 }
2084                         }
2085                 }
2086         }
2087
2088         /* now we can count. we store selection state in selstate, since
2089          * get_crazy_mapped_editverts messes up the index state of the
2090          * verts*/
2091         selstate = MEM_callocN(sizeof(*selstate) * bm->totvert, __func__);
2092         eve = BM_iter_new(&iter, bm, BM_VERTS_OF_MESH, NULL);
2093         for(a=0; eve; eve=BM_iter_step(&iter), a++) {
2094                 if (!BM_elem_flag_test(eve, BM_ELEM_HIDDEN)) {
2095                         if (BM_elem_flag_test(eve, BM_ELEM_TAG)) {
2096                                 selstate[a] = 1;
2097                                 countsel++;
2098                         }
2099                         if(propmode) count++;
2100                 }
2101         }
2102
2103         /* note: in prop mode we need at least 1 selected */
2104         if (countsel == 0) {
2105                 goto cleanup;
2106         }
2107
2108         /* check active */
2109         if (em->bm->selected.last) {
2110                 BMEditSelection *ese = em->bm->selected.last;
2111                 if (ese->htype == BM_VERT) {
2112                         eve_act = (BMVert *)ese->ele;
2113                 }
2114         }
2115
2116
2117         if(propmode) {
2118                 t->total = count;
2119
2120                 /* allocating scratch arrays */
2121                 if (propmode & T_PROP_CONNECTED)
2122                         dists = MEM_mallocN(em->bm->totvert * sizeof(float), "scratch nears");
2123         }
2124         else t->total = countsel;
2125
2126         tob= t->data= MEM_callocN(t->total*sizeof(TransData), "TransObData(Mesh EditMode)");
2127
2128         copy_m3_m4(mtx, t->obedit->obmat);
2129         invert_m3_m3(smtx, mtx);
2130
2131         if(propmode & T_PROP_CONNECTED) {
2132                 editmesh_set_connectivity_distance(em, mtx, dists);
2133         }
2134
2135         /* detect CrazySpace [tm] */
2136         if(modifiers_getCageIndex(t->scene, t->obedit, NULL, 1)>=0) {
2137                 if(modifiers_isCorrectableDeformed(t->obedit)) {
2138                         /* check if we can use deform matrices for modifier from the
2139                          * start up to stack, they are more accurate than quats */
2140                         totleft= editbmesh_get_first_deform_matrices(t->scene, t->obedit, em, &defmats, &defcos);
2141
2142                         /* if we still have more modifiers, also do crazyspace
2143                          * correction with quats, relative to the coordinates after
2144                          * the modifiers that support deform matrices (defcos) */
2145                         if(totleft > 0) {
2146                                 mappedcos= crazyspace_get_mapped_editverts(t->scene, t->obedit);
2147                                 quats= MEM_mallocN( (t->total)*sizeof(float)*4, "crazy quats");
2148                                 crazyspace_set_quats_editmesh(em, (float*)defcos, mappedcos, quats); /* BMESH_TODO, abuses vertex index, should use an int array */
2149                                 if(mappedcos)
2150                                         MEM_freeN(mappedcos);
2151                         }
2152
2153                         if(defcos)
2154                                 MEM_freeN(defcos);
2155                 }
2156         }
2157
2158         /* find out which half we do */
2159         if(mirror) {
2160                 eve = BM_iter_new(&iter, bm, BM_VERTS_OF_MESH, NULL);
2161                 for(a=0; eve; eve=BM_iter_step(&iter), a++) {
2162                         if(!BM_elem_flag_test(eve, BM_ELEM_HIDDEN) && selstate[a] && eve->co[0]!=0.0f) {
2163                                 if(eve->co[0]<0.0f)
2164                                 {
2165                                         t->mirror = -1;
2166                                         mirror = -1;
2167                                 }
2168                                 break;
2169                         }
2170                 }
2171         }
2172
2173         eve = BM_iter_new(&iter, bm, BM_VERTS_OF_MESH, NULL);
2174         for(a=0; eve; eve=BM_iter_step(&iter), a++) {
2175                 if(!BM_elem_flag_test(eve, BM_ELEM_HIDDEN)) {
2176                         if(propmode || selstate[a]) {
2177                                 float *bweight = CustomData_bmesh_get(&bm->vdata, eve->head.data, CD_BWEIGHT);
2178                                 
2179                                 VertsToTransData(t, tob, em, eve, bweight);
2180
2181                                 /* selected */
2182                                 if(selstate[a]) tob->flag |= TD_SELECTED;
2183
2184                                 /* active */
2185                                 if(eve == eve_act) tob->flag |= TD_ACTIVE;
2186
2187                                 if(propmode) {
2188                                         if (propmode & T_PROP_CONNECTED) {
2189                                                 tob->dist = dists[a];
2190                                         } else {
2191                                                 tob->flag |= TD_NOTCONNECTED;
2192                                                 tob->dist = MAXFLOAT;
2193                                         }
2194                                 }
2195
2196                                 /* CrazySpace */
2197                                 if(defmats || (quats && BM_elem_index_get(eve) != -1)) {
2198                                         float mat[3][3], qmat[3][3], imat[3][3];
2199
2200                                         /* use both or either quat and defmat correction */
2201                                         if(quats && BM_elem_index_get(eve) != -1) {
2202                                                 quat_to_mat3(qmat, quats + 4*BM_elem_index_get(eve));
2203
2204                                                 if(defmats)
2205                                                         mul_serie_m3(mat, mtx, qmat, defmats[a],
2206                                                                 NULL, NULL, NULL, NULL, NULL);
2207                                                 else
2208                                                         mul_m3_m3m3(mat, mtx, qmat);
2209                                         }
2210                                         else
2211                                                 mul_m3_m3m3(mat, mtx, defmats[a]);
2212
2213                                         invert_m3_m3(imat, mat);
2214
2215                                         copy_m3_m3(tob->smtx, imat);
2216                                         copy_m3_m3(tob->mtx, mat);
2217                                 }
2218                                 else {
2219                                         copy_m3_m3(tob->smtx, smtx);
2220                                         copy_m3_m3(tob->mtx, mtx);
2221                                 }
2222
2223                                 /* Mirror? */
2224                                 if( (mirror>0 && tob->iloc[0]>0.0f) || (mirror<0 && tob->iloc[0]<0.0f)) {
2225                                         BMVert *vmir= EDBM_GetMirrorVert(em, eve); //t->obedit, em, eve, tob->iloc, a);
2226                                         if(vmir && vmir != eve) {
2227                                                 tob->extra = vmir;
2228                                         }
2229                                 }
2230                                 tob++;
2231                         }
2232                 }
2233         }
2234         
2235         if (mirror != 0)
2236         {
2237                 tob = t->data;
2238                 for( a = 0; a < t->total; a++, tob++ )
2239                 {
2240                         if (ABS(tob->loc[0]) <= 0.00001f)
2241                         {
2242                                 tob->flag |= TD_MIRROR_EDGE;
2243                         }
2244                 }
2245         }
2246
2247 cleanup:
2248         /* crazy space free */
2249         if(quats)
2250                 MEM_freeN(quats);
2251         if(defmats)
2252                 MEM_freeN(defmats);
2253         if (dists)
2254                 MEM_freeN(dists);
2255         
2256         MEM_freeN(selstate);
2257
2258         if (t->flag & T_MIRROR) {
2259                 EDBM_EndMirrorCache(em);
2260                 mirror = 1;
2261         }
2262 }
2263
2264 /* *** NODE EDITOR *** */
2265 void flushTransNodes(TransInfo *t)
2266 {
2267         int a;
2268         TransData2D *td;
2269
2270         /* flush to 2d vector from internally used 3d vector */
2271         for(a=0, td= t->data2d; a<t->total; a++, td++) {
2272                 td->loc2d[0]= td->loc[0];
2273                 td->loc2d[1]= td->loc[1];
2274         }
2275         
2276         /* handle intersection with noodles */
2277         if(t->total==1) {
2278                 ED_node_link_intersect_test(t->sa, 1);
2279         }
2280         
2281 }
2282
2283 /* *** SEQUENCE EDITOR *** */
2284
2285 /* commented _only_ because the meta may have animation data which
2286  * needs moving too [#28158] */
2287
2288 #define SEQ_TX_NESTED_METAS
2289
2290 void flushTransSeq(TransInfo *t)
2291 {
2292         ListBase *seqbasep= seq_give_editing(t->scene, FALSE)->seqbasep; /* Editing null check already done */
2293         int a, new_frame, old_start;
2294         TransData *td= NULL;
2295         TransData2D *td2d= NULL;
2296         TransDataSeq *tdsq= NULL;
2297         Sequence *seq;
2298
2299
2300
2301         /* prevent updating the same seq twice
2302          * if the transdata order is changed this will mess up
2303          * but so will TransDataSeq */
2304         Sequence *seq_prev= NULL;
2305
2306         /* flush to 2d vector from internally used 3d vector */
2307         for(a=0, td= t->data, td2d= t->data2d; a<t->total; a++, td++, td2d++) {
2308                 tdsq= (TransDataSeq *)td->extra;
2309                 seq= tdsq->seq;
2310                 old_start = seq->start;
2311                 new_frame= (int)floor(td2d->loc[0] + 0.5f);
2312
2313                 switch (tdsq->sel_flag) {
2314                 case SELECT:
2315 #ifdef SEQ_TX_NESTED_METAS
2316                         if ((seq->depth != 0 || seq_tx_test(seq))) /* for meta's, their children move */
2317                                 seq->start= new_frame - tdsq->start_offset;
2318 #else
2319                         if (seq->type != SEQ_META && (seq->depth != 0 || seq_tx_test(seq))) /* for meta's, their children move */
2320                                 seq->start= new_frame - tdsq->start_offset;
2321 #endif
2322                         if (seq->depth==0) {
2323                                 seq->machine= (int)floor(td2d->loc[1] + 0.5f);
2324                                 CLAMP(seq->machine, 1, MAXSEQ);
2325                         }
2326                         break;
2327                 case SEQ_LEFTSEL: /* no vertical transform  */
2328                         seq_tx_set_final_left(seq, new_frame);
2329                         seq_tx_handle_xlimits(seq, tdsq->flag&SEQ_LEFTSEL, tdsq->flag&SEQ_RIGHTSEL);
2330                         seq_single_fix(seq); /* todo - move this into aftertrans update? - old seq tx needed it anyway */
2331                         break;
2332                 case SEQ_RIGHTSEL: /* no vertical transform  */
2333                         seq_tx_set_final_right(seq, new_frame);
2334                         seq_tx_handle_xlimits(seq, tdsq->flag&SEQ_LEFTSEL, tdsq->flag&SEQ_RIGHTSEL);
2335                         seq_single_fix(seq); /* todo - move this into aftertrans update? - old seq tx needed it anyway */
2336                         break;
2337                 }
2338
2339                 if (seq != seq_prev) {
2340                         if(seq->depth==0) {
2341                                 /* Calculate this strip and all nested strips
2342                                  * children are ALWAYS transformed first
2343                                  * so we dont need to do this in another loop. */
2344                                 calc_sequence(t->scene, seq);
2345                         }
2346                         else {
2347                                 calc_sequence_disp(t->scene, seq);
2348                         }
2349
2350                         if(tdsq->sel_flag == SELECT)
2351                                 seq_offset_animdata(t->scene, seq, seq->start - old_start);
2352                 }
2353                 seq_prev= seq;
2354         }
2355
2356
2357         if (ELEM(t->mode, TFM_SEQ_SLIDE, TFM_TIME_TRANSLATE)) { /* originally TFM_TIME_EXTEND, transform changes */
2358                 /* Special annoying case here, need to calc metas with TFM_TIME_EXTEND only */
2359
2360                 /* calc all meta's then effects [#27953] */
2361                 for (seq = seqbasep->first; seq; seq = seq->next) {
2362                         if (seq->type == SEQ_META && seq->flag & SELECT) {
2363                                 calc_sequence(t->scene, seq);
2364                         }
2365                 }
2366                 for (seq = seqbasep->first; seq; seq = seq->next) {
2367                         if (seq->seq1 || seq->seq2 || seq->seq3) {
2368                                 calc_sequence(t->scene, seq);
2369                         }
2370                 }
2371         }
2372
2373         /* need to do the overlap check in a new loop otherwise adjacent strips
2374          * will not be updated and we'll get false positives */
2375         seq_prev= NULL;
2376         for(a=0, td= t->data, td2d= t->data2d; a<t->total; a++, td++, td2d++) {
2377
2378                 tdsq= (TransDataSeq *)td->extra;
2379                 seq= tdsq->seq;
2380
2381                 if (seq != seq_prev) {
2382                         if(seq->depth==0) {
2383                                 /* test overlap, displayes red outline */
2384                                 seq->flag &= ~SEQ_OVERLAP;
2385                                 if( seq_test_overlap(seqbasep, seq) ) {
2386                                         seq->flag |= SEQ_OVERLAP;
2387                                 }
2388                         }
2389                 }
2390                 seq_prev= seq;
2391         }
2392 }
2393
2394 /* ********************* UV ****************** */
2395
2396 static void UVsToTransData(SpaceImage *sima, TransData *td, TransData2D *td2d, float *uv, int selected)
2397 {
2398         float aspx, aspy;
2399
2400         ED_space_image_uv_aspect(sima, &aspx, &aspy);
2401
2402         /* uv coords are scaled by aspects. this is needed for rotations and
2403          * proportional editing to be consistent with the stretched uv coords
2404          * that are displayed. this also means that for display and numinput,
2405          * and when the the uv coords are flushed, these are converted each time */
2406         td2d->loc[0] = uv[0]*aspx;
2407         td2d->loc[1] = uv[1]*aspy;
2408         td2d->loc[2] = 0.0f;
2409         td2d->loc2d = uv;
2410
2411         td->flag = 0;
2412         td->loc = td2d->loc;
2413         copy_v3_v3(td->center, td->loc);
2414         copy_v3_v3(td->iloc, td->loc);
2415
2416         memset(td->axismtx, 0, sizeof(td->axismtx));
2417         td->axismtx[2][2] = 1.0f;
2418
2419         td->ext= NULL; td->val= NULL;
2420
2421         if(selected) {
2422                 td->flag |= TD_SELECTED;
2423                 td->dist= 0.0;
2424         }
2425         else {
2426                 td->dist= MAXFLOAT;
2427         }
2428         unit_m3(td->mtx);
2429         unit_m3(td->smtx);
2430 }
2431
2432 static void createTransUVs(bContext *C, TransInfo *t)
2433 {
2434         SpaceImage *sima = CTX_wm_space_image(C);
2435         Image *ima = CTX_data_edit_image(C);
2436         Scene *scene = t->scene;
2437         TransData *td = NULL;
2438         TransData2D *td2d = NULL;
2439         MTexPoly *tf;
2440         MLoopUV *luv;
2441         BMEditMesh *em = BMEdit_FromObject(t->obedit);
2442         BMFace *efa;
2443         BMLoop *l;
2444         BMIter iter, liter;
2445         int count=0, countsel=0;
2446         int propmode = t->flag & T_PROP_EDIT;
2447
2448         if(!ED_space_image_show_uvedit(sima, t->obedit)) return;
2449
2450         /* count */
2451         BM_ITER(efa, &iter, em->bm, BM_FACES_OF_MESH, NULL) {
2452                 tf= CustomData_bmesh_get(&em->bm->pdata, efa->head.data, CD_MTEXPOLY);
2453
2454                 if(!uvedit_face_visible(scene, ima, efa, tf)) {
2455                         BM_elem_flag_disable(efa, BM_ELEM_TAG);
2456                         continue;
2457                 }
2458                 
2459                 BM_elem_flag_enable(efa, BM_ELEM_TAG);
2460                 BM_ITER(l, &liter, em->bm, BM_LOOPS_OF_FACE, efa) {
2461                         if (uvedit_uv_selected(em, scene, l)) 
2462                                 countsel++;
2463
2464                         if(propmode)
2465                                 count++;
2466                 }
2467         }
2468
2469          /* note: in prop mode we need at least 1 selected */
2470         if (countsel==0) return;
2471
2472         t->total= (propmode)? count: countsel;
2473         t->data= MEM_callocN(t->total*sizeof(TransData), "TransObData(UV Editing)");
2474         /* for each 2d uv coord a 3d vector is allocated, so that they can be
2475          * treated just as if they were 3d verts */
2476         t->data2d= MEM_callocN(t->total*sizeof(TransData2D), "TransObData2D(UV Editing)");
2477
2478         if(sima->flag & SI_CLIP_UV)
2479                 t->flag |= T_CLIP_UV;
2480
2481         td= t->data;
2482         td2d= t->data2d;
2483
2484         BM_ITER(efa, &iter, em->bm, BM_FACES_OF_MESH, NULL) {
2485                 if (!BM_elem_flag_test(efa, BM_ELEM_TAG))
2486                         continue;
2487
2488                 tf= CustomData_bmesh_get(&em->bm->pdata, efa->head.data, CD_MTEXPOLY);
2489                 BM_ITER(l, &liter, em->bm, BM_LOOPS_OF_FACE, efa) {
2490                         if (!propmode && !uvedit_uv_selected(em, scene, l))
2491                                 continue;
2492                         
2493                         luv = CustomData_bmesh_get(&em->bm->ldata, l->head.data, CD_MLOOPUV);
2494                         UVsToTransData(sima, td++, td2d++, luv->uv, uvedit_uv_selected(em, scene, l));
2495                 }
2496         }
2497
2498         if (sima->flag & SI_LIVE_UNWRAP)
2499                 ED_uvedit_live_unwrap_begin(t->scene, t->obedit);
2500 }
2501
2502 void flushTransUVs(TransInfo *t)
2503 {
2504         SpaceImage *sima = t->sa->spacedata.first;
2505         TransData2D *td;
2506         int a, width, height;
2507         float aspx, aspy, invx, invy;
2508
2509         ED_space_image_uv_aspect(sima, &aspx, &aspy);
2510         ED_space_image_size(sima, &width, &height);
2511         invx= 1.0f/aspx;
2512         invy= 1.0f/aspy;
2513
2514         /* flush to 2d vector from internally used 3d vector */
2515         for(a=0, td= t->data2d; a<t->total; a++, td++) {
2516                 td->loc2d[0]= td->loc[0]*invx;
2517                 td->loc2d[1]= td->loc[1]*invy;
2518
2519                 if((sima->flag & SI_PIXELSNAP) && (t->state != TRANS_CANCEL)) {
2520                         td->loc2d[0]= (float)floor(width*td->loc2d[0] + 0.5f)/width;
2521                         td->loc2d[1]= (float)floor(height*td->loc2d[1] + 0.5f)/height;
2522                 }
2523         }
2524 }
2525
2526 int clipUVTransform(TransInfo *t, float *vec, int resize)
2527 {
2528         TransData *td;
2529         int a, clipx=1, clipy=1;
2530         float aspx, aspy, min[2], max[2];
2531
2532         ED_space_image_uv_aspect(t->sa->spacedata.first, &aspx, &aspy);
2533         min[0]= min[1]= 0.0f;
2534         max[0]= aspx; max[1]= aspy;
2535
2536         for(a=0, td= t->data; a<t->total; a++, td++) {
2537                 DO_MINMAX2(td->loc, min, max);
2538         }
2539
2540         if(resize) {
2541                 if(min[0] < 0.0f && t->center[0] > 0.0f && t->center[0] < aspx*0.5f)
2542                         vec[0] *= t->center[0]/(t->center[0] - min[0]);
2543                 else if(max[0] > aspx && t->center[0] < aspx)
2544                         vec[0] *= (t->center[0] - aspx)/(t->center[0] - max[0]);
2545                 else
2546                         clipx= 0;
2547
2548                 if(min[1] < 0.0f && t->center[1] > 0.0f && t->center[1] < aspy*0.5f)
2549                         vec[1] *= t->center[1]/(t->center[1] - min[1]);
2550                 else if(max[1] > aspy && t->center[1] < aspy)
2551                         vec[1] *= (t->center[1] - aspy)/(t->center[1] - max[1]);
2552                 else
2553                         clipy= 0;
2554         }
2555         else {
2556                 if(min[0] < 0.0f)
2557                         vec[0] -= min[0];
2558                 else if(max[0] > aspx)
2559                         vec[0] -= max[0]-aspx;
2560                 else
2561                         clipx= 0;
2562
2563                 if(min[1] < 0.0f)
2564                         vec[1] -= min[1];
2565                 else if(max[1] > aspy)
2566                         vec[1] -= max[1]-aspy;
2567                 else
2568                         clipy= 0;
2569         }
2570
2571         return (clipx || clipy);
2572 }
2573
2574 /* ********************* ANIMATION EDITORS (GENERAL) ************************* */
2575
2576 /* This function tests if a point is on the "mouse" side of the cursor/frame-marking */
2577 static short FrameOnMouseSide(char side, float frame, float cframe)
2578 {
2579         /* both sides, so it doesn't matter */
2580         if (side == 'B') return 1;
2581
2582         /* only on the named side */
2583         if (side == 'R')
2584                 return (frame >= cframe) ? 1 : 0;
2585         else
2586                 return (frame <= cframe) ? 1 : 0;
2587 }
2588
2589 /* ********************* NLA EDITOR ************************* */
2590
2591 static void createTransNlaData(bContext *C, TransInfo *t)
2592 {
2593         Scene *scene= t->scene;
2594         SpaceNla *snla = NULL;
2595         TransData *td = NULL;
2596         TransDataNla *tdn = NULL;
2597         
2598         bAnimContext ac;
2599         ListBase anim_data = {NULL, NULL};
2600         bAnimListElem *ale;
2601         int filter;
2602         
2603         int count=0;
2604         
2605         /* determine what type of data we are operating on */
2606         if (ANIM_animdata_get_context(C, &ac) == 0)
2607                 return;
2608         snla = (SpaceNla *)ac.sl;
2609         
2610         /* filter data */
2611         filter= (ANIMFILTER_DATA_VISIBLE | ANIMFILTER_LIST_VISIBLE | ANIMFILTER_FOREDIT);
2612         ANIM_animdata_filter(&ac, &anim_data, filter, ac.data, ac.datatype);
2613         
2614         /* which side of the current frame should be allowed */
2615         if (t->mode == TFM_TIME_EXTEND) {
2616                 /* only side on which mouse is gets transformed */
2617                 float xmouse, ymouse;
2618                 
2619                 UI_view2d_region_to_view(&ac.ar->v2d, t->imval[0], t->imval[1], &xmouse, &ymouse);
2620                 t->frame_side= (xmouse > CFRA) ? 'R' : 'L';
2621         }
2622         else {
2623                 /* normal transform - both sides of current frame are considered */
2624                 t->frame_side = 'B';
2625         }
2626         
2627         /* loop 1: count how many strips are selected (consider each strip as 2 points) */
2628         for (ale= anim_data.first; ale; ale= ale->next) {
2629                 NlaTrack *nlt= (NlaTrack *)ale->data;
2630                 NlaStrip *strip;
2631                 
2632                 /* make some meta-strips for chains of selected strips */
2633                 BKE_nlastrips_make_metas(&nlt->strips, 1);
2634                 
2635                 /* only consider selected strips */
2636                 for (strip= nlt->strips.first; strip; strip= strip->next) {
2637                         // TODO: we can make strips have handles later on...
2638                         /* transition strips can't get directly transformed */
2639                         if (strip->type != NLASTRIP_TYPE_TRANSITION) {
2640                                 if (strip->flag & NLASTRIP_FLAG_SELECT) {
2641                                         if (FrameOnMouseSide(t->frame_side, strip->start, (float)CFRA)) count++;
2642                                         if (FrameOnMouseSide(t->frame_side, strip->end, (float)CFRA)) count++;
2643                                 }
2644                         }
2645                 }
2646         }
2647         
2648         /* stop if trying to build list if nothing selected */
2649         if (count == 0) {
2650                 /* cleanup temp list */
2651                 BLI_freelistN(&anim_data);
2652                 return;
2653         }
2654         
2655         /* allocate memory for data */
2656         t->total= count;
2657         
2658         t->data= MEM_callocN(t->total*sizeof(TransData), "TransData(NLA Editor)");
2659         td= t->data;
2660         t->customData= MEM_callocN(t->total*sizeof(TransDataNla), "TransDataNla (NLA Editor)");
2661         tdn= t->customData;
2662         
2663         /* loop 2: build transdata array */
2664         for (ale= anim_data.first; ale; ale= ale->next) {
2665                 /* only if a real NLA-track */
2666                 if (ale->type == ANIMTYPE_NLATRACK) {
2667                         AnimData *adt = ale->adt;
2668                         NlaTrack *nlt= (NlaTrack *)ale->data;
2669                         NlaStrip *strip;
2670                         
2671                         /* only consider selected strips */
2672                         for (strip= nlt->strips.first; strip; strip= strip->next) {
2673                                 // TODO: we can make strips have handles later on...
2674                                 /* transition strips can't get directly transformed */
2675                                 if (strip->type != NLASTRIP_TYPE_TRANSITION) {
2676                                         if (strip->flag & NLASTRIP_FLAG_SELECT) {
2677                                                 /* our transform data is constructed as follows:
2678                                                  *      - only the handles on the right side of the current-frame get included
2679                                                  *      - td structs are transform-elements operated on by the transform system
2680                                                  *        and represent a single handle. The storage/pointer used (val or loc) depends on
2681                                                  *        whether we're scaling or transforming. Ultimately though, the handles
2682                                                  *        the td writes to will simply be a dummy in tdn
2683                                                  *      - for each strip being transformed, a single tdn struct is used, so in some
2684                                                  *        cases, there will need to be 1 of these tdn elements in the array skipped...
2685                                                  */
2686                                                 float center[3], yval;
2687                                                 
2688                                                 /* firstly, init tdn settings */
2689                                                 tdn->id= ale->id;
2690                                                 tdn->oldTrack= tdn->nlt= nlt;
2691                                                 tdn->strip= strip;
2692                                                 tdn->trackIndex= BLI_findindex(&adt->nla_tracks, nlt);
2693                                                 
2694                                                 yval= (float)(tdn->trackIndex * NLACHANNEL_STEP(snla));
2695                                                 
2696                                                 tdn->h1[0]= strip->start;
2697                                                 tdn->h1[1]= yval;
2698                                                 tdn->h2[0]= strip->end;
2699                                                 tdn->h2[1]= yval;
2700                                                 
2701                                                 center[0]= (float)CFRA;
2702                                                 center[1]= yval;
2703                                                 center[2]= 0.0f;
2704                                                 
2705                                                 /* set td's based on which handles are applicable */
2706                                                 if (FrameOnMouseSide(t->frame_side, strip->start, (float)CFRA))
2707                                                 {
2708                                                         /* just set tdn to assume that it only has one handle for now */
2709                                                         tdn->handle= -1;
2710                                                         
2711                                                         /* now, link the transform data up to this data */
2712                                                         if (ELEM(t->mode, TFM_TRANSLATION, TFM_TIME_EXTEND)) {
2713                                                                 td->loc= tdn->h1;
2714                                                                 copy_v3_v3(td->iloc, tdn->h1);
2715                                                                 
2716                                                                 /* store all the other gunk that is required by transform */
2717                                                                 copy_v3_v3(td->center, center);
2718                                                                 memset(td->axismtx, 0, sizeof(td->axismtx));
2719                                                                 td->axismtx[2][2] = 1.0f;
2720                                                                 
2721                                                                 td->ext= NULL; td->val= NULL;
2722                                                                 
2723                                                                 td->flag |= TD_SELECTED;
2724                                                                 td->dist= 0.0f;
2725                                                                 
2726                                                                 unit_m3(td->mtx);
2727                                                                 unit_m3(td->smtx);
2728                                                         }
2729                                                         else {
2730                                                                 /* time scaling only needs single value */
2731                                                                 td->val= &tdn->h1[0];
2732                                                                 td->ival= tdn->h1[0];
2733                                                         }
2734                                                         
2735                                                         td->extra= tdn;
2736                                                         td++;
2737                                                 }
2738                                                 if (FrameOnMouseSide(t->frame_side, strip->end, (float)CFRA))
2739                                                 {
2740                                                         /* if tdn is already holding the start handle, then we're doing both, otherwise, only end */
2741                                                         tdn->handle= (tdn->handle) ? 2 : 1;
2742                                                         
2743                                                         /* now, link the transform data up to this data */
2744                                                         if (ELEM(t->mode, TFM_TRANSLATION, TFM_TIME_EXTEND)) {
2745                                                                 td->loc= tdn->h2;
2746                                                                 copy_v3_v3(td->iloc, tdn->h2);
2747                                                                 
2748                                                                 /* store all the other gunk that is required by transform */
2749                                                                 copy_v3_v3(td->center, center);
2750                                                                 memset(td->axismtx, 0, sizeof(td->axismtx));
2751                                                                 td->axismtx[2][2] = 1.0f;
2752                                                                 
2753                                                                 td->ext= NULL; td->val= NULL;
2754                                                                 
2755                                                                 td->flag |= TD_SELECTED;
2756                                                                 td->dist= 0.0f;
2757                                                                 
2758                                                                 unit_m3(td->mtx);
2759                                                                 unit_m3(td->smtx);
2760                                                         }
2761                                                         else {
2762                                                                 /* time scaling only needs single value */
2763                                                                 td->val= &tdn->h2[0];
2764                                                                 td->ival= tdn->h2[0];
2765                                                         }
2766                                                         
2767                                                         td->extra= tdn;
2768                                                         td++;
2769                                                 }
2770                                                 
2771                                                 /* if both handles were used, skip the next tdn (i.e. leave it blank) since the counting code is dumb...
2772                                                  * otherwise, just advance to the next one...
2773                                                  */
2774                                                 if (tdn->handle == 2)
2775                                                         tdn += 2;
2776                                              &n