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