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