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