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