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