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