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