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