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