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