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