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