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