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