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