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