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