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 void pchan_autoik_adjust(bPoseChannel *pchan, short chainlen)
776 {
777         bConstraint *con;
778
779         /* don't bother to search if no valid constraints */
780         if ((pchan->constflag & (PCHAN_HAS_IK | PCHAN_HAS_TARGET)) == 0)
781                 return;
782
783         /* check if pchan has ik-constraint */
784         for (con = pchan->constraints.first; con; con = con->next) {
785                 if (con->type == CONSTRAINT_TYPE_KINEMATIC && (con->enforce != 0.0f)) {
786                         bKinematicConstraint *data = con->data;
787                         
788                         /* only accept if a temporary one (for auto-ik) */
789                         if (data->flag & CONSTRAINT_IK_TEMP) {
790                                 /* chainlen is new chainlen, but is limited by maximum chainlen */
791                                 if ((chainlen == 0) || (chainlen > data->max_rootbone))
792                                         data->rootbone = data->max_rootbone;
793                                 else
794                                         data->rootbone = chainlen;
795                         }
796                 }
797         }
798 }
799
800 /* change the chain-length of auto-ik */
801 void transform_autoik_update(TransInfo *t, short mode)
802 {
803         short *chainlen = &t->settings->autoik_chainlen;
804         bPoseChannel *pchan;
805
806         /* mode determines what change to apply to chainlen */
807         if (mode == 1) {
808                 /* mode=1 is from WHEELMOUSEDOWN... increases len */
809                 (*chainlen)++;
810         }
811         else if (mode == -1) {
812                 /* mode==-1 is from WHEELMOUSEUP... decreases len */
813                 if (*chainlen > 0) (*chainlen)--;
814         }
815
816         /* sanity checks (don't assume t->poseobj is set, or that it is an armature) */
817         if (ELEM(NULL, t->poseobj, t->poseobj->pose))
818                 return;
819
820         /* apply to all pose-channels */
821         for (pchan = t->poseobj->pose->chanbase.first; pchan; pchan = pchan->next) {
822                 pchan_autoik_adjust(pchan, *chainlen);
823         }
824 }
825
826 /* frees temporal IKs */
827 static void pose_grab_with_ik_clear(Object *ob)
828 {
829         bKinematicConstraint *data;
830         bPoseChannel *pchan;
831         bConstraint *con, *next;
832
833         for (pchan = ob->pose->chanbase.first; pchan; pchan = pchan->next) {
834                 /* clear all temporary lock flags */
835                 pchan->ikflag &= ~(BONE_IK_NO_XDOF_TEMP | BONE_IK_NO_YDOF_TEMP | BONE_IK_NO_ZDOF_TEMP);
836                 
837                 pchan->constflag &= ~(PCHAN_HAS_IK | PCHAN_HAS_TARGET);
838                 
839                 /* remove all temporary IK-constraints added */
840                 for (con = pchan->constraints.first; con; con = next) {
841                         next = con->next;
842                         if (con->type == CONSTRAINT_TYPE_KINEMATIC) {
843                                 data = con->data;
844                                 if (data->flag & CONSTRAINT_IK_TEMP) {
845                                         /* iTaSC needs clear for removed constraints */
846                                         BIK_clear_data(ob->pose);
847
848                                         BLI_remlink(&pchan->constraints, con);
849                                         MEM_freeN(con->data);
850                                         MEM_freeN(con);
851                                         continue;
852                                 }
853                                 pchan->constflag |= PCHAN_HAS_IK;
854                                 if (data->tar == NULL || (data->tar->type == OB_ARMATURE && data->subtarget[0] == 0))
855                                         pchan->constflag |= PCHAN_HAS_TARGET;
856                         }
857                 }
858         }
859
860         /* TODO(sergey): Consider doing partial update only. */
861         DEG_relations_tag_update(G.main);
862 }
863
864 /* adds the IK to pchan - returns if added */
865 static short pose_grab_with_ik_add(bPoseChannel *pchan)
866 {
867         bKinematicConstraint *targetless = NULL;
868         bKinematicConstraint *data;
869         bConstraint *con;
870
871         /* Sanity check */
872         if (pchan == NULL)
873                 return 0;
874
875         /* Rule: not if there's already an IK on this channel */
876         for (con = pchan->constraints.first; con; con = con->next) {
877                 if (con->type == CONSTRAINT_TYPE_KINEMATIC) {
878                         data = con->data;
879                         
880                         if (data->tar == NULL || (data->tar->type == OB_ARMATURE && data->subtarget[0] == '\0')) {
881                                 /* make reference to constraint to base things off later (if it's the last targetless constraint encountered) */
882                                 targetless = (bKinematicConstraint *)con->data;
883                                 
884                                 /* but, if this is a targetless IK, we make it auto anyway (for the children loop) */
885                                 if (con->enforce != 0.0f) {
886                                         data->flag |= CONSTRAINT_IK_AUTO;
887                                         
888                                         /* if no chain length has been specified, just make things obey standard rotation locks too */
889                                         if (data->rootbone == 0) {
890                                                 for (; pchan; pchan = pchan->parent) {
891                                                         /* here, we set ik-settings for bone from pchan->protectflag */
892                                                         // XXX: careful with quats/axis-angle rotations where we're locking 4d components
893                                                         if (pchan->protectflag & OB_LOCK_ROTX) pchan->ikflag |= BONE_IK_NO_XDOF_TEMP;
894                                                         if (pchan->protectflag & OB_LOCK_ROTY) pchan->ikflag |= BONE_IK_NO_YDOF_TEMP;
895                                                         if (pchan->protectflag & OB_LOCK_ROTZ) pchan->ikflag |= BONE_IK_NO_ZDOF_TEMP;
896                                                 }
897                                         }
898                                         
899                                         return 0; 
900                                 }
901                         }
902                         
903                         if ((con->flag & CONSTRAINT_DISABLE) == 0 && (con->enforce != 0.0f))
904                                 return 0;
905                 }
906         }
907
908         con = BKE_constraint_add_for_pose(NULL, pchan, "TempConstraint", CONSTRAINT_TYPE_KINEMATIC);
909         pchan->constflag |= (PCHAN_HAS_IK | PCHAN_HAS_TARGET);    /* for draw, but also for detecting while pose solving */
910         data = con->data;
911         if (targetless) {
912                 /* if exists, use values from last targetless (but disabled) IK-constraint as base */
913                 *data = *targetless;
914         }
915         else
916                 data->flag = CONSTRAINT_IK_TIP;
917         data->flag |= CONSTRAINT_IK_TEMP | CONSTRAINT_IK_AUTO | CONSTRAINT_IK_POS;
918         copy_v3_v3(data->grabtarget, pchan->pose_tail);
919         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] */
920         
921         /* we only include bones that are part of a continual connected chain */
922         do {
923                 /* here, we set ik-settings for bone from pchan->protectflag */
924                 // XXX: careful with quats/axis-angle rotations where we're locking 4d components
925                 if (pchan->protectflag & OB_LOCK_ROTX) pchan->ikflag |= BONE_IK_NO_XDOF_TEMP;
926                 if (pchan->protectflag & OB_LOCK_ROTY) pchan->ikflag |= BONE_IK_NO_YDOF_TEMP;
927                 if (pchan->protectflag & OB_LOCK_ROTZ) pchan->ikflag |= BONE_IK_NO_ZDOF_TEMP;
928                 
929                 /* now we count this pchan as being included */
930                 data->rootbone++;
931                 
932                 /* continue to parent, but only if we're connected to it */
933                 if (pchan->bone->flag & BONE_CONNECTED)
934                         pchan = pchan->parent;
935                 else
936                         pchan = NULL;
937         } while (pchan);
938
939         /* make a copy of maximum chain-length */
940         data->max_rootbone = data->rootbone;
941
942         return 1;
943 }
944
945 /* bone is a candidate to get IK, but we don't do it if it has children connected */
946 static short pose_grab_with_ik_children(bPose *pose, Bone *bone)
947 {
948         Bone *bonec;
949         short wentdeeper = 0, added = 0;
950
951         /* go deeper if children & children are connected */
952         for (bonec = bone->childbase.first; bonec; bonec = bonec->next) {
953                 if (bonec->flag & BONE_CONNECTED) {
954                         wentdeeper = 1;
955                         added += pose_grab_with_ik_children(pose, bonec);
956                 }
957         }
958         if (wentdeeper == 0) {
959                 bPoseChannel *pchan = BKE_pose_channel_find_name(pose, bone->name);
960                 if (pchan)
961                         added += pose_grab_with_ik_add(pchan);
962         }
963
964         return added;
965 }
966
967 /* main call which adds temporal IK chains */
968 static short pose_grab_with_ik(Object *ob)
969 {
970         bArmature *arm;
971         bPoseChannel *pchan, *parent;
972         Bone *bonec;
973         short tot_ik = 0;
974
975         if ((ob == NULL) || (ob->pose == NULL) || (ob->mode & OB_MODE_POSE) == 0)
976                 return 0;
977
978         arm = ob->data;
979
980         /* Rule: allow multiple Bones (but they must be selected, and only one ik-solver per chain should get added) */
981         for (pchan = ob->pose->chanbase.first; pchan; pchan = pchan->next) {
982                 if (pchan->bone->layer & arm->layer) {
983                         if (pchan->bone->flag & BONE_SELECTED) {
984                                 /* Rule: no IK for solitatry (unconnected) bones */
985                                 for (bonec = pchan->bone->childbase.first; bonec; bonec = bonec->next) {
986                                         if (bonec->flag & BONE_CONNECTED) {
987                                                 break;
988                                         }
989                                 }
990                                 if ((pchan->bone->flag & BONE_CONNECTED) == 0 && (bonec == NULL))
991                                         continue;
992
993                                 /* rule: if selected Bone is not a root bone, it gets a temporal IK */
994                                 if (pchan->parent) {
995                                         /* only adds if there's no IK yet (and no parent bone was selected) */
996                                         for (parent = pchan->parent; parent; parent = parent->parent) {
997                                                 if (parent->bone->flag & BONE_SELECTED)
998                                                         break;
999                                         }
1000                                         if (parent == NULL)
1001                                                 tot_ik += pose_grab_with_ik_add(pchan);
1002                                 }
1003                                 else {
1004                                         /* rule: go over the children and add IK to the tips */
1005                                         tot_ik += pose_grab_with_ik_children(ob->pose, pchan->bone);
1006                                 }
1007                         }
1008                 }
1009         }
1010
1011         /* iTaSC needs clear for new IK constraints */
1012         if (tot_ik) {
1013                 BIK_clear_data(ob->pose);
1014                 /* TODO(sergey): Consuder doing partial update only. */
1015                 DEG_relations_tag_update(G.main);
1016         }
1017
1018         return (tot_ik) ? 1 : 0;
1019 }
1020
1021
1022 /* only called with pose mode active object now */
1023 static void createTransPose(TransInfo *t, Object *ob)
1024 {
1025         bArmature *arm;
1026         bPoseChannel *pchan;
1027         TransData *td;
1028         TransDataExtension *tdx;
1029         short ik_on = 0;
1030         int i;
1031
1032         t->total = 0;
1033
1034         /* check validity of state */
1035         arm = BKE_armature_from_object(ob);
1036         if ((arm == NULL) || (ob->pose == NULL)) return;
1037
1038         if (arm->flag & ARM_RESTPOS) {
1039                 if (ELEM(t->mode, TFM_DUMMY, TFM_BONESIZE) == 0) {
1040                         BKE_report(t->reports, RPT_ERROR, "Cannot change Pose when 'Rest Position' is enabled");
1041                         return;
1042                 }
1043         }
1044
1045         /* do we need to add temporal IK chains? */
1046         if ((arm->flag & ARM_AUTO_IK) && t->mode == TFM_TRANSLATION) {
1047                 ik_on = pose_grab_with_ik(ob);
1048                 if (ik_on) t->flag |= T_AUTOIK;
1049         }
1050
1051         /* set flags and count total (warning, can change transform to rotate) */
1052         t->total = count_set_pose_transflags(&t->mode, t->around, ob);
1053
1054         if (t->total == 0) return;
1055
1056         t->flag |= T_POSE;
1057         t->poseobj = ob; /* we also allow non-active objects to be transformed, in weightpaint */
1058
1059         /* disable PET, its not usable in pose mode yet [#32444] */
1060         t->flag &= ~T_PROP_EDIT_ALL;
1061
1062         /* init trans data */
1063         td = t->data = MEM_callocN(t->total * sizeof(TransData), "TransPoseBone");
1064         tdx = t->ext = MEM_callocN(t->total * sizeof(TransDataExtension), "TransPoseBoneExt");
1065         for (i = 0; i < t->total; i++, td++, tdx++) {
1066                 td->ext = tdx;
1067                 td->val = NULL;
1068         }
1069
1070         /* use pose channels to fill trans data */
1071         td = t->data;
1072         for (pchan = ob->pose->chanbase.first; pchan; pchan = pchan->next) {
1073                 if (pchan->bone->flag & BONE_TRANSFORM) {
1074                         add_pose_transdata(t, pchan, ob, td);
1075                         td++;
1076                 }
1077         }
1078
1079         if (td != (t->data + t->total)) {
1080                 BKE_report(t->reports, RPT_DEBUG, "Bone selection count error");
1081         }
1082
1083         /* initialize initial auto=ik chainlen's? */
1084         if (ik_on) transform_autoik_update(t, 0);
1085 }
1086
1087 void restoreBones(TransInfo *t)
1088 {
1089         bArmature *arm = t->obedit->data;
1090         BoneInitData *bid = t->custom.type.data;
1091         EditBone *ebo;
1092
1093         while (bid->bone) {
1094                 ebo = bid->bone;
1095                 
1096                 ebo->dist = bid->dist;
1097                 ebo->rad_tail = bid->rad_tail;
1098                 ebo->roll = bid->roll;
1099                 ebo->xwidth = bid->xwidth;
1100                 ebo->zwidth = bid->zwidth;
1101                 copy_v3_v3(ebo->head, bid->head);
1102                 copy_v3_v3(ebo->tail, bid->tail);
1103                 
1104                 if (arm->flag & ARM_MIRROR_EDIT) {
1105                         EditBone *ebo_child;
1106
1107                         /* Also move connected ebo_child, in case ebo_child's name aren't mirrored properly */
1108                         for (ebo_child = arm->edbo->first; ebo_child; ebo_child = ebo_child->next) {
1109                                 if ((ebo_child->flag & BONE_CONNECTED) && (ebo_child->parent == ebo)) {
1110                                         copy_v3_v3(ebo_child->head, ebo->tail);
1111                                         ebo_child->rad_head = ebo->rad_tail;
1112                                 }
1113                         }
1114
1115                         /* Also move connected parent, in case parent's name isn't mirrored properly */
1116                         if ((ebo->flag & BONE_CONNECTED) && ebo->parent) {
1117                                 EditBone *parent = ebo->parent;
1118                                 copy_v3_v3(parent->tail, ebo->head);
1119                                 parent->rad_tail = ebo->rad_head;
1120                         }
1121                 }
1122                 
1123                 bid++;
1124         }
1125 }
1126
1127
1128 /* ********************* armature ************** */
1129 static void createTransArmatureVerts(TransInfo *t)
1130 {
1131         EditBone *ebo, *eboflip;
1132         bArmature *arm = t->obedit->data;
1133         ListBase *edbo = arm->edbo;
1134         TransData *td, *td_old;
1135         float mtx[3][3], smtx[3][3], bonemat[3][3];
1136         bool mirror = ((arm->flag & ARM_MIRROR_EDIT) != 0);
1137         int total_mirrored = 0, i;
1138         int oldtot;
1139         BoneInitData *bid;
1140         
1141         t->total = 0;
1142         for (ebo = edbo->first; ebo; ebo = ebo->next) {
1143                 oldtot = t->total;
1144
1145                 if (EBONE_VISIBLE(arm, ebo) && !(ebo->flag & BONE_EDITMODE_LOCKED)) {
1146                         if (ELEM(t->mode, TFM_BONESIZE, TFM_BONE_ENVELOPE_DIST)) {
1147                                 if (ebo->flag & BONE_SELECTED)
1148                                         t->total++;
1149                         }
1150                         else if (t->mode == TFM_BONE_ROLL) {
1151                                 if (ebo->flag & BONE_SELECTED)
1152                                         t->total++;
1153                         }
1154                         else {
1155                                 if (ebo->flag & BONE_TIPSEL)
1156                                         t->total++;
1157                                 if (ebo->flag & BONE_ROOTSEL)
1158                                         t->total++;
1159                         }
1160                 }
1161
1162                 if (mirror && (oldtot < t->total)) {
1163                         eboflip = ED_armature_bone_get_mirrored(arm->edbo, ebo);
1164                         if (eboflip)
1165                                 total_mirrored++;
1166                 }
1167         }
1168
1169         if (!t->total) return;
1170
1171         transform_around_single_fallback(t);
1172
1173         copy_m3_m4(mtx, t->obedit->obmat);
1174         pseudoinverse_m3_m3(smtx, mtx, PSEUDOINVERSE_EPSILON);
1175
1176         td = t->data = MEM_callocN(t->total * sizeof(TransData), "TransEditBone");
1177
1178         if (mirror) {
1179                 t->custom.type.data = bid = MEM_mallocN((total_mirrored + 1) * sizeof(BoneInitData), "BoneInitData");
1180                 t->custom.type.use_free = true;
1181         }
1182
1183         i = 0;
1184
1185         for (ebo = edbo->first; ebo; ebo = ebo->next) {
1186                 td_old = td;
1187                 ebo->oldlength = ebo->length;   // length==0.0 on extrude, used for scaling radius of bone points
1188
1189                 if (EBONE_VISIBLE(arm, ebo) && !(ebo->flag & BONE_EDITMODE_LOCKED)) {
1190                         if (t->mode == TFM_BONE_ENVELOPE) {
1191                                 if (ebo->flag & BONE_ROOTSEL) {
1192                                         td->val = &ebo->rad_head;
1193                                         td->ival = *td->val;
1194
1195                                         copy_v3_v3(td->center, ebo->head);
1196                                         td->flag = TD_SELECTED;
1197
1198                                         copy_m3_m3(td->smtx, smtx);
1199                                         copy_m3_m3(td->mtx, mtx);
1200
1201                                         td->loc = NULL;
1202                                         td->ext = NULL;
1203                                         td->ob = t->obedit;
1204
1205                                         td++;
1206                                 }
1207                                 if (ebo->flag & BONE_TIPSEL) {
1208                                         td->val = &ebo->rad_tail;
1209                                         td->ival = *td->val;
1210                                         copy_v3_v3(td->center, ebo->tail);
1211                                         td->flag = TD_SELECTED;
1212
1213                                         copy_m3_m3(td->smtx, smtx);
1214                                         copy_m3_m3(td->mtx, mtx);
1215
1216                                         td->loc = NULL;
1217                                         td->ext = NULL;
1218                                         td->ob = t->obedit;
1219
1220                                         td++;
1221                                 }
1222
1223                         }
1224                         else if (ELEM(t->mode, TFM_BONESIZE, TFM_BONE_ENVELOPE_DIST)) {
1225                                 if (ebo->flag & BONE_SELECTED) {
1226                                         if ((t->mode == TFM_BONE_ENVELOPE_DIST) || (arm->drawtype == ARM_ENVELOPE)) {
1227                                                 td->loc = NULL;
1228                                                 td->val = &ebo->dist;
1229                                                 td->ival = ebo->dist;
1230                                         }
1231                                         else {
1232                                                 // abusive storage of scale in the loc pointer :)
1233                                                 td->loc = &ebo->xwidth;
1234                                                 copy_v3_v3(td->iloc, td->loc);
1235                                                 td->val = NULL;
1236                                         }
1237                                         copy_v3_v3(td->center, ebo->head);
1238                                         td->flag = TD_SELECTED;
1239
1240                                         /* use local bone matrix */
1241                                         ED_armature_ebone_to_mat3(ebo, bonemat);
1242                                         mul_m3_m3m3(td->mtx, mtx, bonemat);
1243                                         invert_m3_m3(td->smtx, td->mtx);
1244
1245                                         copy_m3_m3(td->axismtx, td->mtx);
1246                                         normalize_m3(td->axismtx);
1247
1248                                         td->ext = NULL;
1249                                         td->ob = t->obedit;
1250
1251                                         td++;
1252                                 }
1253                         }
1254                         else if (t->mode == TFM_BONE_ROLL) {
1255                                 if (ebo->flag & BONE_SELECTED) {
1256                                         td->loc = NULL;
1257                                         td->val = &(ebo->roll);
1258                                         td->ival = ebo->roll;
1259
1260                                         copy_v3_v3(td->center, ebo->head);
1261                                         td->flag = TD_SELECTED;
1262
1263                                         td->ext = NULL;
1264                                         td->ob = t->obedit;
1265
1266                                         td++;
1267                                 }
1268                         }
1269                         else {
1270                                 if (ebo->flag & BONE_TIPSEL) {
1271                                         copy_v3_v3(td->iloc, ebo->tail);
1272
1273                                         /* Don't allow single selected tips to have a modified center,
1274                                          * causes problem with snapping (see T45974).
1275                                          * However, in rotation mode, we want to keep that 'rotate bone around root with
1276                                          * only its tip selected' behavior (see T46325). */
1277                                         if ((t->around == V3D_AROUND_LOCAL_ORIGINS) &&
1278                                             ((t->mode == TFM_ROTATION) || (ebo->flag & BONE_ROOTSEL)))
1279                                         {
1280                                                 copy_v3_v3(td->center, ebo->head);
1281                                         }
1282                                         else {
1283                                                 copy_v3_v3(td->center, td->iloc);
1284                                         }
1285
1286                                         td->loc = ebo->tail;
1287                                         td->flag = TD_SELECTED;
1288                                         if (ebo->flag & BONE_EDITMODE_LOCKED)
1289                                                 td->protectflag = OB_LOCK_LOC | OB_LOCK_ROT | OB_LOCK_SCALE;
1290
1291                                         copy_m3_m3(td->smtx, smtx);
1292                                         copy_m3_m3(td->mtx, mtx);
1293
1294                                         ED_armature_ebone_to_mat3(ebo, td->axismtx);
1295
1296                                         if ((ebo->flag & BONE_ROOTSEL) == 0) {
1297                                                 td->extra = ebo;
1298                                                 td->ival = ebo->roll;
1299                                         }
1300
1301                                         td->ext = NULL;
1302                                         td->val = NULL;
1303                                         td->ob = t->obedit;
1304
1305                                         td++;
1306                                 }
1307                                 if (ebo->flag & BONE_ROOTSEL) {
1308                                         copy_v3_v3(td->iloc, ebo->head);
1309                                         copy_v3_v3(td->center, td->iloc);
1310                                         td->loc = ebo->head;
1311                                         td->flag = TD_SELECTED;
1312                                         if (ebo->flag & BONE_EDITMODE_LOCKED)
1313                                                 td->protectflag = OB_LOCK_LOC | OB_LOCK_ROT | OB_LOCK_SCALE;
1314
1315                                         copy_m3_m3(td->smtx, smtx);
1316                                         copy_m3_m3(td->mtx, mtx);
1317
1318                                         ED_armature_ebone_to_mat3(ebo, td->axismtx);
1319
1320                                         td->extra = ebo; /* to fix roll */
1321                                         td->ival = ebo->roll;
1322
1323                                         td->ext = NULL;
1324                                         td->val = NULL;
1325                                         td->ob = t->obedit;
1326
1327                                         td++;
1328                                 }
1329                         }
1330                 }
1331
1332                 if (mirror && (td_old != td)) {
1333                         eboflip = ED_armature_bone_get_mirrored(arm->edbo, ebo);
1334                         if (eboflip) {
1335                                 bid[i].bone = eboflip;
1336                                 bid[i].dist = eboflip->dist;
1337                                 bid[i].rad_tail = eboflip->rad_tail;
1338                                 bid[i].roll = eboflip->roll;
1339                                 bid[i].xwidth = eboflip->xwidth;
1340                                 bid[i].zwidth = eboflip->zwidth;
1341                                 copy_v3_v3(bid[i].head, eboflip->head);
1342                                 copy_v3_v3(bid[i].tail, eboflip->tail);
1343                                 i++;
1344                         }
1345                 }
1346         }
1347
1348         if (mirror) {
1349                 /* trick to terminate iteration */
1350                 bid[total_mirrored].bone = NULL;
1351         }
1352 }
1353
1354 /* ********************* meta elements ********* */
1355
1356 static void createTransMBallVerts(TransInfo *t)
1357 {
1358         MetaBall *mb = (MetaBall *)t->obedit->data;
1359         MetaElem *ml;
1360         TransData *td;
1361         TransDataExtension *tx;
1362         float mtx[3][3], smtx[3][3];
1363         int count = 0, countsel = 0;
1364         const bool is_prop_edit = (t->flag & T_PROP_EDIT) != 0;
1365
1366         /* count totals */
1367         for (ml = mb->editelems->first; ml; ml = ml->next) {
1368                 if (ml->flag & SELECT) countsel++;
1369                 if (is_prop_edit) count++;
1370         }
1371
1372         /* note: in prop mode we need at least 1 selected */
1373         if (countsel == 0) return;
1374
1375         if (is_prop_edit) t->total = count;
1376         else t->total = countsel;
1377
1378         td = t->data = MEM_callocN(t->total * sizeof(TransData), "TransObData(MBall EditMode)");
1379         tx = t->ext = MEM_callocN(t->total * sizeof(TransDataExtension), "MetaElement_TransExtension");
1380
1381         copy_m3_m4(mtx, t->obedit->obmat);
1382         pseudoinverse_m3_m3(smtx, mtx, PSEUDOINVERSE_EPSILON);
1383
1384         for (ml = mb->editelems->first; ml; ml = ml->next) {
1385                 if (is_prop_edit || (ml->flag & SELECT)) {
1386                         td->loc = &ml->x;
1387                         copy_v3_v3(td->iloc, td->loc);
1388                         copy_v3_v3(td->center, td->loc);
1389
1390                         quat_to_mat3(td->axismtx, ml->quat);
1391
1392                         if (ml->flag & SELECT) td->flag = TD_SELECTED | TD_USEQUAT | TD_SINGLESIZE;
1393                         else td->flag = TD_USEQUAT;
1394
1395                         copy_m3_m3(td->smtx, smtx);
1396                         copy_m3_m3(td->mtx, mtx);
1397
1398                         td->ext = tx;
1399
1400                         /* Radius of MetaElem (mass of MetaElem influence) */
1401                         if (ml->flag & MB_SCALE_RAD) {
1402                                 td->val = &ml->rad;
1403                                 td->ival = ml->rad;
1404                         }
1405                         else {
1406                                 td->val = &ml->s;
1407                                 td->ival = ml->s;
1408                         }
1409
1410                         /* expx/expy/expz determine "shape" of some MetaElem types */
1411                         tx->size = &ml->expx;
1412                         tx->isize[0] = ml->expx;
1413                         tx->isize[1] = ml->expy;
1414                         tx->isize[2] = ml->expz;
1415
1416                         /* quat is used for rotation of MetaElem */
1417                         tx->quat = ml->quat;
1418                         copy_qt_qt(tx->iquat, ml->quat);
1419
1420                         tx->rot = NULL;
1421
1422                         td++;
1423                         tx++;
1424                 }
1425         }
1426 }
1427
1428 /* ********************* curve/surface ********* */
1429
1430 static void calc_distanceCurveVerts(TransData *head, TransData *tail)
1431 {
1432         TransData *td, *td_near = NULL;
1433         for (td = head; td <= tail; td++) {
1434                 if (td->flag & TD_SELECTED) {
1435                         td_near = td;
1436                         td->dist = 0.0f;
1437                 }
1438                 else if (td_near) {
1439                         float dist;
1440                         dist = len_v3v3(td_near->center, td->center);
1441                         if (dist < (td - 1)->dist) {
1442                                 td->dist = (td - 1)->dist;
1443                         }
1444                         else {
1445                                 td->dist = dist;
1446                         }
1447                 }
1448                 else {
1449                         td->dist = FLT_MAX;
1450                         td->flag |= TD_NOTCONNECTED;
1451                 }
1452         }
1453         td_near = NULL;
1454         for (td = tail; td >= head; td--) {
1455                 if (td->flag & TD_SELECTED) {
1456                         td_near = td;
1457                         td->dist = 0.0f;
1458                 }
1459                 else if (td_near) {
1460                         float dist;
1461                         dist = len_v3v3(td_near->center, td->center);
1462                         if (td->flag & TD_NOTCONNECTED || dist < td->dist || (td + 1)->dist < td->dist) {
1463                                 td->flag &= ~TD_NOTCONNECTED;
1464                                 if (dist < (td + 1)->dist) {
1465                                         td->dist = (td + 1)->dist;
1466                                 }
1467                                 else {
1468                                         td->dist = dist;
1469                                 }
1470                         }
1471                 }
1472         }
1473 }
1474
1475 /* Utility function for getting the handle data from bezier's */
1476 static TransDataCurveHandleFlags *initTransDataCurveHandles(TransData *td, struct BezTriple *bezt)
1477 {
1478         TransDataCurveHandleFlags *hdata;
1479         td->flag |= TD_BEZTRIPLE;
1480         hdata = td->hdata = MEM_mallocN(sizeof(TransDataCurveHandleFlags), "CuHandle Data");
1481         hdata->ih1 = bezt->h1;
1482         hdata->h1 = &bezt->h1;
1483         hdata->ih2 = bezt->h2; /* in case the second is not selected */
1484         hdata->h2 = &bezt->h2;
1485         return hdata;
1486 }
1487
1488 static void createTransCurveVerts(TransInfo *t)
1489 {
1490         Curve *cu = t->obedit->data;
1491         TransData *td = NULL;
1492         Nurb *nu;
1493         BezTriple *bezt;
1494         BPoint *bp;
1495         float mtx[3][3], smtx[3][3];
1496         int a;
1497         int count = 0, countsel = 0;
1498         const bool is_prop_edit = (t->flag & T_PROP_EDIT) != 0;
1499         short hide_handles = (cu->drawflag & CU_HIDE_HANDLES);
1500         ListBase *nurbs;
1501
1502         /* to be sure */
1503         if (cu->editnurb == NULL) return;
1504
1505         /* count total of vertices, check identical as in 2nd loop for making transdata! */
1506         nurbs = BKE_curve_editNurbs_get(cu);
1507         for (nu = nurbs->first; nu; nu = nu->next) {
1508                 if (nu->type == CU_BEZIER) {
1509                         for (a = 0, bezt = nu->bezt; a < nu->pntsu; a++, bezt++) {
1510                                 if (bezt->hide == 0) {
1511                                         if (hide_handles) {
1512                                                 if (bezt->f2 & SELECT) countsel += 3;
1513                                                 if (is_prop_edit) count += 3;
1514                                         }
1515                                         else {
1516                                                 if (bezt->f1 & SELECT) countsel++;
1517                                                 if (bezt->f2 & SELECT) countsel++;
1518                                                 if (bezt->f3 & SELECT) countsel++;
1519                                                 if (is_prop_edit) count += 3;
1520                                         }
1521                                 }
1522                         }
1523                 }
1524                 else {
1525                         for (a = nu->pntsu * nu->pntsv, bp = nu->bp; a > 0; a--, bp++) {
1526                                 if (bp->hide == 0) {
1527                                         if (is_prop_edit) count++;
1528                                         if (bp->f1 & SELECT) countsel++;
1529                                 }
1530                         }
1531                 }
1532         }
1533         /* note: in prop mode we need at least 1 selected */
1534         if (countsel == 0) return;
1535
1536         if (is_prop_edit) t->total = count;
1537         else t->total = countsel;
1538         t->data = MEM_callocN(t->total * sizeof(TransData), "TransObData(Curve EditMode)");
1539
1540         transform_around_single_fallback(t);
1541
1542         copy_m3_m4(mtx, t->obedit->obmat);
1543         pseudoinverse_m3_m3(smtx, mtx, PSEUDOINVERSE_EPSILON);
1544
1545         td = t->data;
1546         for (nu = nurbs->first; nu; nu = nu->next) {
1547                 if (nu->type == CU_BEZIER) {
1548                         TransData *head, *tail;
1549                         head = tail = td;
1550                         for (a = 0, bezt = nu->bezt; a < nu->pntsu; a++, bezt++) {
1551                                 if (bezt->hide == 0) {
1552                                         TransDataCurveHandleFlags *hdata = NULL;
1553                                         float axismtx[3][3];
1554
1555                                         if (t->around == V3D_AROUND_LOCAL_ORIGINS) {
1556                                                 float normal[3], plane[3];
1557
1558                                                 BKE_nurb_bezt_calc_normal(nu, bezt, normal);
1559                                                 BKE_nurb_bezt_calc_plane(nu, bezt, plane);
1560
1561                                                 if (createSpaceNormalTangent(axismtx, normal, plane)) {
1562                                                         /* pass */
1563                                                 }
1564                                                 else {
1565                                                         normalize_v3(normal);
1566                                                         axis_dominant_v3_to_m3(axismtx, normal);
1567                                                         invert_m3(axismtx);
1568                                                 }
1569                                         }
1570
1571                                         if (is_prop_edit ||
1572                                             ((bezt->f2 & SELECT) && hide_handles) ||
1573                                             ((bezt->f1 & SELECT) && hide_handles == 0))
1574                                         {
1575                                                 copy_v3_v3(td->iloc, bezt->vec[0]);
1576                                                 td->loc = bezt->vec[0];
1577                                                 copy_v3_v3(td->center, bezt->vec[(hide_handles ||
1578                                                                                   (t->around == V3D_AROUND_LOCAL_ORIGINS) ||
1579                                                                                   (bezt->f2 & SELECT)) ? 1 : 0]);
1580                                                 if (hide_handles) {
1581                                                         if (bezt->f2 & SELECT) td->flag = TD_SELECTED;
1582                                                         else td->flag = 0;
1583                                                 }
1584                                                 else {
1585                                                         if (bezt->f1 & SELECT) td->flag = TD_SELECTED;
1586                                                         else td->flag = 0;
1587                                                 }
1588                                                 td->ext = NULL;
1589                                                 td->val = NULL;
1590
1591                                                 hdata = initTransDataCurveHandles(td, bezt);
1592
1593                                                 copy_m3_m3(td->smtx, smtx);
1594                                                 copy_m3_m3(td->mtx, mtx);
1595                                                 if (t->around == V3D_AROUND_LOCAL_ORIGINS) {
1596                                                         copy_m3_m3(td->axismtx, axismtx);
1597                                                 }
1598
1599                                                 td++;
1600                                                 count++;
1601                                                 tail++;
1602                                         }
1603
1604                                         /* This is the Curve Point, the other two are handles */
1605                                         if (is_prop_edit || (bezt->f2 & SELECT)) {
1606                                                 copy_v3_v3(td->iloc, bezt->vec[1]);
1607                                                 td->loc = bezt->vec[1];
1608                                                 copy_v3_v3(td->center, td->loc);
1609                                                 if (bezt->f2 & SELECT) td->flag = TD_SELECTED;
1610                                                 else td->flag = 0;
1611                                                 td->ext = NULL;
1612
1613                                                 if (t->mode == TFM_CURVE_SHRINKFATTEN) { /* || t->mode==TFM_RESIZE) {*/ /* TODO - make points scale */
1614                                                         td->val = &(bezt->radius);
1615                                                         td->ival = bezt->radius;
1616                                                 }
1617                                                 else if (t->mode == TFM_TILT) {
1618                                                         td->val = &(bezt->alfa);
1619                                                         td->ival = bezt->alfa;
1620                                                 }
1621                                                 else {
1622                                                         td->val = NULL;
1623                                                 }
1624
1625                                                 copy_m3_m3(td->smtx, smtx);
1626                                                 copy_m3_m3(td->mtx, mtx);
1627                                                 if (t->around == V3D_AROUND_LOCAL_ORIGINS) {
1628                                                         copy_m3_m3(td->axismtx, axismtx);
1629                                                 }
1630
1631                                                 if ((bezt->f1 & SELECT) == 0 && (bezt->f3 & SELECT) == 0)
1632                                                         /* If the middle is selected but the sides arnt, this is needed */
1633                                                         if (hdata == NULL) { /* if the handle was not saved by the previous handle */
1634                                                                 hdata = initTransDataCurveHandles(td, bezt);
1635                                                         }
1636
1637                                                 td++;
1638                                                 count++;
1639                                                 tail++;
1640                                         }
1641                                         if (is_prop_edit ||
1642                                             ((bezt->f2 & SELECT) && hide_handles) ||
1643                                             ((bezt->f3 & SELECT) && hide_handles == 0))
1644                                         {
1645                                                 copy_v3_v3(td->iloc, bezt->vec[2]);
1646                                                 td->loc = bezt->vec[2];
1647                                                 copy_v3_v3(td->center, bezt->vec[(hide_handles ||
1648                                                                                   (t->around == V3D_AROUND_LOCAL_ORIGINS) ||
1649                                                                                   (bezt->f2 & SELECT)) ? 1 : 2]);
1650                                                 if (hide_handles) {
1651                                                         if (bezt->f2 & SELECT) td->flag = TD_SELECTED;
1652                                                         else td->flag = 0;
1653                                                 }
1654                                                 else {
1655                                                         if (bezt->f3 & SELECT) td->flag = TD_SELECTED;
1656                                                         else td->flag = 0;
1657                                                 }
1658                                                 td->ext = NULL;
1659                                                 td->val = NULL;
1660
1661                                                 if (hdata == NULL) { /* if the handle was not saved by the previous handle */
1662                                                         hdata = initTransDataCurveHandles(td, bezt);
1663                                                 }
1664
1665                                                 copy_m3_m3(td->smtx, smtx);
1666                                                 copy_m3_m3(td->mtx, mtx);
1667                                                 if (t->around == V3D_AROUND_LOCAL_ORIGINS) {
1668                                                         copy_m3_m3(td->axismtx, axismtx);
1669                                                 }
1670
1671                                                 td++;
1672                                                 count++;
1673                                                 tail++;
1674                                         }
1675
1676                                         (void)hdata;  /* quiet warning */
1677                                 }
1678                                 else if (is_prop_edit && head != tail) {
1679                                         calc_distanceCurveVerts(head, tail - 1);
1680                                         head = tail;
1681                                 }
1682                         }
1683                         if (is_prop_edit && head != tail)
1684                                 calc_distanceCurveVerts(head, tail - 1);
1685
1686                         /* TODO - in the case of tilt and radius we can also avoid allocating the initTransDataCurveHandles
1687                          * but for now just don't change handle types */
1688                         if (ELEM(t->mode, TFM_CURVE_SHRINKFATTEN, TFM_TILT, TFM_DUMMY) == 0) {
1689                                 /* sets the handles based on their selection, do this after the data is copied to the TransData */
1690                                 BKE_nurb_handles_test(nu, !hide_handles);
1691                         }
1692                 }
1693                 else {
1694                         TransData *head, *tail;
1695                         head = tail = td;
1696                         for (a = nu->pntsu * nu->pntsv, bp = nu->bp; a > 0; a--, bp++) {
1697                                 if (bp->hide == 0) {
1698                                         if (is_prop_edit || (bp->f1 & SELECT)) {
1699                                                 copy_v3_v3(td->iloc, bp->vec);
1700                                                 td->loc = bp->vec;
1701                                                 copy_v3_v3(td->center, td->loc);
1702                                                 if (bp->f1 & SELECT) td->flag = TD_SELECTED;
1703                                                 else td->flag = 0;
1704                                                 td->ext = NULL;
1705
1706                                                 if (t->mode == TFM_CURVE_SHRINKFATTEN || t->mode == TFM_RESIZE) {
1707                                                         td->val = &(bp->radius);
1708                                                         td->ival = bp->radius;
1709                                                 }
1710                                                 else {
1711                                                         td->val = &(bp->alfa);
1712                                                         td->ival = bp->alfa;
1713                                                 }
1714
1715                                                 copy_m3_m3(td->smtx, smtx);
1716                                                 copy_m3_m3(td->mtx, mtx);
1717
1718                                                 td++;
1719                                                 count++;
1720                                                 tail++;
1721                                         }
1722                                 }
1723                                 else if (is_prop_edit && head != tail) {
1724                                         calc_distanceCurveVerts(head, tail - 1);
1725                                         head = tail;
1726                                 }
1727                         }
1728                         if (is_prop_edit && head != tail)
1729                                 calc_distanceCurveVerts(head, tail - 1);
1730                 }
1731         }
1732 }
1733
1734 /* ********************* lattice *************** */
1735
1736 static void createTransLatticeVerts(TransInfo *t)
1737 {
1738         Lattice *latt = ((Lattice *)t->obedit->data)->editlatt->latt;
1739         TransData *td = NULL;
1740         BPoint *bp;
1741         float mtx[3][3], smtx[3][3];
1742         int a;
1743         int count = 0, countsel = 0;
1744         const bool is_prop_edit = (t->flag & T_PROP_EDIT) != 0;
1745
1746         bp = latt->def;
1747         a  = latt->pntsu * latt->pntsv * latt->pntsw;
1748         while (a--) {
1749                 if (bp->hide == 0) {
1750                         if (bp->f1 & SELECT) countsel++;
1751                         if (is_prop_edit) count++;
1752                 }
1753                 bp++;
1754         }
1755
1756         /* note: in prop mode we need at least 1 selected */
1757         if (countsel == 0) return;
1758
1759         if (is_prop_edit) t->total = count;
1760         else t->total = countsel;
1761         t->data = MEM_callocN(t->total * sizeof(TransData), "TransObData(Lattice EditMode)");
1762
1763         copy_m3_m4(mtx, t->obedit->obmat);
1764         pseudoinverse_m3_m3(smtx, mtx, PSEUDOINVERSE_EPSILON);
1765
1766         td = t->data;
1767         bp = latt->def;
1768         a  = latt->pntsu * latt->pntsv * latt->pntsw;
1769         while (a--) {
1770                 if (is_prop_edit || (bp->f1 & SELECT)) {
1771                         if (bp->hide == 0) {
1772                                 copy_v3_v3(td->iloc, bp->vec);
1773                                 td->loc = bp->vec;
1774                                 copy_v3_v3(td->center, td->loc);
1775                                 if (bp->f1 & SELECT) {
1776                                         td->flag = TD_SELECTED;
1777                                 }
1778                                 else {
1779                                         td->flag = 0;
1780                                 }
1781                                 copy_m3_m3(td->smtx, smtx);
1782                                 copy_m3_m3(td->mtx, mtx);
1783
1784                                 td->ext = NULL;
1785                                 td->val = NULL;
1786
1787                                 td++;
1788                                 count++;
1789                         }
1790                 }
1791                 bp++;
1792         }
1793 }
1794
1795 /* ******************* particle edit **************** */
1796 static void createTransParticleVerts(bContext *C, TransInfo *t)
1797 {
1798         TransData *td = NULL;
1799         TransDataExtension *tx;
1800         Base *base = CTX_data_active_base(C);
1801         Object *ob = CTX_data_active_object(C);
1802         ParticleEditSettings *pset = PE_settings(t->scene);
1803         PTCacheEdit *edit = PE_get_current(t->scene, t->scene_layer, ob);
1804         ParticleSystem *psys = NULL;
1805         ParticleSystemModifierData *psmd = NULL;
1806         PTCacheEditPoint *point;
1807         PTCacheEditKey *key;
1808         float mat[4][4];
1809         int i, k, transformparticle;
1810         int count = 0, hasselected = 0;
1811         const bool is_prop_edit = (t->flag & T_PROP_EDIT) != 0;
1812
1813         if (edit == NULL || t->settings->particle.selectmode == SCE_SELECT_PATH) return;
1814
1815         psys = edit->psys;
1816
1817         if (psys)
1818                 psmd = psys_get_modifier(ob, psys);
1819
1820         base->flag |= BA_HAS_RECALC_DATA;
1821
1822         for (i = 0, point = edit->points; i < edit->totpoint; i++, point++) {
1823                 point->flag &= ~PEP_TRANSFORM;
1824                 transformparticle = 0;
1825
1826                 if ((point->flag & PEP_HIDE) == 0) {
1827                         for (k = 0, key = point->keys; k < point->totkey; k++, key++) {
1828                                 if ((key->flag & PEK_HIDE) == 0) {
1829                                         if (key->flag & PEK_SELECT) {
1830                                                 hasselected = 1;
1831                                                 transformparticle = 1;
1832                                         }
1833                                         else if (is_prop_edit)
1834                                                 transformparticle = 1;
1835                                 }
1836                         }
1837                 }
1838
1839                 if (transformparticle) {
1840                         count += point->totkey;
1841                         point->flag |= PEP_TRANSFORM;
1842                 }
1843         }
1844
1845         /* note: in prop mode we need at least 1 selected */
1846         if (hasselected == 0) return;
1847
1848         t->total = count;
1849         td = t->data = MEM_callocN(t->total * sizeof(TransData), "TransObData(Particle Mode)");
1850
1851         if (t->mode == TFM_BAKE_TIME)
1852                 tx = t->ext = MEM_callocN(t->total * sizeof(TransDataExtension), "Particle_TransExtension");
1853         else
1854                 tx = t->ext = NULL;
1855
1856         unit_m4(mat);
1857
1858         invert_m4_m4(ob->imat, ob->obmat);
1859
1860         for (i = 0, point = edit->points; i < edit->totpoint; i++, point++) {
1861                 TransData *head, *tail;
1862                 head = tail = td;
1863
1864                 if (!(point->flag & PEP_TRANSFORM)) continue;
1865
1866                 if (psys && !(psys->flag & PSYS_GLOBAL_HAIR))
1867                         psys_mat_hair_to_global(ob, psmd->dm_final, psys->part->from, psys->particles + i, mat);
1868
1869                 for (k = 0, key = point->keys; k < point->totkey; k++, key++) {
1870                         if (key->flag & PEK_USE_WCO) {
1871                                 copy_v3_v3(key->world_co, key->co);
1872                                 mul_m4_v3(mat, key->world_co);
1873                                 td->loc = key->world_co;
1874                         }
1875                         else
1876                                 td->loc = key->co;
1877
1878                         copy_v3_v3(td->iloc, td->loc);
1879                         copy_v3_v3(td->center, td->loc);
1880
1881                         if (key->flag & PEK_SELECT)
1882                                 td->flag |= TD_SELECTED;
1883                         else if (!is_prop_edit)
1884                                 td->flag |= TD_SKIP;
1885
1886                         unit_m3(td->mtx);
1887                         unit_m3(td->smtx);
1888
1889                         /* don't allow moving roots */
1890                         if (k == 0 && pset->flag & PE_LOCK_FIRST && (!psys || !(psys->flag & PSYS_GLOBAL_HAIR)))
1891                                 td->protectflag |= OB_LOCK_LOC;
1892
1893                         td->ob = ob;
1894                         td->ext = tx;
1895                         if (t->mode == TFM_BAKE_TIME) {
1896                                 td->val = key->time;
1897                                 td->ival = *(key->time);
1898                                 /* abuse size and quat for min/max values */
1899                                 td->flag |= TD_NO_EXT;
1900                                 if (k == 0) tx->size = NULL;
1901                                 else tx->size = (key - 1)->time;
1902
1903                                 if (k == point->totkey - 1) tx->quat = NULL;
1904                                 else tx->quat = (key + 1)->time;
1905                         }
1906
1907                         td++;
1908                         if (tx)
1909                                 tx++;
1910                         tail++;
1911                 }
1912                 if (is_prop_edit && head != tail)
1913                         calc_distanceCurveVerts(head, tail - 1);
1914         }
1915 }
1916
1917 void flushTransParticles(TransInfo *t)
1918 {
1919         Scene *scene = t->scene;
1920         SceneLayer *sl = t->scene_layer;
1921         Object *ob = OBACT_NEW;
1922         PTCacheEdit *edit = PE_get_current(scene, sl, ob);
1923         ParticleSystem *psys = edit->psys;
1924         ParticleSystemModifierData *psmd = NULL;
1925         PTCacheEditPoint *point;
1926         PTCacheEditKey *key;
1927         TransData *td;
1928         float mat[4][4], imat[4][4], co[3];
1929         int i, k;
1930         const bool is_prop_edit = (t->flag & T_PROP_EDIT) != 0;
1931
1932         if (psys)
1933                 psmd = psys_get_modifier(ob, psys);
1934
1935         /* we do transform in world space, so flush world space position
1936          * back to particle local space (only for hair particles) */
1937         td = t->data;
1938         for (i = 0, point = edit->points; i < edit->totpoint; i++, point++, td++) {
1939                 if (!(point->flag & PEP_TRANSFORM)) continue;
1940
1941                 if (psys && !(psys->flag & PSYS_GLOBAL_HAIR)) {
1942                         psys_mat_hair_to_global(ob, psmd->dm_final, psys->part->from, psys->particles + i, mat);
1943                         invert_m4_m4(imat, mat);
1944
1945                         for (k = 0, key = point->keys; k < point->totkey; k++, key++) {
1946                                 copy_v3_v3(co, key->world_co);
1947                                 mul_m4_v3(imat, co);
1948
1949
1950                                 /* optimization for proportional edit */
1951                                 if (!is_prop_edit || !compare_v3v3(key->co, co, 0.0001f)) {
1952                                         copy_v3_v3(key->co, co);
1953                                         point->flag |= PEP_EDIT_RECALC;
1954                                 }
1955                         }
1956                 }
1957                 else
1958                         point->flag |= PEP_EDIT_RECALC;
1959         }
1960
1961         PE_update_object(scene, sl, OBACT_NEW, 1);
1962 }
1963
1964 /* ********************* mesh ****************** */
1965
1966 static bool bmesh_test_dist_add(
1967         BMVert *v, BMVert *v_other,
1968         float *dists, const float *dists_prev,
1969         /* optionally track original index */
1970         int *index, const int *index_prev,
1971         float mtx[3][3])
1972 {
1973         if ((BM_elem_flag_test(v_other, BM_ELEM_SELECT) == 0) &&
1974             (BM_elem_flag_test(v_other, BM_ELEM_HIDDEN) == 0))
1975         {
1976                 const int i = BM_elem_index_get(v);
1977                 const int i_other = BM_elem_index_get(v_other);
1978                 float vec[3];
1979                 float dist_other;
1980                 sub_v3_v3v3(vec, v->co, v_other->co);
1981                 mul_m3_v3(mtx, vec);
1982
1983                 dist_other = dists_prev[i] + len_v3(vec);
1984                 if (dist_other < dists[i_other]) {
1985                         dists[i_other] = dist_other;
1986                         if (index != NULL) {
1987                                 index[i_other] = index_prev[i];
1988                         }
1989                         return true;
1990                 }
1991         }
1992
1993         return false;
1994 }
1995
1996 /**
1997  * \parm mtx: Measure disatnce in this space.
1998  * \parm dists: Store the closest connected distance to selected vertices.
1999  * \parm index: Optionally store the original index we're measuring the distance to (can be NULL).
2000  */
2001 static void editmesh_set_connectivity_distance(BMesh *bm, float mtx[3][3], float *dists, int *index)
2002 {
2003         BLI_LINKSTACK_DECLARE(queue, BMVert *);
2004
2005         /* any BM_ELEM_TAG'd vertex is in 'queue_next', so we don't add in twice */
2006         BLI_LINKSTACK_DECLARE(queue_next, BMVert *);
2007
2008         BLI_LINKSTACK_INIT(queue);
2009         BLI_LINKSTACK_INIT(queue_next);
2010
2011         {
2012                 BMIter viter;
2013                 BMVert *v;
2014                 int i;
2015
2016                 BM_ITER_MESH_INDEX (v, &viter, bm, BM_VERTS_OF_MESH, i) {
2017                         float dist;
2018                         BM_elem_index_set(v, i); /* set_inline */
2019                         BM_elem_flag_disable(v, BM_ELEM_TAG);
2020
2021                         if (BM_elem_flag_test(v, BM_ELEM_SELECT) == 0 || BM_elem_flag_test(v, BM_ELEM_HIDDEN)) {
2022                                 dist = FLT_MAX;
2023                                 if (index != NULL) {
2024                                         index[i] = i;
2025                                 }
2026                         }
2027                         else {
2028                                 BLI_LINKSTACK_PUSH(queue, v);
2029                                 dist = 0.0f;
2030                                 if (index != NULL) {
2031                                         index[i] = i;
2032                                 }
2033                         }
2034
2035                         dists[i] = dist;
2036                 }
2037                 bm->elem_index_dirty &= ~BM_VERT;
2038         }
2039
2040         /* need to be very careful of feedback loops here, store previous dist's to avoid feedback */
2041         float *dists_prev = MEM_dupallocN(dists);
2042         int *index_prev = MEM_dupallocN(index);  /* may be NULL */
2043
2044         do {
2045                 BMVert *v;
2046                 LinkNode *lnk;
2047
2048                 /* this is correct but slow to do each iteration,
2049                  * instead sync the dist's while clearing BM_ELEM_TAG (below) */
2050 #if 0
2051                 memcpy(dists_prev, dists, sizeof(float) * bm->totvert);
2052 #endif
2053
2054                 while ((v = BLI_LINKSTACK_POP(queue))) {
2055                         BLI_assert(dists[BM_elem_index_get(v)] != FLT_MAX);
2056
2057                         /* connected edge-verts */
2058                         if (v->e != NULL) {
2059                                 BMEdge *e_iter, *e_first;
2060
2061                                 e_iter = e_first = v->e;
2062
2063                                 /* would normally use BM_EDGES_OF_VERT, but this runs so often,
2064                                  * its faster to iterate on the data directly */
2065                                 do {
2066
2067                                         if (BM_elem_flag_test(e_iter, BM_ELEM_HIDDEN) == 0) {
2068
2069                                                 /* edge distance */
2070                                                 {
2071                                                         BMVert *v_other = BM_edge_other_vert(e_iter, v);
2072                                                         if (bmesh_test_dist_add(v, v_other, dists, dists_prev, index, index_prev, mtx)) {
2073                                                                 if (BM_elem_flag_test(v_other, BM_ELEM_TAG) == 0) {
2074                                                                         BM_elem_flag_enable(v_other, BM_ELEM_TAG);
2075                                                                         BLI_LINKSTACK_PUSH(queue_next, v_other);
2076                                                                 }
2077                                                         }
2078                                                 }
2079
2080                                                 /* face distance */
2081                                                 if (e_iter->l) {
2082                                                         BMLoop *l_iter_radial, *l_first_radial;
2083                                                         /**
2084                                                          * imaginary edge diagonally across quad,
2085                                                          * \note, this takes advantage of the rules of winding that we
2086                                                          * know 2 or more of a verts edges wont reference the same face twice.
2087                                                          * Also, if the edge is hidden, the face will be hidden too.
2088                                                          */
2089                                                         l_iter_radial = l_first_radial = e_iter->l;
2090
2091                                                         do {
2092                                                                 if ((l_iter_radial->v == v) &&
2093                                                                     (l_iter_radial->f->len == 4) &&
2094                                                                     (BM_elem_flag_test(l_iter_radial->f, BM_ELEM_HIDDEN) == 0))
2095                                                                 {
2096                                                                         BMVert *v_other = l_iter_radial->next->next->v;
2097                                                                         if (bmesh_test_dist_add(v, v_other, dists, dists_prev, index, index_prev, mtx)) {
2098                                                                                 if (BM_elem_flag_test(v_other, BM_ELEM_TAG) == 0) {
2099                                                                                         BM_elem_flag_enable(v_other, BM_ELEM_TAG);
2100                                                                                         BLI_LINKSTACK_PUSH(queue_next, v_other);
2101                                                                                 }
2102                                                                         }
2103                                                                 }
2104                                                         } while ((l_iter_radial = l_iter_radial->radial_next) != l_first_radial);
2105                                                 }
2106                                         }
2107                                 } while ((e_iter = BM_DISK_EDGE_NEXT(e_iter, v)) != e_first);
2108                         }
2109                 }
2110
2111
2112                 /* clear for the next loop */
2113                 for (lnk = queue_next; lnk; lnk = lnk->next) {
2114                         BMVert *v_link = lnk->link;
2115                         const int i = BM_elem_index_get(v_link);
2116
2117                         BM_elem_flag_disable(v_link, BM_ELEM_TAG);
2118
2119                         /* keep in sync, avoid having to do full memcpy each iteration */
2120                         dists_prev[i] = dists[i];
2121                         if (index != NULL) {
2122                                 index_prev[i] = index[i];
2123                         }
2124                 }
2125
2126                 BLI_LINKSTACK_SWAP(queue, queue_next);
2127
2128                 /* none should be tagged now since 'queue_next' is empty */
2129                 BLI_assert(BM_iter_mesh_count_flag(BM_VERTS_OF_MESH, bm, BM_ELEM_TAG, true) == 0);
2130
2131         } while (BLI_LINKSTACK_SIZE(queue));
2132
2133         BLI_LINKSTACK_FREE(queue);
2134         BLI_LINKSTACK_FREE(queue_next);
2135
2136         MEM_freeN(dists_prev);
2137         if (index_prev != NULL) {
2138                 MEM_freeN(index_prev);
2139         }
2140 }
2141
2142 static struct TransIslandData *editmesh_islands_info_calc(
2143         BMEditMesh *em, int *r_island_tot, int **r_island_vert_map,
2144         bool calc_single_islands)
2145 {
2146         BMesh *bm = em->bm;
2147         struct TransIslandData *trans_islands;
2148         char htype;
2149         char itype;
2150         int i;
2151
2152         /* group vars */
2153         int *groups_array;
2154         int (*group_index)[2];
2155         int group_tot;
2156         void **ele_array;
2157
2158         int *vert_map;
2159
2160         if (em->selectmode & (SCE_SELECT_VERTEX | SCE_SELECT_EDGE)) {
2161                 groups_array = MEM_mallocN(sizeof(*groups_array) * bm->totedgesel, __func__);
2162                 group_tot = BM_mesh_calc_edge_groups(bm, groups_array, &group_index,
2163                                                      NULL, NULL,
2164                                                      BM_ELEM_SELECT);
2165
2166                 htype = BM_EDGE;
2167                 itype = BM_VERTS_OF_EDGE;
2168
2169         }
2170         else {  /* (bm->selectmode & SCE_SELECT_FACE) */
2171                 groups_array = MEM_mallocN(sizeof(*groups_array) * bm->totfacesel, __func__);
2172                 group_tot = BM_mesh_calc_face_groups(bm, groups_array, &group_index,
2173                                                      NULL, NULL,
2174                                                      BM_ELEM_SELECT, BM_VERT);
2175
2176                 htype = BM_FACE;
2177                 itype = BM_VERTS_OF_FACE;
2178         }
2179
2180
2181         trans_islands = MEM_mallocN(sizeof(*trans_islands) * group_tot, __func__);
2182
2183         vert_map = MEM_mallocN(sizeof(*vert_map) * bm->totvert, __func__);
2184         /* we shouldn't need this, but with incorrect selection flushing
2185          * its possible we have a selected vertex thats not in a face, for now best not crash in that case. */
2186         copy_vn_i(vert_map, bm->totvert, -1);
2187
2188         BM_mesh_elem_table_ensure(bm, htype);
2189         ele_array = (htype == BM_FACE) ? (void **)bm->ftable : (void **)bm->etable;
2190
2191         BM_mesh_elem_index_ensure(bm, BM_VERT);
2192
2193         /* may be an edge OR a face array */
2194         for (i = 0; i < group_tot; i++) {
2195                 BMEditSelection ese = {NULL};
2196
2197                 const int fg_sta = group_index[i][0];
2198                 const int fg_len = group_index[i][1];
2199                 float co[3], no[3], tangent[3];
2200                 int j;
2201
2202                 zero_v3(co);
2203                 zero_v3(no);
2204                 zero_v3(tangent);
2205
2206                 ese.htype = htype;
2207
2208                 /* loop on each face in this group:
2209                  * - assign r_vert_map
2210                  * - calculate (co, no)
2211                  */
2212                 for (j = 0; j < fg_len; j++) {
2213                         float tmp_co[3], tmp_no[3], tmp_tangent[3];
2214
2215                         ese.ele = ele_array[groups_array[fg_sta + j]];
2216
2217                         BM_editselection_center(&ese, tmp_co);
2218                         BM_editselection_normal(&ese, tmp_no);
2219                         BM_editselection_plane(&ese, tmp_tangent);
2220
2221                         add_v3_v3(co, tmp_co);
2222                         add_v3_v3(no, tmp_no);
2223                         add_v3_v3(tangent, tmp_tangent);
2224
2225                         {
2226                                 /* setup vertex map */
2227                                 BMIter iter;
2228                                 BMVert *v;
2229
2230                                 /* connected edge-verts */
2231                                 BM_ITER_ELEM (v, &iter, ese.ele, itype) {
2232                                         vert_map[BM_elem_index_get(v)] = i;
2233                                 }
2234                         }
2235                 }
2236
2237                 mul_v3_v3fl(trans_islands[i].co, co, 1.0f / (float)fg_len);
2238
2239                 if (createSpaceNormalTangent(trans_islands[i].axismtx, no, tangent)) {
2240                         /* pass */
2241                 }
2242                 else {
2243                         if (normalize_v3(no) != 0.0f) {
2244                                 axis_dominant_v3_to_m3(trans_islands[i].axismtx, no);
2245                                 invert_m3(trans_islands[i].axismtx);
2246                         }
2247                         else {
2248                                 unit_m3(trans_islands[i].axismtx);
2249                         }
2250                 }
2251         }
2252
2253         MEM_freeN(groups_array);
2254         MEM_freeN(group_index);
2255
2256         /* for PET we need islands of 1 so connected vertices can use it with V3D_AROUND_LOCAL_ORIGINS */
2257         if (calc_single_islands) {
2258                 BMIter viter;
2259                 BMVert *v;
2260                 int group_tot_single = 0;
2261
2262                 BM_ITER_MESH_INDEX (v, &viter, bm, BM_VERTS_OF_MESH, i) {
2263                         if (BM_elem_flag_test(v, BM_ELEM_SELECT) && (vert_map[i] == -1)) {
2264                                 group_tot_single += 1;
2265                         }
2266                 }
2267
2268                 if (group_tot_single != 0) {
2269                         trans_islands = MEM_reallocN(trans_islands, sizeof(*trans_islands) * (group_tot + group_tot_single));
2270
2271                         BM_ITER_MESH_INDEX (v, &viter, bm, BM_VERTS_OF_MESH, i) {
2272                                 if (BM_elem_flag_test(v, BM_ELEM_SELECT) && (vert_map[i] == -1)) {
2273                                         struct TransIslandData *v_island = &trans_islands[group_tot];
2274                                         vert_map[i] = group_tot;
2275
2276                                         copy_v3_v3(v_island->co, v->co);
2277
2278                                         if (is_zero_v3(v->no) != 0.0f) {
2279                                                 axis_dominant_v3_to_m3(v_island->axismtx, v->no);
2280                                                 invert_m3(v_island->axismtx);
2281                                         }
2282                                         else {
2283                                                 unit_m3(v_island->axismtx);
2284                                         }
2285
2286                                         group_tot += 1;
2287                                 }
2288                         }
2289                 }
2290         }
2291
2292         *r_island_tot = group_tot;
2293         *r_island_vert_map = vert_map;
2294
2295         return trans_islands;
2296 }
2297
2298 /* way to overwrite what data is edited with transform */
2299 static void VertsToTransData(TransInfo *t, TransData *td, TransDataExtension *tx,
2300                              BMEditMesh *em, BMVert *eve, float *bweight,
2301                              struct TransIslandData *v_island)
2302 {
2303         float *no, _no[3];
2304         BLI_assert(BM_elem_flag_test(eve, BM_ELEM_HIDDEN) == 0);
2305
2306         td->flag = 0;
2307         //if (key)
2308         //      td->loc = key->co;
2309         //else
2310         td->loc = eve->co;
2311         copy_v3_v3(td->iloc, td->loc);
2312
2313         if ((t->mode == TFM_SHRINKFATTEN) &&
2314             (em->selectmode & SCE_SELECT_FACE) &&
2315             BM_elem_flag_test(eve, BM_ELEM_SELECT) &&
2316             (BM_vert_calc_normal_ex(eve, BM_ELEM_SELECT, _no)))
2317         {
2318                 no = _no;
2319         }
2320         else {
2321                 no = eve->no;
2322         }
2323
2324         if (v_island) {
2325                 copy_v3_v3(td->center, v_island->co);
2326                 copy_m3_m3(td->axismtx, v_island->axismtx);
2327         }
2328         else if (t->around == V3D_AROUND_LOCAL_ORIGINS) {
2329                 copy_v3_v3(td->center, td->loc);
2330                 createSpaceNormal(td->axismtx, no);
2331         }
2332         else {
2333                 copy_v3_v3(td->center, td->loc);
2334
2335                 /* Setting normals */
2336                 copy_v3_v3(td->axismtx[2], no);
2337                 td->axismtx[0][0]        =
2338                     td->axismtx[0][1]    =
2339                     td->axismtx[0][2]    =
2340                     td->axismtx[1][0]    =
2341                     td->axismtx[1][1]    =
2342                     td->axismtx[1][2]    = 0.0f;
2343         }
2344
2345
2346         td->ext = NULL;
2347         td->val = NULL;
2348         td->extra = NULL;
2349         if (t->mode == TFM_BWEIGHT) {
2350                 td->val  =  bweight;
2351                 td->ival = *bweight;
2352         }
2353         else if (t->mode == TFM_SKIN_RESIZE) {
2354                 MVertSkin *vs = CustomData_bmesh_get(&em->bm->vdata,
2355                                                      eve->head.data,
2356                                                      CD_MVERT_SKIN);
2357                 /* skin node size */
2358                 td->ext = tx;
2359                 copy_v3_v3(tx->isize, vs->radius);
2360                 tx->size = vs->radius;
2361                 td->val = vs->radius;
2362         }
2363         else if (t->mode == TFM_SHRINKFATTEN) {
2364                 td->ext = tx;
2365                 tx->isize[0] = BM_vert_calc_shell_factor_ex(eve, no, BM_ELEM_SELECT);
2366         }
2367 }
2368
2369 static void createTransEditVerts(TransInfo *t)
2370 {
2371         TransData *tob = NULL;
2372         TransDataExtension *tx = NULL;
2373         BMEditMesh *em = BKE_editmesh_from_object(t->obedit);
2374         Mesh *me = t->obedit->data;
2375         BMesh *bm = em->bm;
2376         BMVert *eve;
2377         BMIter iter;
2378         float (*mappedcos)[3] = NULL, (*quats)[4] = NULL;
2379         float mtx[3][3], smtx[3][3], (*defmats)[3][3] = NULL, (*defcos)[3] = NULL;
2380         float *dists = NULL;
2381         int a;
2382         const int prop_mode = (t->flag & T_PROP_EDIT) ? (t->flag & T_PROP_EDIT_ALL) : 0;
2383         int mirror = 0;
2384         int cd_vert_bweight_offset = -1;
2385         bool use_topology = (me->editflag & ME_EDIT_MIRROR_TOPO) != 0;
2386
2387         struct TransIslandData *island_info = NULL;
2388         int island_info_tot;
2389         int *island_vert_map = NULL;
2390
2391         /* Even for translation this is needed because of island-orientation, see: T51651. */
2392         const bool is_island_center = (t->around == V3D_AROUND_LOCAL_ORIGINS);
2393         /* Original index of our connected vertex when connected distances are calculated.
2394          * Optional, allocate if needed. */
2395         int *dists_index = NULL;
2396
2397         if (t->flag & T_MIRROR) {
2398                 EDBM_verts_mirror_cache_begin(em, 0, false, (t->flag & T_PROP_EDIT) == 0, use_topology);
2399                 mirror = 1;
2400         }
2401
2402         /**
2403          * Quick check if we can transform.
2404          *
2405          * \note ignore modes here, even in edge/face modes, transform data is created by selected vertices.
2406          * \note in prop mode we need at least 1 selected.
2407          */
2408         if (bm->totvertsel == 0) {
2409                 goto cleanup;
2410         }
2411
2412         if (t->mode == TFM_BWEIGHT) {
2413                 BM_mesh_cd_flag_ensure(bm, BKE_mesh_from_object(t->obedit), ME_CDFLAG_VERT_BWEIGHT);
2414                 cd_vert_bweight_offset = CustomData_get_offset(&bm->vdata, CD_BWEIGHT);
2415         }
2416
2417         if (prop_mode) {
2418                 unsigned int count = 0;
2419                 BM_ITER_MESH (eve, &iter, bm, BM_VERTS_OF_MESH) {
2420                         if (!BM_elem_flag_test(eve, BM_ELEM_HIDDEN)) {
2421                                 count++;
2422                         }
2423                 }
2424
2425                 t->total = count;
2426
2427                 /* allocating scratch arrays */
2428                 if (prop_mode & T_PROP_CONNECTED) {
2429                         dists = MEM_mallocN(em->bm->totvert * sizeof(float), __func__);
2430                         if (is_island_center) {
2431                                 dists_index =  MEM_mallocN(em->bm->totvert * sizeof(int), __func__);
2432                         }
2433                 }
2434         }
2435         else {
2436                 t->total = bm->totvertsel;
2437         }
2438
2439         tob = t->data = MEM_callocN(t->total * sizeof(TransData), "TransObData(Mesh EditMode)");
2440         if (ELEM(t->mode, TFM_SKIN_RESIZE, TFM_SHRINKFATTEN)) {
2441                 /* warning, this is overkill, we only need 2 extra floats,
2442                  * but this stores loads of extra stuff, for TFM_SHRINKFATTEN its even more overkill
2443                  * since we may not use the 'alt' transform mode to maintain shell thickness,
2444                  * but with generic transform code its hard to lazy init vars */
2445                 tx = t->ext = MEM_callocN(t->total * sizeof(TransDataExtension),
2446                                           "TransObData ext");
2447         }
2448
2449         copy_m3_m4(mtx, t->obedit->obmat);
2450         /* we use a pseudoinverse so that when one of the axes is scaled to 0,
2451          * matrix inversion still works and we can still moving along the other */
2452         pseudoinverse_m3_m3(smtx, mtx, PSEUDOINVERSE_EPSILON);
2453
2454         if (prop_mode & T_PROP_CONNECTED) {
2455                 editmesh_set_connectivity_distance(em->bm, mtx, dists, dists_index);
2456         }
2457
2458         if (is_island_center) {
2459                 /* In this specific case, near-by vertices will need to know the island of the nearest connected vertex. */
2460                 const bool calc_single_islands = (
2461                         (prop_mode & T_PROP_CONNECTED) &&
2462                         (t->around == V3D_AROUND_LOCAL_ORIGINS) &&
2463                         (em->selectmode & SCE_SELECT_VERTEX));
2464
2465                 island_info = editmesh_islands_info_calc(em, &island_info_tot, &island_vert_map, calc_single_islands);
2466         }
2467
2468         /* detect CrazySpace [tm] */
2469         if (modifiers_getCageIndex(t->scene, t->obedit, NULL, 1) != -1) {
2470                 int totleft = -1;
2471                 if (modifiers_isCorrectableDeformed(t->scene, t->obedit)) {
2472                         /* check if we can use deform matrices for modifier from the
2473                          * start up to stack, they are more accurate than quats */
2474                         totleft = BKE_crazyspace_get_first_deform_matrices_editbmesh(t->scene, t->obedit, em, &defmats, &defcos);
2475                 }
2476
2477                 /* if we still have more modifiers, also do crazyspace
2478                  * correction with quats, relative to the coordinates after
2479                  * the modifiers that support deform matrices (defcos) */
2480
2481 #if 0   /* TODO, fix crazyspace+extrude so it can be enabled for general use - campbell */
2482                 if ((totleft > 0) || (totleft == -1))
2483 #else
2484                 if (totleft > 0)
2485 #endif
2486                 {
2487                         mappedcos = BKE_crazyspace_get_mapped_editverts(t->scene, t->obedit);
2488                         quats = MEM_mallocN(em->bm->totvert * sizeof(*quats), "crazy quats");
2489                         BKE_crazyspace_set_quats_editmesh(em, defcos, mappedcos, quats, !prop_mode);
2490                         if (mappedcos)
2491                                 MEM_freeN(mappedcos);
2492                 }
2493
2494                 if (defcos) {
2495                         MEM_freeN(defcos);
2496                 }
2497         }
2498
2499         /* find out which half we do */
2500         if (mirror) {
2501                 BM_ITER_MESH (eve, &iter, bm, BM_VERTS_OF_MESH) {
2502                         if (BM_elem_flag_test(eve, BM_ELEM_SELECT) && eve->co[0] != 0.0f) {
2503                                 if (eve->co[0] < 0.0f) {
2504                                         t->mirror = -1;
2505                                         mirror = -1;
2506                                 }
2507                                 break;
2508                         }
2509                 }
2510         }
2511
2512         BM_ITER_MESH_INDEX (eve, &iter, bm, BM_VERTS_OF_MESH, a) {
2513                 if (!BM_elem_flag_test(eve, BM_ELEM_HIDDEN)) {
2514                         if (prop_mode || BM_elem_flag_test(eve, BM_ELEM_SELECT)) {
2515                                 struct TransIslandData *v_island = NULL;
2516                                 float *bweight = (cd_vert_bweight_offset != -1) ? BM_ELEM_CD_GET_VOID_P(eve, cd_vert_bweight_offset) : NULL;
2517
2518                                 if (island_info) {
2519                                         const int connected_index = (dists_index && dists_index[a] != -1) ? dists_index[a] : a;
2520                                         v_island = (island_vert_map[connected_index] != -1) ?
2521                                                    &island_info[island_vert_map[connected_index]] : NULL;
2522                                 }
2523
2524
2525                                 VertsToTransData(t, tob, tx, em, eve, bweight, v_island);
2526                                 if (tx)
2527                                         tx++;
2528
2529                                 /* selected */
2530                                 if (BM_elem_flag_test(eve, BM_ELEM_SELECT))
2531                                         tob->flag |= TD_SELECTED;
2532
2533                                 if (prop_mode) {
2534                                         if (prop_mode & T_PROP_CONNECTED) {
2535                                                 tob->dist = dists[a];
2536                                         }
2537                                         else {
2538                                                 tob->flag |= TD_NOTCONNECTED;
2539                                                 tob->dist = FLT_MAX;
2540                                         }
2541                                 }
2542
2543                                 /* CrazySpace */
2544                                 if (defmats || (quats && BM_elem_flag_test(eve, BM_ELEM_TAG))) {
2545                                         float mat[3][3], qmat[3][3], imat[3][3];
2546
2547                                         /* use both or either quat and defmat correction */
2548                                         if (quats && BM_elem_flag_test(eve, BM_ELEM_TAG)) {
2549                                                 quat_to_mat3(qmat, quats[BM_elem_index_get(eve)]);
2550
2551                                                 if (defmats)
2552                                                         mul_m3_series(mat, defmats[a], qmat, mtx);
2553                                                 else
2554                                                         mul_m3_m3m3(mat, mtx, qmat);
2555                                         }
2556                                         else
2557                                                 mul_m3_m3m3(mat, mtx, defmats[a]);
2558
2559                                         invert_m3_m3(imat, mat);
2560
2561                                         copy_m3_m3(tob->smtx, imat);
2562                                         copy_m3_m3(tob->mtx, mat);
2563                                 }
2564                                 else {
2565                                         copy_m3_m3(tob->smtx, smtx);
2566                                         copy_m3_m3(tob->mtx, mtx);
2567                                 }
2568
2569                                 /* Mirror? */
2570                                 if ((mirror > 0 && tob->iloc[0] > 0.0f) || (mirror < 0 && tob->iloc[0] < 0.0f)) {
2571                                         BMVert *vmir = EDBM_verts_mirror_get(em, eve); //t->obedit, em, eve, tob->iloc, a);
2572                                         if (vmir && vmir != eve) {
2573                                                 tob->extra = vmir;
2574                                         }
2575                                 }
2576                                 tob++;
2577                         }
2578                 }
2579         }
2580         
2581         if (island_info) {
2582                 MEM_freeN(island_info);
2583                 MEM_freeN(island_vert_map);
2584         }
2585
2586         if (mirror != 0) {
2587                 tob = t->data;
2588                 for (a = 0; a < t->total; a++, tob++) {
2589                         if (ABS(tob->loc[0]) <= 0.00001f) {
2590                                 tob->flag |= TD_MIRROR_EDGE;
2591                         }
2592                 }
2593         }
2594
2595 cleanup:
2596         /* crazy space free */
2597         if (quats)
2598                 MEM_freeN(quats);
2599         if (defmats)
2600                 MEM_freeN(defmats);
2601         if (dists)
2602                 MEM_freeN(dists);
2603         if (dists_index)
2604                 MEM_freeN(dists_index);
2605
2606         if (t->flag & T_MIRROR) {
2607                 EDBM_verts_mirror_cache_end(em);
2608         }
2609 }
2610
2611 /* *** NODE EDITOR *** */
2612 void flushTransNodes(TransInfo *t)
2613 {
2614         const float dpi_fac = UI_DPI_FAC;
2615         int a;
2616         TransData *td;
2617         TransData2D *td2d;
2618         
2619         applyGridAbsolute(t);
2620         
2621         /* flush to 2d vector from internally used 3d vector */
2622         for (a = 0, td = t->data, td2d = t->data2d; a < t->total; a++, td++, td2d++) {
2623                 bNode *node = td->extra;
2624                 float locx, locy;
2625
2626                 /* weirdo - but the node system is a mix of free 2d elements and dpi sensitive UI */
2627 #ifdef USE_NODE_CENTER
2628                 locx = (td2d->loc[0] - (BLI_rctf_size_x(&node->totr)) * +0.5f) / dpi_fac;
2629                 locy = (td2d->loc[1] - (BLI_rctf_size_y(&node->totr)) * -0.5f) / dpi_fac;
2630 #else
2631                 locx = td2d->loc[0] / dpi_fac;
2632                 locy = td2d->loc[1] / dpi_fac;
2633 #endif
2634                 
2635                 /* account for parents (nested nodes) */
2636                 if (node->parent) {
2637                         nodeFromView(node->parent, locx, locy, &node->locx, &node->locy);
2638                 }
2639                 else {
2640                         node->locx = locx;
2641                         node->locy = locy;
2642                 }
2643         }
2644         
2645         /* handle intersection with noodles */
2646         if (t->total == 1) {
2647                 ED_node_link_intersect_test(t->sa, 1);
2648         }
2649 }
2650
2651 /* *** SEQUENCE EDITOR *** */
2652
2653 /* commented _only_ because the meta may have animation data which
2654  * needs moving too [#28158] */
2655
2656 #define SEQ_TX_NESTED_METAS
2657
2658 BLI_INLINE void trans_update_seq(Scene *sce, Sequence *seq, int old_start, int sel_flag)
2659 {
2660         if (seq->depth == 0) {
2661                 /* Calculate this strip and all nested strips.
2662                  * Children are ALWAYS transformed first so we don't need to do this in another loop.
2663                  */
2664                 BKE_sequence_calc(sce, seq);
2665         }
2666         else {
2667                 BKE_sequence_calc_disp(sce, seq);
2668         }
2669
2670         if (sel_flag == SELECT)
2671                 BKE_sequencer_offset_animdata(sce, seq, seq->start - old_start);
2672 }
2673
2674 void flushTransSeq(TransInfo *t)
2675 {
2676         ListBase *seqbasep = BKE_sequencer_editing_get(t->scene, false)->seqbasep; /* Editing null check already done */
2677         int a, new_frame;
2678         TransData *td = NULL;
2679         TransData2D *td2d = NULL;
2680         TransDataSeq *tdsq = NULL;
2681         Sequence *seq;
2682
2683
2684
2685         /* prevent updating the same seq twice
2686          * if the transdata order is changed this will mess up
2687          * but so will TransDataSeq */
2688         Sequence *seq_prev = NULL;
2689         int old_start_prev = 0, sel_flag_prev = 0;
2690
2691         /* flush to 2d vector from internally used 3d vector */
2692         for (a = 0, td = t->data, td2d = t->data2d; a < t->total; a++, td++, td2d++) {
2693                 int old_start;
2694                 tdsq = (TransDataSeq *)td->extra;
2695                 seq = tdsq->seq;
2696                 old_start = seq->start;
2697                 new_frame = iroundf(td2d->loc[0]);
2698
2699                 switch (tdsq->sel_flag) {
2700                         case SELECT:
2701 #ifdef SEQ_TX_NESTED_METAS
2702                                 if ((seq->depth != 0 || BKE_sequence_tx_test(seq))) /* for meta's, their children move */
2703                                         seq->start = new_frame - tdsq->start_offset;
2704 #else
2705                                 if (seq->type != SEQ_TYPE_META && (seq->depth != 0 || seq_tx_test(seq))) /* for meta's, their children move */
2706                                         seq->start = new_frame - tdsq->start_offset;
2707 #endif
2708                                 if (seq->depth == 0) {
2709                                         seq->machine = iroundf(td2d->loc[1]);
2710                                         CLAMP(seq->machine, 1, MAXSEQ);
2711                                 }
2712                                 break;
2713                         case SEQ_LEFTSEL: /* no vertical transform  */
2714                                 BKE_sequence_tx_set_final_left(seq, new_frame);
2715                                 BKE_sequence_tx_handle_xlimits(seq, tdsq->flag & SEQ_LEFTSEL, tdsq->flag & SEQ_RIGHTSEL);
2716                                 BKE_sequence_single_fix(seq); /* todo - move this into aftertrans update? - old seq tx needed it anyway */
2717                                 break;
2718                         case SEQ_RIGHTSEL: /* no vertical transform  */
2719                                 BKE_sequence_tx_set_final_right(seq, new_frame);
2720                                 BKE_sequence_tx_handle_xlimits(seq, tdsq->flag & SEQ_LEFTSEL, tdsq->flag & SEQ_RIGHTSEL);
2721                                 BKE_sequence_single_fix(seq); /* todo - move this into aftertrans update? - old seq tx needed it anyway */
2722                                 break;
2723                 }
2724
2725                 /* Update *previous* seq! Else, we would update a seq after its first transform, and if it has more than one
2726                  * (like e.g. SEQ_LEFTSEL and SEQ_RIGHTSEL), the others are not updated! See T38469.
2727                  */
2728                 if (seq != seq_prev) {
2729                         if (seq_prev) {
2730                                 trans_update_seq(t->scene, seq_prev, old_start_prev, sel_flag_prev);
2731                         }
2732
2733                         seq_prev = seq;
2734                         old_start_prev = old_start;
2735                         sel_flag_prev = tdsq->sel_flag;
2736                 }
2737                 else {
2738                         /* We want to accumulate *all* sel_flags for this seq! */
2739                         sel_flag_prev |= tdsq->sel_flag;
2740                 }
2741         }
2742
2743         /* Don't forget to update the last seq! */
2744         if (seq_prev) {
2745                 trans_update_seq(t->scene, seq_prev, old_start_prev, sel_flag_prev);
2746         }
2747
2748
2749         if (ELEM(t->mode, TFM_SEQ_SLIDE, TFM_TIME_TRANSLATE)) { /* originally TFM_TIME_EXTEND, transform changes */
2750                 /* Special annoying case here, need to calc metas with TFM_TIME_EXTEND only */
2751
2752                 /* calc all meta's then effects [#27953] */
2753                 for (seq = seqbasep->first; seq; seq = seq->next) {
2754                         if (seq->type == SEQ_TYPE_META && seq->flag & SELECT) {
2755                                 BKE_sequence_calc(t->scene, seq);
2756                         }
2757                 }
2758                 for (seq = seqbasep->first; seq; seq = seq->next) {
2759                         if (seq->seq1 || seq->seq2 || seq->seq3) {
2760                                 BKE_sequence_calc(t->scene, seq);
2761                         }
2762                 }
2763
2764                 /* update effects inside meta's */
2765                 for (a = 0, seq_prev = NULL, td = t->data, td2d = t->data2d;
2766                      a < t->total;
2767                      a++, td++, td2d++, seq_prev = seq)
2768                 {
2769                         tdsq = (TransDataSeq *)td->extra;
2770                         seq = tdsq->seq;
2771                         if ((seq != seq_prev) && (seq->depth != 0)) {
2772                                 if (seq->seq1 || seq->seq2 || seq->seq3) {
2773                                         BKE_sequence_calc(t->scene, seq);
2774                                 }