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