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