Merge branch 'blender2.7'
[blender.git] / source / blender / editors / transform / transform_generics.c
1 /*
2  * This program is free software; you can redistribute it and/or
3  * modify it under the terms of the GNU General Public License
4  * as published by the Free Software Foundation; either version 2
5  * of the License, or (at your option) any later version.
6  *
7  * This program is distributed in the hope that it will be useful,
8  * but WITHOUT ANY WARRANTY; without even the implied warranty of
9  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
10  * GNU General Public License for more details.
11  *
12  * You should have received a copy of the GNU General Public License
13  * along with this program; if not, write to the Free Software Foundation,
14  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
15  *
16  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
17  * All rights reserved.
18  */
19
20 /** \file
21  * \ingroup edtransform
22  */
23
24 #include <string.h>
25 #include <math.h>
26
27 #include "MEM_guardedalloc.h"
28
29 #include "BLI_sys_types.h" /* for intptr_t support */
30
31 #include "DNA_anim_types.h"
32 #include "DNA_armature_types.h"
33 #include "DNA_brush_types.h"
34 #include "DNA_gpencil_types.h"
35 #include "DNA_lattice_types.h"
36 #include "DNA_screen_types.h"
37 #include "DNA_sequence_types.h"
38 #include "DNA_space_types.h"
39 #include "DNA_scene_types.h"
40 #include "DNA_object_types.h"
41 #include "DNA_mesh_types.h"
42 #include "DNA_view3d_types.h"
43 #include "DNA_modifier_types.h"
44 #include "DNA_movieclip_types.h"
45 #include "DNA_mask_types.h"
46 #include "DNA_meta_types.h"
47
48 #include "BLI_math.h"
49 #include "BLI_blenlib.h"
50 #include "BLI_rand.h"
51 #include "BLI_utildefines.h"
52
53 #include "PIL_time.h"
54
55 #include "BLT_translation.h"
56
57 #include "RNA_access.h"
58
59 #include "GPU_immediate.h"
60 #include "GPU_matrix.h"
61
62 #include "BIK_api.h"
63
64 #include "BKE_action.h"
65 #include "BKE_animsys.h"
66 #include "BKE_armature.h"
67 #include "BKE_context.h"
68 #include "BKE_curve.h"
69 #include "BKE_editmesh.h"
70 #include "BKE_fcurve.h"
71 #include "BKE_gpencil.h"
72 #include "BKE_lattice.h"
73 #include "BKE_layer.h"
74 #include "BKE_library.h"
75 #include "BKE_mask.h"
76 #include "BKE_nla.h"
77 #include "BKE_paint.h"
78 #include "BKE_scene.h"
79 #include "BKE_sequencer.h"
80 #include "BKE_tracking.h"
81 #include "BKE_workspace.h"
82
83 #include "DEG_depsgraph.h"
84
85 #include "ED_anim_api.h"
86 #include "ED_armature.h"
87 #include "ED_image.h"
88 #include "ED_keyframing.h"
89 #include "ED_markers.h"
90 #include "ED_mesh.h"
91 #include "ED_object.h"
92 #include "ED_particle.h"
93 #include "ED_screen_types.h"
94 #include "ED_space_api.h"
95 #include "ED_uvedit.h"
96 #include "ED_view3d.h"
97 #include "ED_curve.h" /* for curve_editnurbs */
98 #include "ED_clip.h"
99 #include "ED_screen.h"
100 #include "ED_gpencil.h"
101
102 #include "WM_types.h"
103 #include "WM_api.h"
104
105 #include "RE_engine.h"
106
107 #include "UI_resources.h"
108 #include "UI_view2d.h"
109
110 #include "transform.h"
111
112 /* ************************** Functions *************************** */
113
114 void getViewVector(const TransInfo *t, const float coord[3], float vec[3])
115 {
116         if (t->persp != RV3D_ORTHO) {
117                 sub_v3_v3v3(vec, coord, t->viewinv[3]);
118         }
119         else {
120                 copy_v3_v3(vec, t->viewinv[2]);
121         }
122         normalize_v3(vec);
123 }
124
125 /* ************************** GENERICS **************************** */
126
127
128 static void clipMirrorModifier(TransInfo *t)
129 {
130         FOREACH_TRANS_DATA_CONTAINER (t, tc) {
131                 Object *ob = tc->obedit;
132                 ModifierData *md = ob->modifiers.first;
133                 float tolerance[3] = {0.0f, 0.0f, 0.0f};
134                 int axis = 0;
135
136                 for (; md; md = md->next) {
137                         if ((md->type == eModifierType_Mirror) && (md->mode & eModifierMode_Realtime)) {
138                                 MirrorModifierData *mmd = (MirrorModifierData *) md;
139
140                                 if (mmd->flag & MOD_MIR_CLIPPING) {
141                                         axis = 0;
142                                         if (mmd->flag & MOD_MIR_AXIS_X) {
143                                                 axis |= 1;
144                                                 tolerance[0] = mmd->tolerance;
145                                         }
146                                         if (mmd->flag & MOD_MIR_AXIS_Y) {
147                                                 axis |= 2;
148                                                 tolerance[1] = mmd->tolerance;
149                                         }
150                                         if (mmd->flag & MOD_MIR_AXIS_Z) {
151                                                 axis |= 4;
152                                                 tolerance[2] = mmd->tolerance;
153                                         }
154                                         if (axis) {
155                                                 float mtx[4][4], imtx[4][4];
156                                                 int i;
157
158                                                 if (mmd->mirror_ob) {
159                                                         float obinv[4][4];
160
161                                                         invert_m4_m4(obinv, mmd->mirror_ob->obmat);
162                                                         mul_m4_m4m4(mtx, obinv, ob->obmat);
163                                                         invert_m4_m4(imtx, mtx);
164                                                 }
165
166                                                 TransData *td = tc->data;
167                                                 for (i = 0; i < tc->data_len; i++, td++) {
168                                                         int clip;
169                                                         float loc[3], iloc[3];
170
171                                                         if (td->flag & TD_NOACTION)
172                                                                 break;
173                                                         if (td->loc == NULL)
174                                                                 break;
175
176                                                         if (td->flag & TD_SKIP)
177                                                                 continue;
178
179                                                         copy_v3_v3(loc,  td->loc);
180                                                         copy_v3_v3(iloc, td->iloc);
181
182                                                         if (mmd->mirror_ob) {
183                                                                 mul_m4_v3(mtx, loc);
184                                                                 mul_m4_v3(mtx, iloc);
185                                                         }
186
187                                                         clip = 0;
188                                                         if (axis & 1) {
189                                                                 if (fabsf(iloc[0]) <= tolerance[0] ||
190                                                                     loc[0] * iloc[0] < 0.0f)
191                                                                 {
192                                                                         loc[0] = 0.0f;
193                                                                         clip = 1;
194                                                                 }
195                                                         }
196
197                                                         if (axis & 2) {
198                                                                 if (fabsf(iloc[1]) <= tolerance[1] ||
199                                                                     loc[1] * iloc[1] < 0.0f)
200                                                                 {
201                                                                         loc[1] = 0.0f;
202                                                                         clip = 1;
203                                                                 }
204                                                         }
205                                                         if (axis & 4) {
206                                                                 if (fabsf(iloc[2]) <= tolerance[2] ||
207                                                                     loc[2] * iloc[2] < 0.0f)
208                                                                 {
209                                                                         loc[2] = 0.0f;
210                                                                         clip = 1;
211                                                                 }
212                                                         }
213                                                         if (clip) {
214                                                                 if (mmd->mirror_ob) {
215                                                                         mul_m4_v3(imtx, loc);
216                                                                 }
217                                                                 copy_v3_v3(td->loc, loc);
218                                                         }
219                                                 }
220                                         }
221
222                                 }
223                         }
224                 }
225         }
226 }
227
228 /* assumes obedit set to mesh object */
229 static void editbmesh_apply_to_mirror(TransInfo *t)
230 {
231         FOREACH_TRANS_DATA_CONTAINER (t, tc) {
232                 if (tc->mirror.axis_flag) {
233                         TransData *td = tc->data;
234                         BMVert *eve;
235                         int i;
236
237                         for (i = 0; i < tc->data_len; i++, td++) {
238                                 if (td->flag & TD_NOACTION)
239                                         break;
240                                 if (td->loc == NULL)
241                                         break;
242                                 if (td->flag & TD_SKIP)
243                                         continue;
244
245                                 eve = td->extra;
246                                 if (eve) {
247                                         eve->co[0] = -td->loc[0];
248                                         eve->co[1] = td->loc[1];
249                                         eve->co[2] = td->loc[2];
250                                 }
251
252                                 if (td->flag & TD_MIRROR_EDGE) {
253                                         td->loc[0] = 0;
254                                 }
255                         }
256                 }
257         }
258 }
259
260 /* for the realtime animation recording feature, handle overlapping data */
261 static void animrecord_check_state(Scene *scene, ID *id, wmTimer *animtimer)
262 {
263         ScreenAnimData *sad = (animtimer) ? animtimer->customdata : NULL;
264
265         /* sanity checks */
266         if (ELEM(NULL, scene, id, sad))
267                 return;
268
269         /* check if we need a new strip if:
270          * - if animtimer is running
271          * - we're not only keying for available channels
272          * - the option to add new actions for each round is not enabled
273          */
274         if (IS_AUTOKEY_FLAG(scene, INSERTAVAIL) == 0 && (scene->toolsettings->autokey_flag & ANIMRECORD_FLAG_WITHNLA)) {
275                 /* if playback has just looped around,
276                  * we need to add a new NLA track+strip to allow a clean pass to occur */
277                 if ((sad) && (sad->flag & ANIMPLAY_FLAG_JUMPED)) {
278                         AnimData *adt = BKE_animdata_from_id(id);
279                         const bool is_first = (adt) && (adt->nla_tracks.first == NULL);
280
281                         /* perform push-down manually with some differences
282                          * NOTE: BKE_nla_action_pushdown() sync warning...
283                          */
284                         if ((adt->action) && !(adt->flag & ADT_NLA_EDIT_ON)) {
285                                 float astart, aend;
286
287                                 /* only push down if action is more than 1-2 frames long */
288                                 calc_action_range(adt->action, &astart, &aend, 1);
289                                 if (aend > astart + 2.0f) {
290                                         NlaStrip *strip = BKE_nlastack_add_strip(adt, adt->action);
291
292                                         /* clear reference to action now that we've pushed it onto the stack */
293                                         id_us_min(&adt->action->id);
294                                         adt->action = NULL;
295
296                                         /* adjust blending + extend so that they will behave correctly */
297                                         strip->extendmode = NLASTRIP_EXTEND_NOTHING;
298                                         strip->flag &= ~(NLASTRIP_FLAG_AUTO_BLENDS | NLASTRIP_FLAG_SELECT | NLASTRIP_FLAG_ACTIVE);
299
300                                         /* copy current "action blending" settings from adt to the strip,
301                                          * as it was keyframed with these settings, so omitting them will
302                                          * change the effect  [T54766]
303                                          */
304                                         if (is_first == false) {
305                                                 strip->blendmode = adt->act_blendmode;
306                                                 strip->influence = adt->act_influence;
307
308                                                 if (adt->act_influence < 1.0f) {
309                                                         /* enable "user-controlled" influence (which will insert a default keyframe)
310                                                          * so that the influence doesn't get lost on the new update
311                                                          *
312                                                          * NOTE: An alternative way would have been to instead hack the influence
313                                                          * to not get always get reset to full strength if NLASTRIP_FLAG_USR_INFLUENCE
314                                                          * is disabled but auto-blending isn't being used. However, that approach
315                                                          * is a bit hacky/hard to discover, and may cause backwards compatibility issues,
316                                                          * so it's better to just do it this way.
317                                                          */
318                                                         strip->flag |= NLASTRIP_FLAG_USR_INFLUENCE;
319                                                         BKE_nlastrip_validate_fcurves(strip);
320                                                 }
321                                         }
322
323                                         /* also, adjust the AnimData's action extend mode to be on
324                                          * 'nothing' so that previous result still play
325                                          */
326                                         adt->act_extendmode = NLASTRIP_EXTEND_NOTHING;
327                                 }
328                         }
329                 }
330         }
331 }
332
333 static bool fcu_test_selected(FCurve *fcu)
334 {
335         BezTriple *bezt = fcu->bezt;
336         unsigned int i;
337
338         if (bezt == NULL) /* ignore baked */
339                 return 0;
340
341         for (i = 0; i < fcu->totvert; i++, bezt++) {
342                 if (BEZT_ISSEL_ANY(bezt)) return 1;
343         }
344
345         return 0;
346 }
347
348 /* helper for recalcData() - for Action Editor transforms */
349 static void recalcData_actedit(TransInfo *t)
350 {
351         ViewLayer *view_layer = t->view_layer;
352         SpaceAction *saction = (SpaceAction *)t->sa->spacedata.first;
353
354         bAnimContext ac = {NULL};
355         ListBase anim_data = {NULL, NULL};
356         bAnimListElem *ale;
357         int filter;
358
359         /* initialize relevant anim-context 'context' data from TransInfo data */
360         /* NOTE: sync this with the code in ANIM_animdata_get_context() */
361         ac.bmain = CTX_data_main(t->context);
362         ac.scene = t->scene;
363         ac.view_layer = t->view_layer;
364         ac.obact = OBACT(view_layer);
365         ac.sa = t->sa;
366         ac.ar = t->ar;
367         ac.sl = (t->sa) ? t->sa->spacedata.first : NULL;
368         ac.spacetype = (t->sa) ? t->sa->spacetype : 0;
369         ac.regiontype = (t->ar) ? t->ar->regiontype : 0;
370
371         ANIM_animdata_context_getdata(&ac);
372
373         /* perform flush */
374         if (ELEM(ac.datatype, ANIMCONT_GPENCIL, ANIMCONT_MASK)) {
375                 /* flush transform values back to actual coordinates */
376                 flushTransIntFrameActionData(t);
377         }
378
379         if (ac.datatype != ANIMCONT_MASK) {
380                 /* get animdata blocks visible in editor, assuming that these will be the ones where things changed */
381                 filter = (ANIMFILTER_DATA_VISIBLE | ANIMFILTER_ANIMDATA);
382                 ANIM_animdata_filter(&ac, &anim_data, filter, ac.data, ac.datatype);
383
384                 /* just tag these animdata-blocks to recalc, assuming that some data there changed
385                  * BUT only do this if realtime updates are enabled
386                  */
387                 if ((saction->flag & SACTION_NOREALTIMEUPDATES) == 0) {
388                         for (ale = anim_data.first; ale; ale = ale->next) {
389                                 /* set refresh tags for objects using this animation */
390                                 ANIM_list_elem_update(CTX_data_main(t->context), t->scene, ale);
391                         }
392                 }
393
394                 /* now free temp channels */
395                 ANIM_animdata_freelist(&anim_data);
396         }
397 }
398 /* helper for recalcData() - for Graph Editor transforms */
399 static void recalcData_graphedit(TransInfo *t)
400 {
401         SpaceGraph *sipo = (SpaceGraph *)t->sa->spacedata.first;
402         ViewLayer *view_layer = t->view_layer;
403
404         ListBase anim_data = {NULL, NULL};
405         bAnimContext ac = {NULL};
406         int filter;
407
408         bAnimListElem *ale;
409         int dosort = 0;
410
411         /* initialize relevant anim-context 'context' data from TransInfo data */
412         /* NOTE: sync this with the code in ANIM_animdata_get_context() */
413         ac.bmain = CTX_data_main(t->context);
414         ac.scene = t->scene;
415         ac.view_layer = t->view_layer;
416         ac.obact = OBACT(view_layer);
417         ac.sa = t->sa;
418         ac.ar = t->ar;
419         ac.sl = (t->sa) ? t->sa->spacedata.first : NULL;
420         ac.spacetype = (t->sa) ? t->sa->spacetype : 0;
421         ac.regiontype = (t->ar) ? t->ar->regiontype : 0;
422
423         ANIM_animdata_context_getdata(&ac);
424
425         /* do the flush first */
426         flushTransGraphData(t);
427
428         /* get curves to check if a re-sort is needed */
429         filter = (ANIMFILTER_DATA_VISIBLE | ANIMFILTER_FOREDIT | ANIMFILTER_CURVE_VISIBLE);
430         ANIM_animdata_filter(&ac, &anim_data, filter, ac.data, ac.datatype);
431
432         /* now test if there is a need to re-sort */
433         for (ale = anim_data.first; ale; ale = ale->next) {
434                 FCurve *fcu = (FCurve *)ale->key_data;
435
436                 /* ignore FC-Curves without any selected verts */
437                 if (!fcu_test_selected(fcu))
438                         continue;
439
440                 /* watch it: if the time is wrong: do not correct handles yet */
441                 if (test_time_fcurve(fcu))
442                         dosort++;
443                 else
444                         calchandles_fcurve(fcu);
445
446                 /* set refresh tags for objects using this animation,
447                  * BUT only if realtime updates are enabled
448                  */
449                 if ((sipo->flag & SIPO_NOREALTIMEUPDATES) == 0)
450                         ANIM_list_elem_update(CTX_data_main(t->context), t->scene, ale);
451         }
452
453         /* do resort and other updates? */
454         if (dosort) remake_graph_transdata(t, &anim_data);
455
456         /* now free temp channels */
457         ANIM_animdata_freelist(&anim_data);
458 }
459
460 /* helper for recalcData() - for NLA Editor transforms */
461 static void recalcData_nla(TransInfo *t)
462 {
463         SpaceNla *snla = (SpaceNla *)t->sa->spacedata.first;
464         Scene *scene = t->scene;
465         double secf = FPS;
466         int i;
467
468         TransDataContainer *tc = TRANS_DATA_CONTAINER_FIRST_SINGLE(t);
469         TransDataNla *tdn = tc->custom.type.data;
470
471         /* for each strip we've got, perform some additional validation of the values that got set before
472          * using RNA to set the value (which does some special operations when setting these values to make
473          * sure that everything works ok)
474          */
475         for (i = 0; i < tc->data_len; i++, tdn++) {
476                 NlaStrip *strip = tdn->strip;
477                 PointerRNA strip_ptr;
478                 short pExceeded, nExceeded, iter;
479                 int delta_y1, delta_y2;
480
481                 /* if this tdn has no handles, that means it is just a dummy that should be skipped */
482                 if (tdn->handle == 0)
483                         continue;
484
485                 /* set refresh tags for objects using this animation,
486                  * BUT only if realtime updates are enabled
487                  */
488                 if ((snla->flag & SNLA_NOREALTIMEUPDATES) == 0)
489                         ANIM_id_update(CTX_data_main(t->context), tdn->id);
490
491                 /* if canceling transform, just write the values without validating, then move on */
492                 if (t->state == TRANS_CANCEL) {
493                         /* clear the values by directly overwriting the originals, but also need to restore
494                          * endpoints of neighboring transition-strips
495                          */
496
497                         /* start */
498                         strip->start = tdn->h1[0];
499
500                         if ((strip->prev) && (strip->prev->type == NLASTRIP_TYPE_TRANSITION))
501                                 strip->prev->end = tdn->h1[0];
502
503                         /* end */
504                         strip->end = tdn->h2[0];
505
506                         if ((strip->next) && (strip->next->type == NLASTRIP_TYPE_TRANSITION))
507                                 strip->next->start = tdn->h2[0];
508
509                         /* flush transforms to child strips (since this should be a meta) */
510                         BKE_nlameta_flush_transforms(strip);
511
512                         /* restore to original track (if needed) */
513                         if (tdn->oldTrack != tdn->nlt) {
514                                 /* just append to end of list for now, since strips get sorted in special_aftertrans_update() */
515                                 BLI_remlink(&tdn->nlt->strips, strip);
516                                 BLI_addtail(&tdn->oldTrack->strips, strip);
517                         }
518
519                         continue;
520                 }
521
522                 /* firstly, check if the proposed transform locations would overlap with any neighboring strips
523                  * (barring transitions) which are absolute barriers since they are not being moved
524                  *
525                  * this is done as a iterative procedure (done 5 times max for now)
526                  */
527                 for (iter = 0; iter < 5; iter++) {
528                         pExceeded = ((strip->prev) && (strip->prev->type != NLASTRIP_TYPE_TRANSITION) && (tdn->h1[0] < strip->prev->end));
529                         nExceeded = ((strip->next) && (strip->next->type != NLASTRIP_TYPE_TRANSITION) && (tdn->h2[0] > strip->next->start));
530
531                         if ((pExceeded && nExceeded) || (iter == 4)) {
532                                 /* both endpoints exceeded (or iteration ping-pong'd meaning that we need a compromise)
533                                  * - simply crop strip to fit within the bounds of the strips bounding it
534                                  * - if there were no neighbors, clear the transforms (make it default to the strip's current values)
535                                  */
536                                 if (strip->prev && strip->next) {
537                                         tdn->h1[0] = strip->prev->end;
538                                         tdn->h2[0] = strip->next->start;
539                                 }
540                                 else {
541                                         tdn->h1[0] = strip->start;
542                                         tdn->h2[0] = strip->end;
543                                 }
544                         }
545                         else if (nExceeded) {
546                                 /* move backwards */
547                                 float offset = tdn->h2[0] - strip->next->start;
548
549                                 tdn->h1[0] -= offset;
550                                 tdn->h2[0] -= offset;
551                         }
552                         else if (pExceeded) {
553                                 /* more forwards */
554                                 float offset = strip->prev->end - tdn->h1[0];
555
556                                 tdn->h1[0] += offset;
557                                 tdn->h2[0] += offset;
558                         }
559                         else /* all is fine and well */
560                                 break;
561                 }
562
563                 /* handle auto-snapping
564                  * NOTE: only do this when transform is still running, or we can't restore
565                  */
566                 if (t->state != TRANS_CANCEL) {
567                         switch (snla->autosnap) {
568                                 case SACTSNAP_FRAME: /* snap to nearest frame */
569                                 case SACTSNAP_STEP: /* frame step - this is basically the same,
570                                                      * since we don't have any remapping going on */
571                                 {
572                                         tdn->h1[0] = floorf(tdn->h1[0] + 0.5f);
573                                         tdn->h2[0] = floorf(tdn->h2[0] + 0.5f);
574                                         break;
575                                 }
576
577                                 case SACTSNAP_SECOND: /* snap to nearest second */
578                                 case SACTSNAP_TSTEP: /* second step - this is basically the same,
579                                                       * since we don't have any remapping going on */
580                                 {
581                                         /* This case behaves differently from the rest, since lengths of strips
582                                          * may not be multiples of a second. If we just naively resize adjust
583                                          * the handles, things may not work correctly. Instead, we only snap
584                                          * the first handle, and move the other to fit.
585                                          *
586                                          * FIXME: we do run into problems here when user attempts to negatively
587                                          *        scale the strip, as it then just compresses down and refuses
588                                          *        to expand out the other end.
589                                          */
590                                         float h1_new = (float)(floor(((double)tdn->h1[0] / secf) + 0.5) * secf);
591                                         float delta  = h1_new - tdn->h1[0];
592
593                                         tdn->h1[0] = h1_new;
594                                         tdn->h2[0] += delta;
595                                         break;
596                                 }
597
598                                 case SACTSNAP_MARKER: /* snap to nearest marker */
599                                 {
600                                         tdn->h1[0] = (float)ED_markers_find_nearest_marker_time(&t->scene->markers, tdn->h1[0]);
601                                         tdn->h2[0] = (float)ED_markers_find_nearest_marker_time(&t->scene->markers, tdn->h2[0]);
602                                         break;
603                                 }
604                         }
605                 }
606
607                 /* Use RNA to write the values to ensure that constraints on these are obeyed
608                  * (e.g. for transition strips, the values are taken from the neighbors)
609                  *
610                  * NOTE: we write these twice to avoid truncation errors which can arise when
611                  * moving the strips a large distance using numeric input [#33852]
612                  */
613                 RNA_pointer_create(NULL, &RNA_NlaStrip, strip, &strip_ptr);
614
615                 RNA_float_set(&strip_ptr, "frame_start", tdn->h1[0]);
616                 RNA_float_set(&strip_ptr, "frame_end", tdn->h2[0]);
617
618                 RNA_float_set(&strip_ptr, "frame_start", tdn->h1[0]);
619                 RNA_float_set(&strip_ptr, "frame_end", tdn->h2[0]);
620
621                 /* flush transforms to child strips (since this should be a meta) */
622                 BKE_nlameta_flush_transforms(strip);
623
624
625                 /* now, check if we need to try and move track
626                  * - we need to calculate both, as only one may have been altered by transform if only 1 handle moved
627                  */
628                 delta_y1 = ((int)tdn->h1[1] / NLACHANNEL_STEP(snla) - tdn->trackIndex);
629                 delta_y2 = ((int)tdn->h2[1] / NLACHANNEL_STEP(snla) - tdn->trackIndex);
630
631                 if (delta_y1 || delta_y2) {
632                         NlaTrack *track;
633                         int delta = (delta_y2) ? delta_y2 : delta_y1;
634                         int n;
635
636                         /* move in the requested direction, checking at each layer if there's space for strip to pass through,
637                          * stopping on the last track available or that we're able to fit in
638                          */
639                         if (delta > 0) {
640                                 for (track = tdn->nlt->next, n = 0; (track) && (n < delta); track = track->next, n++) {
641                                         /* check if space in this track for the strip */
642                                         if (BKE_nlatrack_has_space(track, strip->start, strip->end)) {
643                                                 /* move strip to this track */
644                                                 BLI_remlink(&tdn->nlt->strips, strip);
645                                                 BKE_nlatrack_add_strip(track, strip);
646
647                                                 tdn->nlt = track;
648                                                 tdn->trackIndex++;
649                                         }
650                                         else /* can't move any further */
651                                                 break;
652                                 }
653                         }
654                         else {
655                                 /* make delta 'positive' before using it, since we now know to go backwards */
656                                 delta = -delta;
657
658                                 for (track = tdn->nlt->prev, n = 0; (track) && (n < delta); track = track->prev, n++) {
659                                         /* check if space in this track for the strip */
660                                         if (BKE_nlatrack_has_space(track, strip->start, strip->end)) {
661                                                 /* move strip to this track */
662                                                 BLI_remlink(&tdn->nlt->strips, strip);
663                                                 BKE_nlatrack_add_strip(track, strip);
664
665                                                 tdn->nlt = track;
666                                                 tdn->trackIndex--;
667                                         }
668                                         else /* can't move any further */
669                                                 break;
670                                 }
671                         }
672                 }
673         }
674 }
675
676 static void recalcData_mask_common(TransInfo *t)
677 {
678         Mask *mask = CTX_data_edit_mask(t->context);
679
680         flushTransMasking(t);
681
682         DEG_id_tag_update(&mask->id, 0);
683 }
684
685 /* helper for recalcData() - for Image Editor transforms */
686 static void recalcData_image(TransInfo *t)
687 {
688         if (t->options & CTX_MASK) {
689                 recalcData_mask_common(t);
690         }
691         else if (t->options & CTX_PAINT_CURVE) {
692                 flushTransPaintCurve(t);
693         }
694         else if ((t->flag & T_EDIT) && t->obedit_type == OB_MESH) {
695                 SpaceImage *sima = t->sa->spacedata.first;
696
697                 flushTransUVs(t);
698                 if (sima->flag & SI_LIVE_UNWRAP)
699                         ED_uvedit_live_unwrap_re_solve();
700
701                 FOREACH_TRANS_DATA_CONTAINER (t, tc) {
702                         if (tc->data_len) {
703                                 DEG_id_tag_update(tc->obedit->data, 0);
704                         }
705                 }
706         }
707 }
708
709 /* helper for recalcData() - for Movie Clip transforms */
710 static void recalcData_spaceclip(TransInfo *t)
711 {
712         SpaceClip *sc = t->sa->spacedata.first;
713
714         if (ED_space_clip_check_show_trackedit(sc)) {
715                 MovieClip *clip = ED_space_clip_get_clip(sc);
716                 ListBase *tracksbase = BKE_tracking_get_active_tracks(&clip->tracking);
717                 MovieTrackingTrack *track;
718                 int framenr = ED_space_clip_get_clip_frame_number(sc);
719
720                 flushTransTracking(t);
721
722                 track = tracksbase->first;
723                 while (track) {
724                         if (TRACK_VIEW_SELECTED(sc, track) && (track->flag & TRACK_LOCKED) == 0) {
725                                 MovieTrackingMarker *marker = BKE_tracking_marker_get(track, framenr);
726
727                                 if (t->mode == TFM_TRANSLATION) {
728                                         if (TRACK_AREA_SELECTED(track, TRACK_AREA_PAT))
729                                                 BKE_tracking_marker_clamp(marker, CLAMP_PAT_POS);
730                                         if (TRACK_AREA_SELECTED(track, TRACK_AREA_SEARCH))
731                                                 BKE_tracking_marker_clamp(marker, CLAMP_SEARCH_POS);
732                                 }
733                                 else if (t->mode == TFM_RESIZE) {
734                                         if (TRACK_AREA_SELECTED(track, TRACK_AREA_PAT))
735                                                 BKE_tracking_marker_clamp(marker, CLAMP_PAT_DIM);
736                                         if (TRACK_AREA_SELECTED(track, TRACK_AREA_SEARCH))
737                                                 BKE_tracking_marker_clamp(marker, CLAMP_SEARCH_DIM);
738                                 }
739                                 else if (t->mode == TFM_ROTATION) {
740                                         if (TRACK_AREA_SELECTED(track, TRACK_AREA_PAT))
741                                                 BKE_tracking_marker_clamp(marker, CLAMP_PAT_POS);
742                                 }
743                         }
744
745                         track = track->next;
746                 }
747
748                 DEG_id_tag_update(&clip->id, 0);
749         }
750         else if (t->options & CTX_MASK) {
751                 recalcData_mask_common(t);
752         }
753 }
754
755 /* helper for recalcData() - for object transforms, typically in the 3D view */
756 static void recalcData_objects(TransInfo *t)
757 {
758         Base *base = t->view_layer->basact;
759
760         if (t->obedit_type != -1) {
761                 if (ELEM(t->obedit_type, OB_CURVE, OB_SURF)) {
762
763                         if (t->state != TRANS_CANCEL) {
764                                 clipMirrorModifier(t);
765                                 applyProject(t);
766                         }
767
768                         FOREACH_TRANS_DATA_CONTAINER (t, tc) {
769                                 Curve *cu = tc->obedit->data;
770                                 ListBase *nurbs = BKE_curve_editNurbs_get(cu);
771                                 Nurb *nu = nurbs->first;
772
773                                 DEG_id_tag_update(tc->obedit->data, 0);  /* sets recalc flags */
774
775                                 if (t->state == TRANS_CANCEL) {
776                                         while (nu) {
777                                                 /* Cant do testhandlesNurb here, it messes up the h1 and h2 flags */
778                                                 BKE_nurb_handles_calc(nu);
779                                                 nu = nu->next;
780                                         }
781                                 }
782                                 else {
783                                         /* Normal updating */
784                                         while (nu) {
785                                                 BKE_nurb_test_2d(nu);
786                                                 BKE_nurb_handles_calc(nu);
787                                                 nu = nu->next;
788                                         }
789                                 }
790                         }
791                 }
792                 else if (t->obedit_type == OB_LATTICE) {
793
794                         if (t->state != TRANS_CANCEL) {
795                                 applyProject(t);
796                         }
797
798                         FOREACH_TRANS_DATA_CONTAINER (t, tc) {
799                                 Lattice *la = tc->obedit->data;
800                                 DEG_id_tag_update(tc->obedit->data, 0);  /* sets recalc flags */
801                                 if (la->editlatt->latt->flag & LT_OUTSIDE) {
802                                         outside_lattice(la->editlatt->latt);
803                                 }
804                         }
805                 }
806                 else if (t->obedit_type == OB_MESH) {
807                         /* mirror modifier clipping? */
808                         if (t->state != TRANS_CANCEL) {
809                                 /* apply clipping after so we never project past the clip plane [#25423] */
810                                 applyProject(t);
811                                 clipMirrorModifier(t);
812                         }
813                         if ((t->flag & T_NO_MIRROR) == 0 &&
814                             (t->options & CTX_NO_MIRROR) == 0)
815                         {
816                                 editbmesh_apply_to_mirror(t);
817                         }
818
819                         if (t->mode == TFM_EDGE_SLIDE) {
820                                 projectEdgeSlideData(t, false);
821                         }
822                         else if (t->mode == TFM_VERT_SLIDE) {
823                                 projectVertSlideData(t, false);
824                         }
825
826                         FOREACH_TRANS_DATA_CONTAINER (t, tc) {
827                                 DEG_id_tag_update(tc->obedit->data, 0);  /* sets recalc flags */
828                                 BMEditMesh *em = BKE_editmesh_from_object(tc->obedit);
829                                 EDBM_mesh_normals_update(em);
830                                 BKE_editmesh_tessface_calc(em);
831                         }
832                 }
833                 else if (t->obedit_type == OB_ARMATURE) { /* no recalc flag, does pose */
834
835                         if (t->state != TRANS_CANCEL) {
836                                 applyProject(t);
837                         }
838
839                         FOREACH_TRANS_DATA_CONTAINER (t, tc) {
840                                 bArmature *arm = tc->obedit->data;
841                                 ListBase *edbo = arm->edbo;
842                                 EditBone *ebo, *ebo_parent;
843                                 TransData *td = tc->data;
844                                 int i;
845
846                                 /* Ensure all bones are correctly adjusted */
847                                 for (ebo = edbo->first; ebo; ebo = ebo->next) {
848                                         ebo_parent = (ebo->flag & BONE_CONNECTED) ? ebo->parent : NULL;
849
850                                         if (ebo_parent) {
851                                                 /* If this bone has a parent tip that has been moved */
852                                                 if (ebo_parent->flag & BONE_TIPSEL) {
853                                                         copy_v3_v3(ebo->head, ebo_parent->tail);
854                                                         if (t->mode == TFM_BONE_ENVELOPE) ebo->rad_head = ebo_parent->rad_tail;
855                                                 }
856                                                 /* If this bone has a parent tip that has NOT been moved */
857                                                 else {
858                                                         copy_v3_v3(ebo_parent->tail, ebo->head);
859                                                         if (t->mode == TFM_BONE_ENVELOPE) ebo_parent->rad_tail = ebo->rad_head;
860                                                 }
861                                         }
862
863                                         /* on extrude bones, oldlength==0.0f, so we scale radius of points */
864                                         ebo->length = len_v3v3(ebo->head, ebo->tail);
865                                         if (ebo->oldlength == 0.0f) {
866                                                 ebo->rad_head = 0.25f * ebo->length;
867                                                 ebo->rad_tail = 0.10f * ebo->length;
868                                                 ebo->dist = 0.25f * ebo->length;
869                                                 if (ebo->parent) {
870                                                         if (ebo->rad_head > ebo->parent->rad_tail)
871                                                                 ebo->rad_head = ebo->parent->rad_tail;
872                                                 }
873                                         }
874                                         else if (t->mode != TFM_BONE_ENVELOPE) {
875                                                 /* if bones change length, lets do that for the deform distance as well */
876                                                 ebo->dist *= ebo->length / ebo->oldlength;
877                                                 ebo->rad_head *= ebo->length / ebo->oldlength;
878                                                 ebo->rad_tail *= ebo->length / ebo->oldlength;
879                                                 ebo->oldlength = ebo->length;
880
881                                                 if (ebo_parent) {
882                                                         ebo_parent->rad_tail = ebo->rad_head;
883                                                 }
884                                         }
885                                 }
886
887                                 if (!ELEM(t->mode, TFM_BONE_ROLL, TFM_BONE_ENVELOPE, TFM_BONE_ENVELOPE_DIST, TFM_BONESIZE)) {
888                                         /* fix roll */
889                                         for (i = 0; i < tc->data_len; i++, td++) {
890                                                 if (td->extra) {
891                                                         float vec[3], up_axis[3];
892                                                         float qrot[4];
893                                                         float roll;
894
895                                                         ebo = td->extra;
896
897                                                         if (t->state == TRANS_CANCEL) {
898                                                                 /* restore roll */
899                                                                 ebo->roll = td->ival;
900                                                         }
901                                                         else {
902                                                                 copy_v3_v3(up_axis, td->axismtx[2]);
903
904                                                                 sub_v3_v3v3(vec, ebo->tail, ebo->head);
905                                                                 normalize_v3(vec);
906                                                                 rotation_between_vecs_to_quat(qrot, td->axismtx[1], vec);
907                                                                 mul_qt_v3(qrot, up_axis);
908
909                                                                 /* roll has a tendency to flip in certain orientations - [#34283], [#33974] */
910                                                                 roll = ED_armature_ebone_roll_to_vector(ebo, up_axis, false);
911                                                                 ebo->roll = angle_compat_rad(roll, td->ival);
912                                                         }
913                                                 }
914                                         }
915                                 }
916
917                                 if (arm->flag & ARM_MIRROR_EDIT) {
918                                         if (t->state != TRANS_CANCEL) {
919                                                 ED_armature_edit_transform_mirror_update(tc->obedit);
920                                         }
921                                         else {
922                                                 restoreBones(tc);
923                                         }
924                                 }
925                         }
926                 }
927                 else {
928                         if (t->state != TRANS_CANCEL) {
929                                 applyProject(t);
930                         }
931                         FOREACH_TRANS_DATA_CONTAINER (t, tc) {
932                                 if (tc->data_len) {
933                                         DEG_id_tag_update(tc->obedit->data, 0);  /* sets recalc flags */
934                                 }
935                         }
936                 }
937
938         }
939         else if (t->flag & T_POSE) {
940                 GSet *motionpath_updates = BLI_gset_ptr_new("motionpath updates");
941
942                 FOREACH_TRANS_DATA_CONTAINER (t, tc) {
943                         Object *ob = tc->poseobj;
944                         bArmature *arm = ob->data;
945
946                         /* if animtimer is running, and the object already has animation data,
947                          * check if the auto-record feature means that we should record 'samples'
948                          * (i.e. uneditable animation values)
949                          *
950                          * context is needed for keying set poll() functions.
951                          */
952                         // TODO: autokeyframe calls need some setting to specify to add samples (FPoints) instead of keyframes?
953                         if ((t->animtimer) && (t->context) && IS_AUTOKEY_ON(t->scene)) {
954                                 int targetless_ik = (t->flag & T_AUTOIK); // XXX this currently doesn't work, since flags aren't set yet!
955
956                                 animrecord_check_state(t->scene, &ob->id, t->animtimer);
957                                 autokeyframe_pose(t->context, t->scene, ob, t->mode, targetless_ik);
958                         }
959
960                         if (motionpath_need_update_pose(t->scene, ob)) {
961                                 BLI_gset_insert(motionpath_updates, ob);
962                         }
963
964                         /* old optimize trick... this enforces to bypass the depgraph */
965                         if (!(arm->flag & ARM_DELAYDEFORM)) {
966                                 DEG_id_tag_update(&ob->id, ID_RECALC_GEOMETRY);  /* sets recalc flags */
967                                 /* transformation of pose may affect IK tree, make sure it is rebuilt */
968                                 BIK_clear_data(ob->pose);
969                         }
970                         else {
971                                 BKE_pose_where_is(t->depsgraph, t->scene, ob);
972                         }
973                 }
974
975                 /* Update motion paths once for all transformed bones in an object. */
976                 GSetIterator gs_iter;
977                 GSET_ITER (gs_iter, motionpath_updates) {
978                         Object *ob = BLI_gsetIterator_getKey(&gs_iter);
979                         ED_pose_recalculate_paths(t->context, t->scene, ob, true);
980                 }
981                 BLI_gset_free(motionpath_updates, NULL);
982         }
983         else if (base && (base->object->mode & OB_MODE_PARTICLE_EDIT) &&
984                  PE_get_current(t->scene, base->object))
985         {
986                 if (t->state != TRANS_CANCEL) {
987                         applyProject(t);
988                 }
989                 flushTransParticles(t);
990         }
991         else {
992                 bool motionpath_update = false;
993
994                 if (t->state != TRANS_CANCEL) {
995                         applyProject(t);
996                 }
997
998                 FOREACH_TRANS_DATA_CONTAINER (t, tc) {
999                         TransData *td = tc->data;
1000
1001                         for (int i = 0; i < tc->data_len; i++, td++) {
1002                                 Object *ob = td->ob;
1003
1004                                 if (td->flag & TD_NOACTION)
1005                                         break;
1006
1007                                 if (td->flag & TD_SKIP)
1008                                         continue;
1009
1010                                 /* if animtimer is running, and the object already has animation data,
1011                                  * check if the auto-record feature means that we should record 'samples'
1012                                  * (i.e. uneditable animation values)
1013                                  */
1014                                 // TODO: autokeyframe calls need some setting to specify to add samples (FPoints) instead of keyframes?
1015                                 if ((t->animtimer) && IS_AUTOKEY_ON(t->scene)) {
1016                                         animrecord_check_state(t->scene, &ob->id, t->animtimer);
1017                                         autokeyframe_object(t->context, t->scene, t->view_layer, ob, t->mode);
1018                                 }
1019
1020                                 motionpath_update |= motionpath_need_update_object(t->scene, ob);
1021
1022                                 /* sets recalc flags fully, instead of flushing existing ones
1023                                  * otherwise proxies don't function correctly
1024                                  */
1025                                 DEG_id_tag_update(&ob->id, ID_RECALC_TRANSFORM);
1026
1027                                 if (t->flag & T_TEXTURE)
1028                                         DEG_id_tag_update(&ob->id, ID_RECALC_GEOMETRY);
1029                         }
1030                 }
1031
1032                 if (motionpath_update) {
1033                         /* Update motion paths once for all transformed objects. */
1034                         ED_objects_recalculate_paths(t->context, t->scene, true);
1035                 }
1036         }
1037 }
1038
1039 static void recalcData_cursor(TransInfo *t)
1040 {
1041         DEG_id_tag_update(&t->scene->id, ID_RECALC_COPY_ON_WRITE);
1042 }
1043
1044 /* helper for recalcData() - for sequencer transforms */
1045 static void recalcData_sequencer(TransInfo *t)
1046 {
1047         TransData *td;
1048         int a;
1049         Sequence *seq_prev = NULL;
1050
1051         TransDataContainer *tc = TRANS_DATA_CONTAINER_FIRST_SINGLE(t);
1052
1053         for (a = 0, td = tc->data; a < tc->data_len; a++, td++) {
1054                 TransDataSeq *tdsq = (TransDataSeq *) td->extra;
1055                 Sequence *seq = tdsq->seq;
1056
1057                 if (seq != seq_prev) {
1058                         if (BKE_sequence_tx_fullupdate_test(seq)) {
1059                                 /* A few effect strip types need a complete recache on transform. */
1060                                 BKE_sequence_invalidate_cache(t->scene, seq);
1061                         }
1062                         else {
1063                                 BKE_sequence_invalidate_dependent(t->scene, seq);
1064                         }
1065                 }
1066
1067                 seq_prev = seq;
1068         }
1069
1070         BKE_sequencer_preprocessed_cache_cleanup();
1071
1072         flushTransSeq(t);
1073 }
1074
1075 /* force recalculation of triangles during transformation */
1076 static void recalcData_gpencil_strokes(TransInfo *t)
1077 {
1078         TransDataContainer *tc = TRANS_DATA_CONTAINER_FIRST_SINGLE(t);
1079
1080         TransData *td = tc->data;
1081         for (int i = 0; i < tc->data_len; i++, td++) {
1082                 bGPDstroke *gps = td->extra;
1083                 if (gps != NULL) {
1084                         gps->flag |= GP_STROKE_RECALC_GEOMETRY;
1085                 }
1086         }
1087 }
1088
1089 /* called for updating while transform acts, once per redraw */
1090 void recalcData(TransInfo *t)
1091 {
1092         /* if tests must match createTransData for correct updates */
1093         if (t->options & CTX_CURSOR) {
1094                 recalcData_cursor(t);
1095         }
1096         else if (t->options & CTX_TEXTURE) {
1097                 recalcData_objects(t);
1098         }
1099         else if (t->options & CTX_EDGE) {
1100                 recalcData_objects(t);
1101         }
1102         else if (t->options & CTX_PAINT_CURVE) {
1103                 flushTransPaintCurve(t);
1104         }
1105         else if (t->options & CTX_GPENCIL_STROKES) {
1106                 /* set recalc triangle cache flag */
1107                 recalcData_gpencil_strokes(t);
1108         }
1109         else if (t->spacetype == SPACE_IMAGE) {
1110                 recalcData_image(t);
1111         }
1112         else if (t->spacetype == SPACE_ACTION) {
1113                 recalcData_actedit(t);
1114         }
1115         else if (t->spacetype == SPACE_NLA) {
1116                 recalcData_nla(t);
1117         }
1118         else if (t->spacetype == SPACE_SEQ) {
1119                 recalcData_sequencer(t);
1120         }
1121         else if (t->spacetype == SPACE_GRAPH) {
1122                 recalcData_graphedit(t);
1123         }
1124         else if (t->spacetype == SPACE_NODE) {
1125                 flushTransNodes(t);
1126         }
1127         else if (t->spacetype == SPACE_CLIP) {
1128                 recalcData_spaceclip(t);
1129         }
1130         else {
1131                 recalcData_objects(t);
1132         }
1133 }
1134
1135 void drawLine(TransInfo *t, const float center[3], const float dir[3], char axis, short options)
1136 {
1137         float v1[3], v2[3], v3[3];
1138         unsigned char col[3], col2[3];
1139
1140         if (t->spacetype == SPACE_VIEW3D) {
1141                 View3D *v3d = t->view;
1142
1143                 GPU_matrix_push();
1144
1145                 copy_v3_v3(v3, dir);
1146                 mul_v3_fl(v3, v3d->clip_end);
1147
1148                 sub_v3_v3v3(v2, center, v3);
1149                 add_v3_v3v3(v1, center, v3);
1150
1151                 if (options & DRAWLIGHT) {
1152                         col[0] = col[1] = col[2] = 220;
1153                 }
1154                 else {
1155                         UI_GetThemeColor3ubv(TH_GRID, col);
1156                 }
1157                 UI_make_axis_color(col, col2, axis);
1158
1159                 uint pos = GPU_vertformat_attr_add(immVertexFormat(), "pos", GPU_COMP_F32, 3, GPU_FETCH_FLOAT);
1160
1161                 immBindBuiltinProgram(GPU_SHADER_3D_UNIFORM_COLOR);
1162                 immUniformColor3ubv(col2);
1163
1164                 immBegin(GPU_PRIM_LINES, 2);
1165                 immVertex3fv(pos, v1);
1166                 immVertex3fv(pos, v2);
1167                 immEnd();
1168
1169                 immUnbindProgram();
1170
1171                 GPU_matrix_pop();
1172         }
1173 }
1174
1175 /**
1176  * Free data before switching to another mode.
1177  */
1178 void resetTransModal(TransInfo *t)
1179 {
1180         freeTransCustomDataForMode(t);
1181 }
1182
1183 void resetTransRestrictions(TransInfo *t)
1184 {
1185         t->flag &= ~T_ALL_RESTRICTIONS;
1186 }
1187
1188 static int initTransInfo_edit_pet_to_flag(const int proportional)
1189 {
1190         switch (proportional) {
1191                 case PROP_EDIT_ON:
1192                         return T_PROP_EDIT;
1193                 case PROP_EDIT_CONNECTED:
1194                         return T_PROP_EDIT | T_PROP_CONNECTED;
1195                 case PROP_EDIT_PROJECTED:
1196                         return T_PROP_EDIT | T_PROP_PROJECTED;
1197                 default:
1198                         return 0;
1199         }
1200 }
1201
1202 void initTransDataContainers_FromObjectData(TransInfo *t, Object *obact, Object **objects, uint objects_len)
1203 {
1204         const eObjectMode object_mode = obact ? obact->mode : OB_MODE_OBJECT;
1205         const short object_type = obact ? obact->type : -1;
1206
1207         if ((object_mode & OB_MODE_EDIT) || (t->options & CTX_GPENCIL_STROKES) ||
1208             ((object_mode & OB_MODE_POSE) && (object_type == OB_ARMATURE)))
1209         {
1210                 if (t->data_container) {
1211                         MEM_freeN(t->data_container);
1212                 }
1213
1214                 bool free_objects = false;
1215                 if (objects == NULL) {
1216                         objects = BKE_view_layer_array_from_objects_in_mode(
1217                                 t->view_layer,
1218                                 (t->spacetype == SPACE_VIEW3D) ? t->view : NULL,
1219                                 &objects_len, {
1220                                     .object_mode = object_mode,
1221                                     .no_dup_data = true,
1222                                 });
1223                         free_objects = true;
1224                 }
1225
1226                 t->data_container = MEM_callocN(sizeof(*t->data_container) * objects_len, __func__);
1227                 t->data_container_len = objects_len;
1228
1229                 for (int i = 0; i < objects_len; i++) {
1230                         TransDataContainer *tc = &t->data_container[i];
1231                         /* TODO, multiple axes. */
1232                         tc->mirror.axis_flag = (
1233                                 ((t->flag & T_NO_MIRROR) == 0) &&
1234                                 ((t->options & CTX_NO_MIRROR) == 0) &&
1235                                 (((Mesh *)objects[i]->data)->editflag & ME_EDIT_MIRROR_X) != 0);
1236
1237                         if (object_mode & OB_MODE_EDIT) {
1238                                 tc->obedit = objects[i];
1239                                 /* Check needed for UV's */
1240                                 if ((t->flag & T_2D_EDIT) == 0) {
1241                                         tc->use_local_mat = true;
1242                                 }
1243                         }
1244                         else if (object_mode & OB_MODE_POSE) {
1245                                 tc->poseobj = objects[i];
1246                                 tc->use_local_mat = true;
1247                         }
1248                         else if (t->options & CTX_GPENCIL_STROKES) {
1249                                 tc->use_local_mat = true;
1250                         }
1251
1252                         if (tc->use_local_mat) {
1253                                 BLI_assert((t->flag & T_2D_EDIT) == 0);
1254                                 copy_m4_m4(tc->mat, objects[i]->obmat);
1255                                 copy_m3_m4(tc->mat3, tc->mat);
1256                                 invert_m4_m4(tc->imat, tc->mat);
1257                                 invert_m3_m3(tc->imat3, tc->mat3);
1258                                 normalize_m3_m3(tc->mat3_unit, tc->mat3);
1259                         }
1260                         /* Otherwise leave as zero. */
1261                 }
1262
1263                 if (free_objects) {
1264                         MEM_freeN(objects);
1265                 }
1266         }
1267 }
1268
1269 /**
1270  * Setup internal data, mouse, vectors
1271  *
1272  * \note \a op and \a event can be NULL
1273  *
1274  * \see #saveTransform does the reverse.
1275  */
1276 void initTransInfo(bContext *C, TransInfo *t, wmOperator *op, const wmEvent *event)
1277 {
1278         Depsgraph *depsgraph = CTX_data_depsgraph(C);
1279         Scene *sce = CTX_data_scene(C);
1280         ViewLayer *view_layer = CTX_data_view_layer(C);
1281         const eObjectMode object_mode = OBACT(view_layer) ? OBACT(view_layer)->mode : OB_MODE_OBJECT;
1282         const short object_type = OBACT(view_layer) ? OBACT(view_layer)->type : -1;
1283         ToolSettings *ts = CTX_data_tool_settings(C);
1284         ARegion *ar = CTX_wm_region(C);
1285         ScrArea *sa = CTX_wm_area(C);
1286
1287         bGPdata *gpd = CTX_data_gpencil_data(C);
1288         PropertyRNA *prop;
1289
1290         t->depsgraph = depsgraph;
1291         t->scene = sce;
1292         t->view_layer = view_layer;
1293         t->sa = sa;
1294         t->ar = ar;
1295         t->settings = ts;
1296         t->reports = op ? op->reports : NULL;
1297
1298         t->helpline = HLP_NONE;
1299
1300         t->flag = 0;
1301
1302         t->obedit_type = ((object_mode == OB_MODE_EDIT) || (object_mode == OB_MODE_EDIT_GPENCIL)) ? object_type : -1;
1303
1304         /* Many kinds of transform only use a single handle. */
1305         if (t->data_container == NULL) {
1306                 t->data_container = MEM_callocN(sizeof(*t->data_container), __func__);
1307                 t->data_container_len = 1;
1308         }
1309
1310         t->redraw = TREDRAW_HARD;  /* redraw first time */
1311
1312         if (event) {
1313                 t->mouse.imval[0] = event->mval[0];
1314                 t->mouse.imval[1] = event->mval[1];
1315         }
1316         else {
1317                 t->mouse.imval[0] = 0;
1318                 t->mouse.imval[1] = 0;
1319         }
1320
1321         t->con.imval[0] = t->mouse.imval[0];
1322         t->con.imval[1] = t->mouse.imval[1];
1323
1324         t->mval[0] = t->mouse.imval[0];
1325         t->mval[1] = t->mouse.imval[1];
1326
1327         t->transform        = NULL;
1328         t->handleEvent      = NULL;
1329
1330         t->data_len_all = 0;
1331
1332         t->val = 0.0f;
1333
1334         zero_v3(t->vec);
1335         zero_v3(t->center_global);
1336
1337         unit_m3(t->mat);
1338
1339         /* if there's an event, we're modal */
1340         if (event) {
1341                 t->flag |= T_MODAL;
1342         }
1343
1344         /* Crease needs edge flag */
1345         if (ELEM(t->mode, TFM_CREASE, TFM_BWEIGHT)) {
1346                 t->options |= CTX_EDGE;
1347         }
1348
1349         t->remove_on_cancel = false;
1350
1351         if (op && (prop = RNA_struct_find_property(op->ptr, "remove_on_cancel")) && RNA_property_is_set(op->ptr, prop)) {
1352                 if (RNA_property_boolean_get(op->ptr, prop)) {
1353                         t->remove_on_cancel = true;
1354                 }
1355         }
1356
1357         /* GPencil editing context */
1358         if (GPENCIL_EDIT_MODE(gpd)) {
1359                 t->options |= CTX_GPENCIL_STROKES;
1360         }
1361
1362         /* Assign the space type, some exceptions for running in different mode */
1363         if (sa == NULL) {
1364                 /* background mode */
1365                 t->spacetype = SPACE_EMPTY;
1366         }
1367         else if ((ar == NULL) && (sa->spacetype == SPACE_VIEW3D)) {
1368                 /* running in the text editor */
1369                 t->spacetype = SPACE_EMPTY;
1370         }
1371         else {
1372                 /* normal operation */
1373                 t->spacetype = sa->spacetype;
1374         }
1375
1376         /* handle T_ALT_TRANSFORM initialization, we may use for different operators */
1377         if (op) {
1378                 const char *prop_id = NULL;
1379                 if (t->mode == TFM_SHRINKFATTEN) {
1380                         prop_id = "use_even_offset";
1381                 }
1382
1383                 if (prop_id && (prop = RNA_struct_find_property(op->ptr, prop_id))) {
1384                         SET_FLAG_FROM_TEST(t->flag, RNA_property_boolean_get(op->ptr, prop), T_ALT_TRANSFORM);
1385                 }
1386         }
1387
1388         if (t->spacetype == SPACE_VIEW3D) {
1389                 View3D *v3d = sa->spacedata.first;
1390                 bScreen *animscreen = ED_screen_animation_playing(CTX_wm_manager(C));
1391
1392                 t->view = v3d;
1393                 t->animtimer = (animscreen) ? animscreen->animtimer : NULL;
1394
1395                 /* turn gizmo off during transform */
1396                 if (t->flag & T_MODAL) {
1397                         t->gizmo_flag = v3d->gizmo_flag;
1398                         v3d->gizmo_flag = V3D_GIZMO_HIDE;
1399                 }
1400
1401                 if (t->scene->toolsettings->transform_flag & SCE_XFORM_AXIS_ALIGN) {
1402                         t->flag |= T_V3D_ALIGN;
1403                 }
1404                 t->around = t->scene->toolsettings->transform_pivot_point;
1405
1406                 /* bend always uses the cursor */
1407                 if (t->mode == TFM_BEND) {
1408                         t->around = V3D_AROUND_CURSOR;
1409                 }
1410
1411                 TransformOrientationSlot *orient_slot = &t->scene->orientation_slots[SCE_ORIENT_DEFAULT];
1412                 t->orientation.user = orient_slot->type;
1413                 t->orientation.custom = BKE_scene_transform_orientation_find(t->scene, orient_slot->index_custom);
1414
1415                 t->orientation.index = 0;
1416                 ARRAY_SET_ITEMS(
1417                         t->orientation.types,
1418                         &t->orientation.user,
1419                         NULL);
1420
1421                 /* Make second orientation local if both are global. */
1422                 if (t->orientation.user == V3D_ORIENT_GLOBAL) {
1423                         t->orientation.user_alt = V3D_ORIENT_LOCAL;
1424                         t->orientation.types[0] = &t->orientation.user_alt;
1425                         SWAP(short *, t->orientation.types[0], t->orientation.types[1]);
1426                 }
1427
1428                 /* exceptional case */
1429                 if (t->around == V3D_AROUND_LOCAL_ORIGINS) {
1430                         if (ELEM(t->mode, TFM_ROTATION, TFM_RESIZE, TFM_TRACKBALL)) {
1431                                 const bool use_island = transdata_check_local_islands(t, t->around);
1432
1433                                 if ((t->obedit_type != -1) && !use_island) {
1434                                         t->options |= CTX_NO_PET;
1435                                 }
1436                         }
1437                 }
1438
1439                 if (object_mode & OB_MODE_ALL_PAINT) {
1440                         Paint *p = BKE_paint_get_active_from_context(C);
1441                         if (p && p->brush && (p->brush->flag & BRUSH_CURVE)) {
1442                                 t->options |= CTX_PAINT_CURVE;
1443                         }
1444                 }
1445
1446                 /* initialize UV transform from */
1447                 if (op && ((prop = RNA_struct_find_property(op->ptr, "correct_uv")))) {
1448                         if (RNA_property_is_set(op->ptr, prop)) {
1449                                 if (RNA_property_boolean_get(op->ptr, prop)) {
1450                                         t->settings->uvcalc_flag |= UVCALC_TRANSFORM_CORRECT;
1451                                 }
1452                                 else {
1453                                         t->settings->uvcalc_flag &= ~UVCALC_TRANSFORM_CORRECT;
1454                                 }
1455                         }
1456                         else {
1457                                 RNA_property_boolean_set(op->ptr, prop, (t->settings->uvcalc_flag & UVCALC_TRANSFORM_CORRECT) != 0);
1458                         }
1459                 }
1460
1461         }
1462         else if (t->spacetype == SPACE_IMAGE) {
1463                 SpaceImage *sima = sa->spacedata.first;
1464                 // XXX for now, get View2D from the active region
1465                 t->view = &ar->v2d;
1466                 t->around = sima->around;
1467
1468                 if (ED_space_image_show_uvedit(sima, OBACT(t->view_layer))) {
1469                         /* UV transform */
1470                 }
1471                 else if (sima->mode == SI_MODE_MASK) {
1472                         t->options |= CTX_MASK;
1473                 }
1474                 else if (sima->mode == SI_MODE_PAINT) {
1475                         Paint *p = &sce->toolsettings->imapaint.paint;
1476                         if (p->brush && (p->brush->flag & BRUSH_CURVE)) {
1477                                 t->options |= CTX_PAINT_CURVE;
1478                         }
1479                 }
1480                 /* image not in uv edit, nor in mask mode, can happen for some tools */
1481         }
1482         else if (t->spacetype == SPACE_NODE) {
1483                 // XXX for now, get View2D from the active region
1484                 t->view = &ar->v2d;
1485                 t->around = V3D_AROUND_CENTER_BOUNDS;
1486         }
1487         else if (t->spacetype == SPACE_GRAPH) {
1488                 SpaceGraph *sipo = sa->spacedata.first;
1489                 t->view = &ar->v2d;
1490                 t->around = sipo->around;
1491         }
1492         else if (t->spacetype == SPACE_CLIP) {
1493                 SpaceClip *sclip = sa->spacedata.first;
1494                 t->view = &ar->v2d;
1495                 t->around = sclip->around;
1496
1497                 if (ED_space_clip_check_show_trackedit(sclip))
1498                         t->options |= CTX_MOVIECLIP;
1499                 else if (ED_space_clip_check_show_maskedit(sclip))
1500                         t->options |= CTX_MASK;
1501         }
1502         else {
1503                 if (ar) {
1504                         // XXX for now, get View2D  from the active region
1505                         t->view = &ar->v2d;
1506                         // XXX for now, the center point is the midpoint of the data
1507                 }
1508                 else {
1509                         t->view = NULL;
1510                 }
1511                 t->around = V3D_AROUND_CENTER_BOUNDS;
1512         }
1513
1514         if (op && ((prop = RNA_struct_find_property(op->ptr, "constraint_matrix")) &&
1515                    RNA_property_is_set(op->ptr, prop)))
1516         {
1517                 RNA_property_float_get_array(op->ptr, prop, &t->spacemtx[0][0]);
1518                 t->orientation.user = V3D_ORIENT_CUSTOM_MATRIX;
1519                 t->orientation.custom = 0;
1520         }
1521         else if (op && ((prop = RNA_struct_find_property(op->ptr, "constraint_orientation")) &&
1522                         RNA_property_is_set(op->ptr, prop)))
1523         {
1524                 short orientation = RNA_property_enum_get(op->ptr, prop);
1525                 TransformOrientation *custom_orientation = NULL;
1526
1527                 if (orientation >= V3D_ORIENT_CUSTOM) {
1528                         if (orientation >= V3D_ORIENT_CUSTOM + BIF_countTransformOrientation(C)) {
1529                                 orientation = V3D_ORIENT_GLOBAL;
1530                         }
1531                         else {
1532                                 custom_orientation = BKE_scene_transform_orientation_find(
1533                                         t->scene, orientation - V3D_ORIENT_CUSTOM);
1534                                 orientation = V3D_ORIENT_CUSTOM;
1535                         }
1536                 }
1537
1538                 t->orientation.user = orientation;
1539                 t->orientation.custom = custom_orientation;
1540         }
1541
1542         if (op && ((prop = RNA_struct_find_property(op->ptr, "release_confirm")) &&
1543                    RNA_property_is_set(op->ptr, prop)))
1544         {
1545                 if (RNA_property_boolean_get(op->ptr, prop)) {
1546                         t->flag |= T_RELEASE_CONFIRM;
1547                 }
1548         }
1549         else {
1550                 if (U.flag & USER_RELEASECONFIRM) {
1551                         t->flag |= T_RELEASE_CONFIRM;
1552                 }
1553         }
1554
1555         if (op && ((prop = RNA_struct_find_property(op->ptr, "mirror")) &&
1556                    RNA_property_is_set(op->ptr, prop)))
1557         {
1558                 if (!RNA_property_boolean_get(op->ptr, prop)) {
1559                         t->flag |= T_NO_MIRROR;
1560                 }
1561         }
1562         else if ((t->spacetype == SPACE_VIEW3D) && (t->obedit_type == OB_MESH)) {
1563                 /* pass */
1564         }
1565         else {
1566                 /* Avoid mirroring for unsupported contexts. */
1567                 t->options |= CTX_NO_MIRROR;
1568         }
1569
1570         /* setting PET flag only if property exist in operator. Otherwise, assume it's not supported */
1571         if (op && (prop = RNA_struct_find_property(op->ptr, "proportional"))) {
1572                 if (RNA_property_is_set(op->ptr, prop)) {
1573                         t->flag |= initTransInfo_edit_pet_to_flag(RNA_property_enum_get(op->ptr, prop));
1574                 }
1575                 else {
1576                         /* use settings from scene only if modal */
1577                         if (t->flag & T_MODAL) {
1578                                 if ((t->options & CTX_NO_PET) == 0) {
1579                                         if (t->spacetype == SPACE_GRAPH) {
1580                                                 t->flag |= initTransInfo_edit_pet_to_flag(ts->proportional_fcurve);
1581                                         }
1582                                         else if (t->spacetype == SPACE_ACTION) {
1583                                                 t->flag |= initTransInfo_edit_pet_to_flag(ts->proportional_action);
1584                                         }
1585                                         else if (t->obedit_type != -1) {
1586                                                 t->flag |= initTransInfo_edit_pet_to_flag(ts->proportional);
1587                                         }
1588                                         else if (t->options & CTX_GPENCIL_STROKES) {
1589                                                 t->flag |= initTransInfo_edit_pet_to_flag(ts->proportional);
1590                                         }
1591                                         else if (t->options & CTX_MASK) {
1592                                                 if (ts->proportional_mask) {
1593                                                         t->flag |= T_PROP_EDIT;
1594
1595                                                         if (ts->proportional == PROP_EDIT_CONNECTED) {
1596                                                                 t->flag |= T_PROP_CONNECTED;
1597                                                         }
1598                                                 }
1599                                         }
1600                                         else if ((t->obedit_type == -1) && ts->proportional_objects) {
1601                                                 t->flag |= T_PROP_EDIT;
1602                                         }
1603                                 }
1604                         }
1605                 }
1606
1607                 if (op && ((prop = RNA_struct_find_property(op->ptr, "proportional_size")) &&
1608                            RNA_property_is_set(op->ptr, prop)))
1609                 {
1610                         t->prop_size = RNA_property_float_get(op->ptr, prop);
1611                 }
1612                 else {
1613                         t->prop_size = ts->proportional_size;
1614                 }
1615
1616
1617                 /* TRANSFORM_FIX_ME rna restrictions */
1618                 if (t->prop_size <= 0.00001f) {
1619                         printf("Proportional size (%f) under 0.00001, resetting to 1!\n", t->prop_size);
1620                         t->prop_size = 1.0f;
1621                 }
1622
1623                 if (op && ((prop = RNA_struct_find_property(op->ptr, "proportional_edit_falloff")) &&
1624                            RNA_property_is_set(op->ptr, prop)))
1625                 {
1626                         t->prop_mode = RNA_property_enum_get(op->ptr, prop);
1627                 }
1628                 else {
1629                         t->prop_mode = ts->prop_mode;
1630                 }
1631         }
1632         else { /* add not pet option to context when not available */
1633                 t->options |= CTX_NO_PET;
1634         }
1635
1636         // Mirror is not supported with PET, turn it off.
1637 #if 0
1638         if (t->flag & T_PROP_EDIT) {
1639                 t->flag &= ~T_MIRROR;
1640         }
1641 #endif
1642
1643         setTransformViewAspect(t, t->aspect);
1644
1645         if (op && (prop = RNA_struct_find_property(op->ptr, "center_override")) && RNA_property_is_set(op->ptr, prop)) {
1646                 RNA_property_float_get_array(op->ptr, prop, t->center_global);
1647                 mul_v3_v3(t->center_global, t->aspect);
1648                 t->flag |= T_OVERRIDE_CENTER;
1649         }
1650
1651         setTransformViewMatrices(t);
1652         initNumInput(&t->num);
1653 }
1654
1655
1656 static void freeTransCustomData(
1657         TransInfo *t, TransDataContainer *tc,
1658         TransCustomData *custom_data)
1659 {
1660         if (custom_data->free_cb) {
1661                 /* Can take over freeing t->data and data_2d etc... */
1662                 custom_data->free_cb(t, tc, custom_data);
1663                 BLI_assert(custom_data->data == NULL);
1664         }
1665         else if ((custom_data->data != NULL) && custom_data->use_free) {
1666                 MEM_freeN(custom_data->data);
1667                 custom_data->data = NULL;
1668         }
1669         /* In case modes are switched in the same transform session. */
1670         custom_data->free_cb = false;
1671         custom_data->use_free = false;
1672 }
1673
1674 static void freeTransCustomDataContainer(TransInfo *t, TransDataContainer *tc, TransCustomDataContainer *tcdc)
1675 {
1676         TransCustomData *custom_data = &tcdc->first_elem;
1677         for (int i = 0; i < TRANS_CUSTOM_DATA_ELEM_MAX; i++, custom_data++) {
1678                 freeTransCustomData(t, tc, custom_data);
1679         }
1680 }
1681
1682 /**
1683  * Needed for mode switching.
1684  */
1685 void freeTransCustomDataForMode(TransInfo *t)
1686 {
1687         freeTransCustomData(t, NULL, &t->custom.mode);
1688         FOREACH_TRANS_DATA_CONTAINER (t, tc) {
1689                 freeTransCustomData(t, tc, &tc->custom.mode);
1690         }
1691 }
1692
1693 /* Here I would suggest only TransInfo related issues, like free data & reset vars. Not redraws */
1694 void postTrans(bContext *C, TransInfo *t)
1695 {
1696         if (t->draw_handle_view)
1697                 ED_region_draw_cb_exit(t->ar->type, t->draw_handle_view);
1698         if (t->draw_handle_apply)
1699                 ED_region_draw_cb_exit(t->ar->type, t->draw_handle_apply);
1700         if (t->draw_handle_pixel)
1701                 ED_region_draw_cb_exit(t->ar->type, t->draw_handle_pixel);
1702         if (t->draw_handle_cursor)
1703                 WM_paint_cursor_end(CTX_wm_manager(C), t->draw_handle_cursor);
1704
1705         if (t->flag & T_MODAL_CURSOR_SET) {
1706                 WM_cursor_modal_restore(CTX_wm_window(C));
1707         }
1708
1709         /* Free all custom-data */
1710         freeTransCustomDataContainer(t, NULL, &t->custom);
1711         FOREACH_TRANS_DATA_CONTAINER (t, tc) {
1712                 freeTransCustomDataContainer(t, tc, &tc->custom);
1713         }
1714
1715         /* postTrans can be called when nothing is selected, so data is NULL already */
1716         if (t->data_len_all != 0) {
1717                 FOREACH_TRANS_DATA_CONTAINER (t, tc) {
1718                         /* free data malloced per trans-data */
1719                         if (ELEM(t->obedit_type, OB_CURVE, OB_SURF) ||
1720                             (t->spacetype == SPACE_GRAPH))
1721                         {
1722                                 TransData *td = tc->data;
1723                                 for (int a = 0; a < tc->data_len; a++, td++) {
1724                                         if (td->flag & TD_BEZTRIPLE) {
1725                                                 MEM_freeN(td->hdata);
1726                                         }
1727                                 }
1728                         }
1729                         MEM_freeN(tc->data);
1730
1731                         MEM_SAFE_FREE(tc->data_ext);
1732                         MEM_SAFE_FREE(tc->data_2d);
1733                 }
1734         }
1735
1736         MEM_SAFE_FREE(t->data_container);
1737         t->data_container = NULL;
1738
1739         BLI_freelistN(&t->tsnap.points);
1740
1741         if (t->spacetype == SPACE_IMAGE) {
1742                 if (t->options & (CTX_MASK | CTX_PAINT_CURVE)) {
1743                         /* pass */
1744                 }
1745                 else {
1746                         SpaceImage *sima = t->sa->spacedata.first;
1747                         if (sima->flag & SI_LIVE_UNWRAP)
1748                                 ED_uvedit_live_unwrap_end(t->state == TRANS_CANCEL);
1749                 }
1750         }
1751         else if (t->spacetype == SPACE_VIEW3D) {
1752                 View3D *v3d = t->sa->spacedata.first;
1753                 /* restore gizmo */
1754                 if (t->flag & T_MODAL) {
1755                         v3d->gizmo_flag = t->gizmo_flag;
1756                 }
1757         }
1758
1759         if (t->mouse.data) {
1760                 MEM_freeN(t->mouse.data);
1761         }
1762
1763         if (t->rng != NULL) {
1764                 BLI_rng_free(t->rng);
1765         }
1766
1767         freeSnapping(t);
1768 }
1769
1770 void applyTransObjects(TransInfo *t)
1771 {
1772         TransDataContainer *tc = TRANS_DATA_CONTAINER_FIRST_SINGLE(t);
1773
1774         TransData *td;
1775
1776         for (td = tc->data; td < tc->data + tc->data_len; td++) {
1777                 copy_v3_v3(td->iloc, td->loc);
1778                 if (td->ext->rot) {
1779                         copy_v3_v3(td->ext->irot, td->ext->rot);
1780                 }
1781                 if (td->ext->size) {
1782                         copy_v3_v3(td->ext->isize, td->ext->size);
1783                 }
1784         }
1785         recalcData(t);
1786 }
1787
1788 static void restoreElement(TransData *td)
1789 {
1790         /* TransData for crease has no loc */
1791         if (td->loc) {
1792                 copy_v3_v3(td->loc, td->iloc);
1793         }
1794         if (td->val) {
1795                 *td->val = td->ival;
1796         }
1797
1798         if (td->ext && (td->flag & TD_NO_EXT) == 0) {
1799                 if (td->ext->rot) {
1800                         copy_v3_v3(td->ext->rot, td->ext->irot);
1801                 }
1802                 if (td->ext->rotAngle) {
1803                         *td->ext->rotAngle = td->ext->irotAngle;
1804                 }
1805                 if (td->ext->rotAxis) {
1806                         copy_v3_v3(td->ext->rotAxis, td->ext->irotAxis);
1807                 }
1808                 /* XXX, drotAngle & drotAxis not used yet */
1809                 if (td->ext->size) {
1810                         copy_v3_v3(td->ext->size, td->ext->isize);
1811                 }
1812                 if (td->ext->quat) {
1813                         copy_qt_qt(td->ext->quat, td->ext->iquat);
1814                 }
1815         }
1816
1817         if (td->flag & TD_BEZTRIPLE) {
1818                 *(td->hdata->h1) = td->hdata->ih1;
1819                 *(td->hdata->h2) = td->hdata->ih2;
1820         }
1821 }
1822
1823 void restoreTransObjects(TransInfo *t)
1824 {
1825         FOREACH_TRANS_DATA_CONTAINER (t, tc) {
1826
1827                 TransData *td;
1828                 TransData2D *td2d;
1829
1830                 for (td = tc->data; td < tc->data + tc->data_len; td++) {
1831                         restoreElement(td);
1832                 }
1833
1834                 for (td2d = tc->data_2d; tc->data_2d && td2d < tc->data_2d + tc->data_len; td2d++) {
1835                         if (td2d->h1) {
1836                                 td2d->h1[0] = td2d->ih1[0];
1837                                 td2d->h1[1] = td2d->ih1[1];
1838                         }
1839                         if (td2d->h2) {
1840                                 td2d->h2[0] = td2d->ih2[0];
1841                                 td2d->h2[1] = td2d->ih2[1];
1842                         }
1843                 }
1844
1845                 unit_m3(t->mat);
1846
1847         }
1848
1849         recalcData(t);
1850 }
1851
1852 void calculateCenter2D(TransInfo *t)
1853 {
1854         BLI_assert(!is_zero_v3(t->aspect));
1855         projectFloatView(t, t->center_global, t->center2d);
1856 }
1857
1858 void calculateCenterLocal(
1859         TransInfo *t, const float center_global[3])
1860 {
1861         /* setting constraint center */
1862         /* note, init functions may over-ride t->center */
1863         FOREACH_TRANS_DATA_CONTAINER (t, tc) {
1864                 if (tc->use_local_mat) {
1865                         mul_v3_m4v3(tc->center_local, tc->imat, center_global);
1866                 }
1867                 else {
1868                         copy_v3_v3(tc->center_local, center_global);
1869                 }
1870         }
1871 }
1872
1873 void calculateCenterCursor(TransInfo *t, float r_center[3])
1874 {
1875         const float *cursor = t->scene->cursor.location;
1876         copy_v3_v3(r_center, cursor);
1877
1878         /* If edit or pose mode, move cursor in local space */
1879         if (t->options & CTX_PAINT_CURVE) {
1880                 if (ED_view3d_project_float_global(t->ar, cursor, r_center, V3D_PROJ_TEST_NOP) != V3D_PROJ_RET_OK) {
1881                         r_center[0] = t->ar->winx / 2.0f;
1882                         r_center[1] = t->ar->winy / 2.0f;
1883                 }
1884                 r_center[2] = 0.0f;
1885         }
1886 }
1887
1888 void calculateCenterCursor2D(TransInfo *t, float r_center[2])
1889 {
1890         const float *cursor = NULL;
1891
1892         if (t->spacetype == SPACE_IMAGE) {
1893                 SpaceImage *sima = (SpaceImage *)t->sa->spacedata.first;
1894                 cursor = sima->cursor;
1895         }
1896         else if (t->spacetype == SPACE_CLIP) {
1897                 SpaceClip *space_clip = (SpaceClip *) t->sa->spacedata.first;
1898                 cursor = space_clip->cursor;
1899         }
1900
1901         if (cursor) {
1902                 if (t->options & CTX_MASK) {
1903                         float co[2];
1904
1905                         if (t->spacetype == SPACE_IMAGE) {
1906                                 SpaceImage *sima = (SpaceImage *)t->sa->spacedata.first;
1907                                 BKE_mask_coord_from_image(sima->image, &sima->iuser, co, cursor);
1908                         }
1909                         else if (t->spacetype == SPACE_CLIP) {
1910                                 SpaceClip *space_clip = (SpaceClip *) t->sa->spacedata.first;
1911                                 BKE_mask_coord_from_movieclip(space_clip->clip, &space_clip->user, co, cursor);
1912                         }
1913                         else {
1914                                 BLI_assert(!"Shall not happen");
1915                         }
1916
1917                         r_center[0] = co[0] * t->aspect[0];
1918                         r_center[1] = co[1] * t->aspect[1];
1919                 }
1920                 else if (t->options & CTX_PAINT_CURVE) {
1921                         if (t->spacetype == SPACE_IMAGE) {
1922                                 r_center[0] = UI_view2d_view_to_region_x(&t->ar->v2d, cursor[0]);
1923                                 r_center[1] = UI_view2d_view_to_region_y(&t->ar->v2d, cursor[1]);
1924                         }
1925                 }
1926                 else {
1927                         r_center[0] = cursor[0] * t->aspect[0];
1928                         r_center[1] = cursor[1] * t->aspect[1];
1929                 }
1930         }
1931 }
1932
1933 void calculateCenterCursorGraph2D(TransInfo *t, float r_center[2])
1934 {
1935         SpaceGraph *sipo = (SpaceGraph *)t->sa->spacedata.first;
1936         Scene *scene = t->scene;
1937
1938         /* cursor is combination of current frame, and graph-editor cursor value */
1939         if (sipo->mode == SIPO_MODE_DRIVERS) {
1940                 r_center[0] = sipo->cursorTime;
1941                 r_center[1] = sipo->cursorVal;
1942         }
1943         else {
1944                 r_center[0] = (float)(scene->r.cfra);
1945                 r_center[1] = sipo->cursorVal;
1946         }
1947 }
1948
1949 void calculateCenterMedian(TransInfo *t, float r_center[3])
1950 {
1951         float partial[3] = {0.0f, 0.0f, 0.0f};
1952         int total = 0;
1953
1954         FOREACH_TRANS_DATA_CONTAINER (t, tc) {
1955                 for (int i = 0; i < tc->data_len; i++) {
1956                         if (tc->data[i].flag & TD_SELECTED) {
1957                                 if (!(tc->data[i].flag & TD_NOCENTER)) {
1958                                         if (tc->use_local_mat) {
1959                                                 float v[3];
1960                                                 mul_v3_m4v3(v, tc->mat, tc->data[i].center);
1961                                                 add_v3_v3(partial, v);
1962                                         }
1963                                         else {
1964                                                 add_v3_v3(partial, tc->data[i].center);
1965                                         }
1966                                         total++;
1967                                 }
1968                         }
1969                 }
1970         }
1971         if (total) {
1972                 mul_v3_fl(partial, 1.0f / (float)total);
1973         }
1974         copy_v3_v3(r_center, partial);
1975 }
1976
1977 void calculateCenterBound(TransInfo *t, float r_center[3])
1978 {
1979         float max[3], min[3];
1980         bool changed = false;
1981         INIT_MINMAX(min, max);
1982         FOREACH_TRANS_DATA_CONTAINER (t, tc) {
1983                 for (int i = 0; i < tc->data_len; i++) {
1984                         if (tc->data[i].flag & TD_SELECTED) {
1985                                 if (!(tc->data[i].flag & TD_NOCENTER)) {
1986                                         if (tc->use_local_mat) {
1987                                                 float v[3];
1988                                                 mul_v3_m4v3(v, tc->mat, tc->data[i].center);
1989                                                 minmax_v3v3_v3(min, max, v);
1990                                         }
1991                                         else {
1992                                                 minmax_v3v3_v3(min, max, tc->data[i].center);
1993                                         }
1994                                         changed = true;
1995                                 }
1996                         }
1997                 }
1998         }
1999         if (changed) {
2000                 mid_v3_v3v3(r_center, min, max);
2001         }
2002 }
2003
2004 /**
2005  * \param select_only: only get active center from data being transformed.
2006  */
2007 bool calculateCenterActive(TransInfo *t, bool select_only, float r_center[3])
2008 {
2009         TransDataContainer *tc = TRANS_DATA_CONTAINER_FIRST_OK(t);
2010
2011         if (t->spacetype != SPACE_VIEW3D) {
2012                 return false;
2013         }
2014         else if (tc->obedit) {
2015                 if (ED_object_calc_active_center_for_editmode(tc->obedit, select_only, r_center)) {
2016                         mul_m4_v3(tc->obedit->obmat, r_center);
2017                         return true;
2018                 }
2019         }
2020         else if (t->flag & T_POSE) {
2021                 ViewLayer *view_layer = t->view_layer;
2022                 Object *ob = OBACT(view_layer) ;
2023                 if (ED_object_calc_active_center_for_posemode(ob, select_only, r_center)) {
2024                         mul_m4_v3(ob->obmat, r_center);
2025                         return true;
2026                 }
2027         }
2028         else if (t->options & CTX_PAINT_CURVE) {
2029                 Paint *p = BKE_paint_get_active(t->scene, t->view_layer);
2030                 Brush *br = p->brush;
2031                 PaintCurve *pc = br->paint_curve;
2032                 copy_v3_v3(r_center, pc->points[pc->add_index - 1].bez.vec[1]);
2033                 r_center[2] = 0.0f;
2034                 return true;
2035         }
2036         else {
2037                 /* object mode */
2038                 ViewLayer *view_layer = t->view_layer;
2039                 Object *ob = OBACT(view_layer);
2040                 Base *base = BASACT(view_layer);
2041                 if (ob && ((!select_only) || ((base->flag & BASE_SELECTED) != 0))) {
2042                         copy_v3_v3(r_center, ob->obmat[3]);
2043                         return true;
2044                 }
2045         }
2046
2047         return false;
2048 }
2049
2050 static void calculateCenter_FromAround(TransInfo *t, int around, float r_center[3])
2051 {
2052         switch (around) {
2053                 case V3D_AROUND_CENTER_BOUNDS:
2054                         calculateCenterBound(t, r_center);
2055                         break;
2056                 case V3D_AROUND_CENTER_MEDIAN:
2057                         calculateCenterMedian(t, r_center);
2058                         break;
2059                 case V3D_AROUND_CURSOR:
2060                         if (ELEM(t->spacetype, SPACE_IMAGE, SPACE_CLIP))
2061                                 calculateCenterCursor2D(t, r_center);
2062                         else if (t->spacetype == SPACE_GRAPH)
2063                                 calculateCenterCursorGraph2D(t, r_center);
2064                         else
2065                                 calculateCenterCursor(t, r_center);
2066                         break;
2067                 case V3D_AROUND_LOCAL_ORIGINS:
2068                         /* Individual element center uses median center for helpline and such */
2069                         calculateCenterMedian(t, r_center);
2070                         break;
2071                 case V3D_AROUND_ACTIVE:
2072                 {
2073                         if (calculateCenterActive(t, false, r_center)) {
2074                                 /* pass */
2075                         }
2076                         else {
2077                                 /* fallback */
2078                                 calculateCenterMedian(t, r_center);
2079                         }
2080                         break;
2081                 }
2082         }
2083 }
2084
2085 void calculateCenter(TransInfo *t)
2086 {
2087         if ((t->flag & T_OVERRIDE_CENTER) == 0) {
2088                 calculateCenter_FromAround(t, t->around, t->center_global);
2089         }
2090         calculateCenterLocal(t, t->center_global);
2091
2092         /* avoid calculating again */
2093         {
2094                 TransCenterData *cd = &t->center_cache[t->around];
2095                 copy_v3_v3(cd->global, t->center_global);
2096                 cd->is_set = true;
2097         }
2098
2099         calculateCenter2D(t);
2100
2101         /* for panning from cameraview */
2102         if ((t->flag & T_OBJECT) && (t->flag & T_OVERRIDE_CENTER) == 0) {
2103                 if (t->spacetype == SPACE_VIEW3D && t->ar && t->ar->regiontype == RGN_TYPE_WINDOW) {
2104
2105                         if (t->flag & T_CAMERA) {
2106                                 float axis[3];
2107                                 /* persinv is nasty, use viewinv instead, always right */
2108                                 copy_v3_v3(axis, t->viewinv[2]);
2109                                 normalize_v3(axis);
2110
2111                                 /* 6.0 = 6 grid units */
2112                                 axis[0] = t->center_global[0] - 6.0f * axis[0];
2113                                 axis[1] = t->center_global[1] - 6.0f * axis[1];
2114                                 axis[2] = t->center_global[2] - 6.0f * axis[2];
2115
2116                                 projectFloatView(t, axis, t->center2d);
2117
2118                                 /* rotate only needs correct 2d center, grab needs ED_view3d_calc_zfac() value */
2119                                 if (t->mode == TFM_TRANSLATION) {
2120                                         copy_v3_v3(t->center_global, axis);
2121                                 }
2122                         }
2123                 }
2124         }
2125
2126         if (t->spacetype == SPACE_VIEW3D) {
2127                 /* ED_view3d_calc_zfac() defines a factor for perspective depth correction, used in ED_view3d_win_to_delta() */
2128
2129                 /* zfac is only used convertViewVec only in cases operator was invoked in RGN_TYPE_WINDOW
2130                  * and never used in other cases.
2131                  *
2132                  * We need special case here as well, since ED_view3d_calc_zfac will crash when called
2133                  * for a region different from RGN_TYPE_WINDOW.
2134                  */
2135                 if (t->ar->regiontype == RGN_TYPE_WINDOW) {
2136                         t->zfac = ED_view3d_calc_zfac(t->ar->regiondata, t->center_global, NULL);
2137                 }
2138                 else {
2139                         t->zfac = 0.0f;
2140                 }
2141         }
2142 }
2143
2144 BLI_STATIC_ASSERT(ARRAY_SIZE(((TransInfo *)NULL)->center_cache) == (V3D_AROUND_ACTIVE + 1), "test size");
2145
2146 /**
2147  * Lazy initialize transform center data, when we need to access center values from other types.
2148  */
2149 const TransCenterData *transformCenter_from_type(TransInfo *t, int around)
2150 {
2151         BLI_assert(around <= V3D_AROUND_ACTIVE);
2152         TransCenterData *cd = &t->center_cache[around];
2153         if (cd->is_set == false) {
2154                 calculateCenter_FromAround(t, around, cd->global);
2155                 cd->is_set = true;
2156         }
2157         return cd;
2158 }
2159
2160 void calculatePropRatio(TransInfo *t)
2161 {
2162         int i;
2163         float dist;
2164         const bool connected = (t->flag & T_PROP_CONNECTED) != 0;
2165
2166         t->proptext[0] = '\0';
2167
2168         if (t->flag & T_PROP_EDIT) {
2169                 const char *pet_id = NULL;
2170                 FOREACH_TRANS_DATA_CONTAINER (t, tc) {
2171                         TransData *td = tc->data;
2172                         for (i = 0; i < tc->data_len; i++, td++) {
2173                                 if (td->flag & TD_SELECTED) {
2174                                         td->factor = 1.0f;
2175                                 }
2176                                 else if (tc->mirror.axis_flag && (td->loc[0] * tc->mirror.sign) < -0.00001f) {
2177                                         td->flag |= TD_SKIP;
2178                                         td->factor = 0.0f;
2179                                         restoreElement(td);
2180                                 }
2181                                 else if ((connected && (td->flag & TD_NOTCONNECTED || td->dist > t->prop_size)) ||
2182                                          (connected == 0 && td->rdist > t->prop_size))
2183                                 {
2184                                         /*
2185                                          * The elements are sorted according to their dist member in the array,
2186                                          * that means we can stop when it finds one element outside of the propsize.
2187                                          * do not set 'td->flag |= TD_NOACTION', the prop circle is being changed.
2188                                          */
2189
2190                                         td->factor = 0.0f;
2191                                         restoreElement(td);
2192                                 }
2193                                 else {
2194                                         /* Use rdist for falloff calculations, it is the real distance */
2195                                         td->flag &= ~TD_NOACTION;
2196
2197                                         if (connected)
2198                                                 dist = (t->prop_size - td->dist) / t->prop_size;
2199                                         else
2200                                                 dist = (t->prop_size - td->rdist) / t->prop_size;
2201
2202                                         /*
2203                                          * Clamp to positive numbers.
2204                                          * Certain corner cases with connectivity and individual centers
2205                                          * can give values of rdist larger than propsize.
2206                                          */
2207                                         if (dist < 0.0f)
2208                                                 dist = 0.0f;
2209
2210                                         switch (t->prop_mode) {
2211                                                 case PROP_SHARP:
2212                                                         td->factor = dist * dist;
2213                                                         break;
2214                                                 case PROP_SMOOTH:
2215                                                         td->factor = 3.0f * dist * dist - 2.0f * dist * dist * dist;
2216                                                         break;
2217                                                 case PROP_ROOT:
2218                                                         td->factor = sqrtf(dist);
2219                                                         break;
2220                                                 case PROP_LIN:
2221                                                         td->factor = dist;
2222                                                         break;
2223                                                 case PROP_CONST:
2224                                                         td->factor = 1.0f;
2225                                                         break;
2226                                                 case PROP_SPHERE:
2227                                                         td->factor = sqrtf(2 * dist - dist * dist);
2228                                                         break;
2229                                                 case PROP_RANDOM:
2230                                                         if (t->rng == NULL) {
2231                                                                 /* Lazy initialization. */
2232                                                                 uint rng_seed = (uint)(PIL_check_seconds_timer_i() & UINT_MAX);
2233                                                                 t->rng = BLI_rng_new(rng_seed);
2234                                                         }
2235                                                         td->factor = BLI_rng_get_float(t->rng) * dist;
2236                                                         break;
2237                                                 case PROP_INVSQUARE:
2238                                                         td->factor = dist * (2.0f - dist);
2239                                                         break;
2240                                                 default:
2241                                                         td->factor = 1;
2242                                                         break;
2243                                         }
2244                                 }
2245                         }
2246                 }
2247
2248                 switch (t->prop_mode) {
2249                         case PROP_SHARP:
2250                                 pet_id = N_("(Sharp)");
2251                                 break;
2252                         case PROP_SMOOTH:
2253                                 pet_id = N_("(Smooth)");
2254                                 break;
2255                         case PROP_ROOT:
2256                                 pet_id = N_("(Root)");
2257                                 break;
2258                         case PROP_LIN:
2259                                 pet_id = N_("(Linear)");
2260                                 break;
2261                         case PROP_CONST:
2262                                 pet_id = N_("(Constant)");
2263                                 break;
2264                         case PROP_SPHERE:
2265                                 pet_id = N_("(Sphere)");
2266                                 break;
2267                         case PROP_RANDOM:
2268                                 pet_id = N_("(Random)");
2269                                 break;
2270                         case PROP_INVSQUARE:
2271                                 pet_id = N_("(InvSquare)");
2272                                 break;
2273                         default:
2274                                 break;
2275                 }
2276
2277                 if (pet_id) {
2278                         BLI_strncpy(t->proptext, IFACE_(pet_id), sizeof(t->proptext));
2279                 }
2280         }
2281         else {
2282                 FOREACH_TRANS_DATA_CONTAINER (t, tc) {
2283                         TransData *td = tc->data;
2284                         for (i = 0; i < tc->data_len; i++, td++) {
2285                                 td->factor = 1.0;
2286                         }
2287                 }
2288         }
2289 }
2290
2291 /**
2292  * Rotate an element, low level code, ignore protected channels.
2293  * (use for objects or pose-bones)
2294  * Similar to #ElementRotation.
2295  */
2296 void transform_data_ext_rotate(TransData *td, float mat[3][3], bool use_drot)
2297 {
2298         float totmat[3][3];
2299         float smat[3][3];
2300         float fmat[3][3];
2301         float obmat[3][3];
2302
2303         float dmat[3][3];  /* delta rotation */
2304         float dmat_inv[3][3];
2305
2306         mul_m3_m3m3(totmat, mat, td->mtx);
2307         mul_m3_m3m3(smat, td->smtx, mat);
2308
2309         /* logic from BKE_object_rot_to_mat3 */
2310         if (use_drot) {
2311                 if (td->ext->rotOrder > 0) {
2312                         eulO_to_mat3(dmat, td->ext->drot, td->ext->rotOrder);
2313                 }
2314                 else if (td->ext->rotOrder == ROT_MODE_AXISANGLE) {
2315 #if 0
2316                         axis_angle_to_mat3(dmat, td->ext->drotAxis, td->ext->drotAngle);
2317 #else
2318                         unit_m3(dmat);
2319 #endif
2320                 }
2321                 else {
2322                         float tquat[4];
2323                         normalize_qt_qt(tquat, td->ext->dquat);
2324                         quat_to_mat3(dmat, tquat);
2325                 }
2326
2327                 invert_m3_m3(dmat_inv, dmat);
2328         }
2329
2330
2331         if (td->ext->rotOrder == ROT_MODE_QUAT) {
2332                 float quat[4];
2333
2334                 /* calculate the total rotatation */
2335                 quat_to_mat3(obmat, td->ext->iquat);
2336                 if (use_drot) {
2337                         mul_m3_m3m3(obmat, dmat, obmat);
2338                 }
2339
2340                 /* mat = transform, obmat = object rotation */
2341                 mul_m3_m3m3(fmat, smat, obmat);
2342
2343                 if (use_drot) {
2344                         mul_m3_m3m3(fmat, dmat_inv, fmat);
2345                 }
2346
2347                 mat3_to_quat(quat, fmat);
2348
2349                 /* apply */
2350                 copy_qt_qt(td->ext->quat, quat);
2351         }
2352         else if (td->ext->rotOrder == ROT_MODE_AXISANGLE) {
2353                 float axis[3], angle;
2354
2355                 /* calculate the total rotatation */
2356                 axis_angle_to_mat3(obmat, td->ext->irotAxis, td->ext->irotAngle);
2357                 if (use_drot) {
2358                         mul_m3_m3m3(obmat, dmat, obmat);
2359                 }
2360
2361                 /* mat = transform, obmat = object rotation */
2362                 mul_m3_m3m3(fmat, smat, obmat);
2363
2364                 if (use_drot) {
2365                         mul_m3_m3m3(fmat, dmat_inv, fmat);
2366                 }
2367
2368                 mat3_to_axis_angle(axis, &angle, fmat);
2369
2370                 /* apply */
2371                 copy_v3_v3(td->ext->rotAxis, axis);
2372                 *td->ext->rotAngle = angle;
2373         }
2374         else {
2375                 float eul[3];
2376
2377                 /* calculate the total rotatation */
2378                 eulO_to_mat3(obmat, td->ext->irot, td->ext->rotOrder);
2379                 if (use_drot) {
2380                         mul_m3_m3m3(obmat, dmat, obmat);
2381                 }
2382
2383                 /* mat = transform, obmat = object rotation */
2384                 mul_m3_m3m3(fmat, smat, obmat);
2385
2386                 if (use_drot) {
2387                         mul_m3_m3m3(fmat, dmat_inv, fmat);
2388                 }
2389
2390                 mat3_to_compatible_eulO(eul, td->ext->rot, td->ext->rotOrder, fmat);
2391
2392                 /* apply */
2393                 copy_v3_v3(td->ext->rot, eul);
2394         }
2395 }