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