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