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