Merging r46725 through r46963 from trunk into soc-2011-tomato
[blender.git] / source / blender / editors / transform / transform_generics.c
1 /*
2  * ***** BEGIN GPL LICENSE BLOCK *****
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  *
18  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
19  * All rights reserved.
20  *
21  * The Original Code is: all of this file.
22  *
23  * Contributor(s): none yet.
24  *
25  * ***** END GPL LICENSE BLOCK *****
26  */
27
28 /** \file blender/editors/transform/transform_generics.c
29  *  \ingroup edtransform
30  */
31
32
33 #include <string.h>
34 #include <math.h>
35
36 #include "MEM_guardedalloc.h"
37
38 #include "BLO_sys_types.h" // for intptr_t support
39
40 #include "DNA_anim_types.h"
41 #include "DNA_armature_types.h"
42 #include "DNA_lattice_types.h"
43 #include "DNA_screen_types.h"
44 #include "DNA_space_types.h"
45 #include "DNA_scene_types.h"
46 #include "DNA_object_types.h"
47 #include "DNA_mesh_types.h"
48 #include "DNA_meshdata_types.h"
49 #include "DNA_view3d_types.h"
50 #include "DNA_modifier_types.h"
51 #include "DNA_movieclip_types.h"
52 #include "DNA_mask_types.h"
53
54 #include "BLI_math.h"
55 #include "BLI_blenlib.h"
56 #include "BLI_rand.h"
57 #include "BLI_utildefines.h"
58
59 #include "RNA_access.h"
60
61 //#include "BIF_screen.h"
62 //#include "BIF_mywindow.h"
63 #include "BIF_gl.h"
64 #include "BIF_glutil.h"
65 //#include "BIF_editmesh.h"
66 //#include "BIF_editsima.h"
67 //#include "BIF_editparticle.h"
68 //#include "BIF_meshtools.h"
69
70 #include "BKE_animsys.h"
71 #include "BKE_action.h"
72 #include "BKE_armature.h"
73 #include "BKE_curve.h"
74 #include "BKE_depsgraph.h"
75 #include "BKE_displist.h"
76 #include "BKE_fcurve.h"
77 #include "BKE_lattice.h"
78 #include "BKE_mesh.h"
79 #include "BKE_nla.h"
80 #include "BKE_context.h"
81 #include "BKE_tessmesh.h"
82 #include "BKE_tracking.h"
83
84 #include "ED_anim_api.h"
85 #include "ED_armature.h"
86 #include "ED_image.h"
87 #include "ED_keyframing.h"
88 #include "ED_markers.h"
89 #include "ED_mesh.h"
90 #include "ED_particle.h"
91 #include "ED_screen_types.h"
92 #include "ED_space_api.h"
93 #include "ED_uvedit.h"
94 #include "ED_view3d.h"
95 #include "ED_curve.h" /* for curve_editnurbs */
96 #include "ED_clip.h"
97
98 //#include "BDR_unwrapper.h"
99
100 #include "WM_types.h"
101 #include "WM_api.h"
102
103 #include "UI_resources.h"
104
105 //#include "blendef.h"
106 //
107 //#include "mydevice.h"
108
109 #include "transform.h"
110
111 /* ************************** Functions *************************** */
112
113 void getViewVector(TransInfo *t, float coord[3], float vec[3])
114 {
115         if (t->persp != RV3D_ORTHO) {
116                 float p1[4], p2[4];
117                 
118                 copy_v3_v3(p1, coord);
119                 p1[3] = 1.0f;
120                 copy_v3_v3(p2, p1);
121                 p2[3] = 1.0f;
122                 mul_m4_v4(t->viewmat, p2);
123                 
124                 p2[0] = 2.0f * p2[0];
125                 p2[1] = 2.0f * p2[1];
126                 p2[2] = 2.0f * p2[2];
127                 
128                 mul_m4_v4(t->viewinv, p2);
129                 
130                 sub_v3_v3v3(vec, p1, p2);
131         }
132         else {
133                 copy_v3_v3(vec, t->viewinv[2]);
134         }
135         normalize_v3(vec);
136 }
137
138 /* ************************** GENERICS **************************** */
139
140 static void clipMirrorModifier(TransInfo *t, Object *ob)
141 {
142         ModifierData *md= ob->modifiers.first;
143         float tolerance[3] = {0.0f, 0.0f, 0.0f};
144         int axis = 0;
145         
146         for (; md; md=md->next) {
147                 if ((md->type==eModifierType_Mirror) && (md->mode & eModifierMode_Realtime)) {
148                         MirrorModifierData *mmd = (MirrorModifierData*) md;
149                         
150                         if (mmd->flag & MOD_MIR_CLIPPING) {
151                                 axis = 0;
152                                 if (mmd->flag & MOD_MIR_AXIS_X) {
153                                         axis |= 1;
154                                         tolerance[0] = mmd->tolerance;
155                                 }
156                                 if (mmd->flag & MOD_MIR_AXIS_Y) {
157                                         axis |= 2;
158                                         tolerance[1] = mmd->tolerance;
159                                 }
160                                 if (mmd->flag & MOD_MIR_AXIS_Z) {
161                                         axis |= 4;
162                                         tolerance[2] = mmd->tolerance;
163                                 }
164                                 if (axis) {
165                                         float mtx[4][4], imtx[4][4];
166                                         int i;
167                                         TransData *td = t->data;
168                                         
169                                         if (mmd->mirror_ob) {
170                                                 float obinv[4][4];
171                                                 
172                                                 invert_m4_m4(obinv, mmd->mirror_ob->obmat);
173                                                 mult_m4_m4m4(mtx, obinv, ob->obmat);
174                                                 invert_m4_m4(imtx, mtx);
175                                         }
176                                         
177                                         for (i = 0 ; i < t->total; i++, td++) {
178                                                 int clip;
179                                                 float loc[3], iloc[3];
180                                                 
181                                                 if (td->flag & TD_NOACTION)
182                                                         break;
183                                                 if (td->loc==NULL)
184                                                         break;
185                                                 
186                                                 if (td->flag & TD_SKIP)
187                                                         continue;
188                                                 
189                                                 copy_v3_v3(loc,  td->loc);
190                                                 copy_v3_v3(iloc, td->iloc);
191                                                 
192                                                 if (mmd->mirror_ob) {
193                                                         mul_m4_v3(mtx, loc);
194                                                         mul_m4_v3(mtx, iloc);
195                                                 }
196                                                 
197                                                 clip = 0;
198                                                 if (axis & 1) {
199                                                         if (fabsf(iloc[0])<=tolerance[0] ||
200                                                            loc[0]*iloc[0]<0.0f)
201                                                         {
202                                                                 loc[0]= 0.0f;
203                                                                 clip = 1;
204                                                         }
205                                                 }
206                                                 
207                                                 if (axis & 2) {
208                                                         if (fabsf(iloc[1]) <= tolerance[1] ||
209                                                            loc[1] * iloc[1]<0.0f)
210                                                         {
211                                                                 loc[1]= 0.0f;
212                                                                 clip = 1;
213                                                         }
214                                                 }
215                                                 if (axis & 4) {
216                                                         if (fabsf(iloc[2]) <= tolerance[2] ||
217                                                            loc[2] * iloc[2] < 0.0f)
218                                                         {
219                                                                 loc[2]= 0.0f;
220                                                                 clip = 1;
221                                                         }
222                                                 }
223                                                 if (clip) {
224                                                         if (mmd->mirror_ob) {
225                                                                 mul_m4_v3(imtx, loc);
226                                                         }
227                                                         copy_v3_v3(td->loc, loc);
228                                                 }
229                                         }
230                                 }
231                                 
232                         }
233                 }
234         }
235 }
236
237 /* assumes obedit set to mesh object */
238 static void editbmesh_apply_to_mirror(TransInfo *t)
239 {
240         TransData *td = t->data;
241         BMVert *eve;
242         int i;
243         
244         for (i = 0 ; i < t->total; i++, td++) {
245                 if (td->flag & TD_NOACTION)
246                         break;
247                 if (td->loc==NULL)
248                         break;
249                 if (td->flag & TD_SKIP)
250                         continue;
251                 
252                 eve = td->extra;
253                 if (eve) {
254                         eve->co[0]= -td->loc[0];
255                         eve->co[1]= td->loc[1];
256                         eve->co[2]= td->loc[2];
257                 }
258                 
259                 if (td->flag & TD_MIRROR_EDGE) {
260                         td->loc[0] = 0;
261                 }
262         }
263 }
264
265 /* for the realtime animation recording feature, handle overlapping data */
266 static void animrecord_check_state (Scene *scene, ID *id, wmTimer *animtimer)
267 {
268         ScreenAnimData *sad= (animtimer) ? animtimer->customdata : NULL;
269         
270         /* sanity checks */
271         if (ELEM3(NULL, scene, id, sad))
272                 return;
273         
274         /* check if we need a new strip if:
275          *      - if animtimer is running 
276          *      - we're not only keying for available channels
277          *      - the option to add new actions for each round is not enabled
278          */
279         if (IS_AUTOKEY_FLAG(scene, INSERTAVAIL)==0 && (scene->toolsettings->autokey_flag & ANIMRECORD_FLAG_WITHNLA)) {
280                 /* if playback has just looped around, we need to add a new NLA track+strip to allow a clean pass to occur */
281                 if ((sad) && (sad->flag & ANIMPLAY_FLAG_JUMPED)) {
282                         AnimData *adt= BKE_animdata_from_id(id);
283                         
284                         /* perform push-down manually with some differences 
285                          * NOTE: BKE_nla_action_pushdown() sync warning...
286                          */
287                         if ((adt->action) && !(adt->flag & ADT_NLA_EDIT_ON)) {
288                                 float astart, aend;
289                                 
290                                 /* only push down if action is more than 1-2 frames long */
291                                 calc_action_range(adt->action, &astart, &aend, 1);
292                                 if (aend > astart+2.0f) {
293                                         NlaStrip *strip= add_nlastrip_to_stack(adt, adt->action);
294                                         
295                                         /* clear reference to action now that we've pushed it onto the stack */
296                                         adt->action->id.us--;
297                                         adt->action= NULL;
298                                         
299                                         /* adjust blending + extend so that they will behave correctly */
300                                         strip->extendmode= NLASTRIP_EXTEND_NOTHING;
301                                         strip->flag &= ~(NLASTRIP_FLAG_AUTO_BLENDS|NLASTRIP_FLAG_SELECT|NLASTRIP_FLAG_ACTIVE);
302                                         
303                                         /* also, adjust the AnimData's action extend mode to be on 
304                                          * 'nothing' so that previous result still play 
305                                          */
306                                         adt->act_extendmode= NLASTRIP_EXTEND_NOTHING;
307                                 }
308                         }
309                 }
310         }
311 }
312
313 static int fcu_test_selected(FCurve *fcu)
314 {
315         BezTriple *bezt= fcu->bezt;
316         unsigned int i;
317
318         if (bezt==NULL) /* ignore baked */
319                 return 0;
320
321         for (i=0; i < fcu->totvert; i++, bezt++) {
322                 if (BEZSELECTED(bezt)) return 1;
323         }
324
325         return 0;
326 }
327
328 /* helper for recalcData() - for Action Editor transforms */
329 static void recalcData_actedit(TransInfo *t)
330 {
331         Scene *scene= t->scene;
332         SpaceAction *saction= (SpaceAction *)t->sa->spacedata.first;
333         
334         bAnimContext ac= {NULL};
335         ListBase anim_data = {NULL, NULL};
336         bAnimListElem *ale;
337         int filter;
338         
339         /* initialize relevant anim-context 'context' data from TransInfo data */
340                 /* NOTE: sync this with the code in ANIM_animdata_get_context() */
341         ac.scene= t->scene;
342         ac.obact= OBACT;
343         ac.sa= t->sa;
344         ac.ar= t->ar;
345         ac.sl= (t->sa)? t->sa->spacedata.first : NULL;
346         ac.spacetype= (t->sa)? t->sa->spacetype : 0;
347         ac.regiontype= (t->ar)? t->ar->regiontype : 0;
348         
349         ANIM_animdata_context_getdata(&ac);
350         
351         /* perform flush */
352         if (ac.datatype == ANIMCONT_GPENCIL) {
353                 /* flush transform values back to actual coordinates */
354                 flushTransGPactionData(t);
355         }
356         else {
357                 /* get animdata blocks visible in editor, assuming that these will be the ones where things changed */
358                 filter= (ANIMFILTER_DATA_VISIBLE | ANIMFILTER_ANIMDATA);
359                 ANIM_animdata_filter(&ac, &anim_data, filter, ac.data, ac.datatype);
360                 
361                 /* just tag these animdata-blocks to recalc, assuming that some data there changed 
362                  * BUT only do this if realtime updates are enabled
363                  */
364                 if ((saction->flag & SACTION_NOREALTIMEUPDATES) == 0) {
365                         for (ale= anim_data.first; ale; ale= ale->next) {
366                                 /* set refresh tags for objects using this animation */
367                                 ANIM_list_elem_update(t->scene, ale);
368                         }
369                 }
370                 
371                 /* now free temp channels */
372                 BLI_freelistN(&anim_data);
373         }
374 }
375 /* helper for recalcData() - for Graph Editor transforms */
376 static void recalcData_graphedit(TransInfo *t)
377 {
378         SpaceIpo *sipo= (SpaceIpo *)t->sa->spacedata.first;
379         Scene *scene;
380         
381         ListBase anim_data = {NULL, NULL};
382         bAnimContext ac= {NULL};
383         int filter;
384         
385         bAnimListElem *ale;
386         int dosort = 0;
387         
388         
389         /* initialize relevant anim-context 'context' data from TransInfo data */
390                 /* NOTE: sync this with the code in ANIM_animdata_get_context() */
391         scene= ac.scene= t->scene;
392         ac.obact= OBACT;
393         ac.sa= t->sa;
394         ac.ar= t->ar;
395         ac.sl= (t->sa)? t->sa->spacedata.first : NULL;
396         ac.spacetype= (t->sa)? t->sa->spacetype : 0;
397         ac.regiontype= (t->ar)? t->ar->regiontype : 0;
398         
399         ANIM_animdata_context_getdata(&ac);
400         
401         /* do the flush first */
402         flushTransGraphData(t);
403         
404         /* get curves to check if a re-sort is needed */
405         filter= (ANIMFILTER_DATA_VISIBLE | ANIMFILTER_FOREDIT | ANIMFILTER_CURVE_VISIBLE);
406         ANIM_animdata_filter(&ac, &anim_data, filter, ac.data, ac.datatype);
407         
408         /* now test if there is a need to re-sort */
409         for (ale= anim_data.first; ale; ale= ale->next) {
410                 FCurve *fcu= (FCurve *)ale->key_data;
411                 
412                 /* ignore unselected fcurves */
413                 if (!fcu_test_selected(fcu))
414                         continue;
415                 
416                 // fixme: only do this for selected verts...
417                 ANIM_unit_mapping_apply_fcurve(ac.scene, ale->id, ale->key_data, ANIM_UNITCONV_ONLYSEL|ANIM_UNITCONV_SELVERTS|ANIM_UNITCONV_RESTORE);
418                 
419                 
420                 /* watch it: if the time is wrong: do not correct handles yet */
421                 if (test_time_fcurve(fcu))
422                         dosort++;
423                 else
424                         calchandles_fcurve(fcu);
425                 
426                 /* set refresh tags for objects using this animation,
427                  * BUT only if realtime updates are enabled  
428                  */
429                 if ((sipo->flag & SIPO_NOREALTIMEUPDATES) == 0)
430                         ANIM_list_elem_update(t->scene, ale);
431         }
432         
433         /* do resort and other updates? */
434         if (dosort) remake_graph_transdata(t, &anim_data);
435         
436         /* now free temp channels */
437         BLI_freelistN(&anim_data);
438 }
439
440 /* helper for recalcData() - for NLA Editor transforms */
441 static void recalcData_nla(TransInfo *t)
442 {
443         TransDataNla *tdn= (TransDataNla *)t->customData;
444         SpaceNla *snla= (SpaceNla *)t->sa->spacedata.first;
445         Scene *scene= t->scene;
446         double secf= FPS;
447         int i;
448         
449         /* for each strip we've got, perform some additional validation of the values that got set before
450          * using RNA to set the value (which does some special operations when setting these values to make
451          * sure that everything works ok)
452          */
453         for (i = 0; i < t->total; i++, tdn++) {
454                 NlaStrip *strip= tdn->strip;
455                 PointerRNA strip_ptr;
456                 short pExceeded, nExceeded, iter;
457                 int delta_y1, delta_y2;
458                 
459                 /* if this tdn has no handles, that means it is just a dummy that should be skipped */
460                 if (tdn->handle == 0)
461                         continue;
462                 
463                 /* set refresh tags for objects using this animation,
464                  * BUT only if realtime updates are enabled  
465                  */
466                 if ((snla->flag & SNLA_NOREALTIMEUPDATES) == 0)
467                         ANIM_id_update(t->scene, tdn->id);
468                 
469                 /* if canceling transform, just write the values without validating, then move on */
470                 if (t->state == TRANS_CANCEL) {
471                         /* clear the values by directly overwriting the originals, but also need to restore
472                          * endpoints of neighboring transition-strips
473                          */
474                         
475                         /* start */
476                         strip->start= tdn->h1[0];
477                         
478                         if ((strip->prev) && (strip->prev->type == NLASTRIP_TYPE_TRANSITION))
479                                 strip->prev->end= tdn->h1[0];
480                         
481                         /* end */
482                         strip->end= tdn->h2[0];
483                         
484                         if ((strip->next) && (strip->next->type == NLASTRIP_TYPE_TRANSITION))
485                                 strip->next->start= tdn->h2[0];
486                         
487                         /* flush transforms to child strips (since this should be a meta) */
488                         BKE_nlameta_flush_transforms(strip);
489                         
490                         /* restore to original track (if needed) */
491                         if (tdn->oldTrack != tdn->nlt) {
492                                 /* just append to end of list for now, since strips get sorted in special_aftertrans_update() */
493                                 BLI_remlink(&tdn->nlt->strips, strip);
494                                 BLI_addtail(&tdn->oldTrack->strips, strip);
495                         }
496                         
497                         continue;
498                 }
499                 
500                 /* firstly, check if the proposed transform locations would overlap with any neighboring strips
501                  * (barring transitions) which are absolute barriers since they are not being moved
502                  *
503                  * this is done as a iterative procedure (done 5 times max for now)
504                  */
505                 for (iter=0; iter < 5; iter++) {
506                         pExceeded= ((strip->prev) && (strip->prev->type != NLASTRIP_TYPE_TRANSITION) && (tdn->h1[0] < strip->prev->end));
507                         nExceeded= ((strip->next) && (strip->next->type != NLASTRIP_TYPE_TRANSITION) && (tdn->h2[0] > strip->next->start));
508                         
509                         if ((pExceeded && nExceeded) || (iter == 4) ) {
510                                 /* both endpoints exceeded (or iteration ping-pong'd meaning that we need a compromise)
511                                  *      - simply crop strip to fit within the bounds of the strips bounding it
512                                  *      - if there were no neighbors, clear the transforms (make it default to the strip's current values)
513                                  */
514                                 if (strip->prev && strip->next) {
515                                         tdn->h1[0]= strip->prev->end;
516                                         tdn->h2[0]= strip->next->start;
517                                 }
518                                 else {
519                                         tdn->h1[0]= strip->start;
520                                         tdn->h2[0]= strip->end;
521                                 }
522                         }
523                         else if (nExceeded) {
524                                 /* move backwards */
525                                 float offset= tdn->h2[0] - strip->next->start;
526                                 
527                                 tdn->h1[0] -= offset;
528                                 tdn->h2[0] -= offset;
529                         }
530                         else if (pExceeded) {
531                                 /* more forwards */
532                                 float offset= strip->prev->end - tdn->h1[0];
533                                 
534                                 tdn->h1[0] += offset;
535                                 tdn->h2[0] += offset;
536                         }
537                         else /* all is fine and well */
538                                 break;
539                 }
540                 
541                 /* handle auto-snapping */
542                 switch (snla->autosnap) {
543                         case SACTSNAP_FRAME: /* snap to nearest frame/time  */
544                                 if (snla->flag & SNLA_DRAWTIME) {
545                                         tdn->h1[0] = (float)(floor(((double)tdn->h1[0] / secf) + 0.5) * secf);
546                                         tdn->h2[0] = (float)(floor(((double)tdn->h2[0] / secf) + 0.5) * secf);
547                                 }
548                                 else {
549                                         tdn->h1[0] = floorf(tdn->h1[0] + 0.5f);
550                                         tdn->h2[0] = floorf(tdn->h2[0] + 0.5f);
551                                 }
552                                 break;
553                         
554                         case SACTSNAP_MARKER: /* snap to nearest marker */
555                                 tdn->h1[0]= (float)ED_markers_find_nearest_marker_time(&t->scene->markers, tdn->h1[0]);
556                                 tdn->h2[0]= (float)ED_markers_find_nearest_marker_time(&t->scene->markers, tdn->h2[0]);
557                                 break;
558                 }
559                 
560                 /* use RNA to write the values... */
561                 // TODO: do we need to write in 2 passes to make sure that no truncation goes on?
562                 RNA_pointer_create(NULL, &RNA_NlaStrip, strip, &strip_ptr);
563                 
564                 RNA_float_set(&strip_ptr, "frame_start", tdn->h1[0]);
565                 RNA_float_set(&strip_ptr, "frame_end", tdn->h2[0]);
566                 
567                 /* flush transforms to child strips (since this should be a meta) */
568                 BKE_nlameta_flush_transforms(strip);
569                 
570                 
571                 /* now, check if we need to try and move track
572                  *      - we need to calculate both, as only one may have been altered by transform if only 1 handle moved
573                  */
574                 delta_y1= ((int)tdn->h1[1] / NLACHANNEL_STEP(snla) - tdn->trackIndex);
575                 delta_y2= ((int)tdn->h2[1] / NLACHANNEL_STEP(snla) - tdn->trackIndex);
576                 
577                 if (delta_y1 || delta_y2) {
578                         NlaTrack *track;
579                         int delta = (delta_y2) ? delta_y2 : delta_y1;
580                         int n;
581                         
582                         /* move in the requested direction, checking at each layer if there's space for strip to pass through,
583                          * stopping on the last track available or that we're able to fit in
584                          */
585                         if (delta > 0) {
586                                 for (track=tdn->nlt->next, n=0; (track) && (n < delta); track=track->next, n++) {
587                                         /* check if space in this track for the strip */
588                                         if (BKE_nlatrack_has_space(track, strip->start, strip->end)) {
589                                                 /* move strip to this track */
590                                                 BLI_remlink(&tdn->nlt->strips, strip);
591                                                 BKE_nlatrack_add_strip(track, strip);
592                                                 
593                                                 tdn->nlt= track;
594                                                 tdn->trackIndex++;
595                                         }
596                                         else /* can't move any further */
597                                                 break;
598                                 }
599                         }
600                         else {
601                                 /* make delta 'positive' before using it, since we now know to go backwards */
602                                 delta= -delta;
603                                 
604                                 for (track=tdn->nlt->prev, n=0; (track) && (n < delta); track=track->prev, n++) {
605                                         /* check if space in this track for the strip */
606                                         if (BKE_nlatrack_has_space(track, strip->start, strip->end)) {
607                                                 /* move strip to this track */
608                                                 BLI_remlink(&tdn->nlt->strips, strip);
609                                                 BKE_nlatrack_add_strip(track, strip);
610                                                 
611                                                 tdn->nlt= track;
612                                                 tdn->trackIndex--;
613                                         }
614                                         else /* can't move any further */
615                                                 break;
616                                 }
617                         }
618                 }
619         }
620 }
621
622 /* helper for recalcData() - for Image Editor transforms */
623 static void recalcData_image(TransInfo *t)
624 {
625         if (t->obedit && t->obedit->type == OB_MESH) {
626                 SpaceImage *sima= t->sa->spacedata.first;
627                 
628                 flushTransUVs(t);
629                 if (sima->flag & SI_LIVE_UNWRAP)
630                         ED_uvedit_live_unwrap_re_solve();
631                 
632                 DAG_id_tag_update(t->obedit->data, 0);
633         }
634 }
635
636 /* helper for recalcData() - for Movie Clip transforms */
637 static void recalcData_spaceclip(TransInfo *t)
638 {
639         SpaceClip *sc = t->sa->spacedata.first;
640
641         if (ED_space_clip_show_trackedit(sc)) {
642                 MovieClip *clip = ED_space_clip(sc);
643                 ListBase *tracksbase = BKE_tracking_get_tracks(&clip->tracking);
644                 MovieTrackingTrack *track;
645                 int framenr = sc->user.framenr;
646
647                 flushTransTracking(t);
648
649                 track = tracksbase->first;
650                 while (track) {
651                         if (TRACK_VIEW_SELECTED(sc, track) && (track->flag & TRACK_LOCKED)==0) {
652                                 MovieTrackingMarker *marker = BKE_tracking_get_marker(track, framenr);
653
654                                 if (t->mode == TFM_TRANSLATION) {
655                                         if (TRACK_AREA_SELECTED(track, TRACK_AREA_PAT))
656                                                 BKE_tracking_clamp_marker(marker, CLAMP_PAT_POS);
657                                         if (TRACK_AREA_SELECTED(track, TRACK_AREA_SEARCH))
658                                                 BKE_tracking_clamp_marker(marker, CLAMP_SEARCH_POS);
659                                 }
660                                 else if (t->mode == TFM_RESIZE) {
661                                         if (TRACK_AREA_SELECTED(track, TRACK_AREA_PAT))
662                                                 BKE_tracking_clamp_marker(marker, CLAMP_PAT_DIM);
663                                         if (TRACK_AREA_SELECTED(track, TRACK_AREA_SEARCH))
664                                                 BKE_tracking_clamp_marker(marker, CLAMP_SEARCH_DIM);
665                                 }
666                                 else if (t->mode == TFM_ROTATION) {
667                                         if (TRACK_AREA_SELECTED(track, TRACK_AREA_PAT))
668                                                 BKE_tracking_clamp_marker(marker, CLAMP_PAT_POS);
669                                 }
670                         }
671
672                         track = track->next;
673                 }
674
675                 DAG_id_tag_update(&clip->id, 0);
676         }
677         else if (ED_space_clip_show_maskedit(sc)) {
678                 Mask *mask = ED_space_clip_mask(sc);
679
680                 flushTransMasking(t);
681
682                 DAG_id_tag_update(&mask->id, 0);
683         }
684 }
685
686 /* helper for recalcData() - for 3d-view transforms */
687 static void recalcData_view3d(TransInfo *t)
688 {
689         Base *base = t->scene->basact;
690         
691         if (t->obedit) {
692                 if (ELEM(t->obedit->type, OB_CURVE, OB_SURF)) {
693                         Curve *cu= t->obedit->data;
694                         ListBase *nurbs= BKE_curve_editNurbs_get(cu);
695                         Nurb *nu= nurbs->first;
696                         
697                         if (t->state != TRANS_CANCEL) {
698                                 clipMirrorModifier(t, t->obedit);
699                                 applyProject(t);
700                         }
701                         
702                         DAG_id_tag_update(t->obedit->data, 0);  /* sets recalc flags */
703                                 
704                         if (t->state == TRANS_CANCEL) {
705                                 while (nu) {
706                                         BKE_nurb_handles_calc(nu); /* Cant do testhandlesNurb here, it messes up the h1 and h2 flags */
707                                         nu= nu->next;
708                                 }
709                         } 
710                         else {
711                                 /* Normal updating */
712                                 while (nu) {
713                                         BKE_nurb_test2D(nu);
714                                         BKE_nurb_handles_calc(nu);
715                                         nu= nu->next;
716                                 }
717                         }
718                 }
719                 else if (t->obedit->type==OB_LATTICE) {
720                         Lattice *la= t->obedit->data;
721                         
722                         if (t->state != TRANS_CANCEL) {
723                                 applyProject(t);
724                         }
725                         
726                         DAG_id_tag_update(t->obedit->data, 0);  /* sets recalc flags */
727                         
728                         if (la->editlatt->latt->flag & LT_OUTSIDE) outside_lattice(la->editlatt->latt);
729                 }
730                 else if (t->obedit->type == OB_MESH) {
731                         BMEditMesh *em = BMEdit_FromObject(t->obedit);
732                         /* mirror modifier clipping? */
733                         if (t->state != TRANS_CANCEL) {
734                                 /* apply clipping after so we never project past the clip plane [#25423] */
735                                 applyProject(t);
736                                 clipMirrorModifier(t, t->obedit);
737                         }
738                         if ((t->options & CTX_NO_MIRROR) == 0 && (t->flag & T_MIRROR))
739                                 editbmesh_apply_to_mirror(t);
740                                 
741                         DAG_id_tag_update(t->obedit->data, 0);  /* sets recalc flags */
742                         
743                         EDBM_mesh_normals_update(em);
744                         BMEdit_RecalcTessellation(em);
745                 }
746                 else if (t->obedit->type==OB_ARMATURE) { /* no recalc flag, does pose */
747                         bArmature *arm= t->obedit->data;
748                         ListBase *edbo = arm->edbo;
749                         EditBone *ebo;
750                         TransData *td = t->data;
751                         int i;
752                         
753                         if (t->state != TRANS_CANCEL) {
754                                 applyProject(t);
755                         }
756                         
757                         /* Ensure all bones are correctly adjusted */
758                         for (ebo = edbo->first; ebo; ebo = ebo->next) {
759                                 
760                                 if ((ebo->flag & BONE_CONNECTED) && ebo->parent) {
761                                         /* If this bone has a parent tip that has been moved */
762                                         if (ebo->parent->flag & BONE_TIPSEL) {
763                                                 copy_v3_v3 (ebo->head, ebo->parent->tail);
764                                                 if (t->mode==TFM_BONE_ENVELOPE) ebo->rad_head= ebo->parent->rad_tail;
765                                         }
766                                         /* If this bone has a parent tip that has NOT been moved */
767                                         else {
768                                                 copy_v3_v3 (ebo->parent->tail, ebo->head);
769                                                 if (t->mode==TFM_BONE_ENVELOPE) ebo->parent->rad_tail= ebo->rad_head;
770                                         }
771                                 }
772                                 
773                                 /* on extrude bones, oldlength==0.0f, so we scale radius of points */
774                                 ebo->length= len_v3v3(ebo->head, ebo->tail);
775                                 if (ebo->oldlength==0.0f) {
776                                         ebo->rad_head= 0.25f*ebo->length;
777                                         ebo->rad_tail= 0.10f*ebo->length;
778                                         ebo->dist= 0.25f*ebo->length;
779                                         if (ebo->parent) {
780                                                 if (ebo->rad_head > ebo->parent->rad_tail)
781                                                         ebo->rad_head= ebo->parent->rad_tail;
782                                         }
783                                 }
784                                 else if (t->mode!=TFM_BONE_ENVELOPE) {
785                                         /* if bones change length, lets do that for the deform distance as well */
786                                         ebo->dist*= ebo->length/ebo->oldlength;
787                                         ebo->rad_head*= ebo->length/ebo->oldlength;
788                                         ebo->rad_tail*= ebo->length/ebo->oldlength;
789                                         ebo->oldlength= ebo->length;
790                                 }
791                         }
792                         
793                         
794                         if (t->mode != TFM_BONE_ROLL) {
795                                 /* fix roll */
796                                 for (i = 0; i < t->total; i++, td++) {
797                                         if (td->extra) {
798                                                 float vec[3], up_axis[3];
799                                                 float qrot[4];
800                                                 
801                                                 ebo = td->extra;
802                                                 copy_v3_v3(up_axis, td->axismtx[2]);
803                                                 
804                                                 if (t->mode != TFM_ROTATION) {
805                                                         sub_v3_v3v3(vec, ebo->tail, ebo->head);
806                                                         normalize_v3(vec);
807                                                         rotation_between_vecs_to_quat(qrot, td->axismtx[1], vec);
808                                                         mul_qt_v3(qrot, up_axis);
809                                                 }
810                                                 else {
811                                                         mul_m3_v3(t->mat, up_axis);
812                                                 }
813                                                 
814                                                 ebo->roll = ED_rollBoneToVector(ebo, up_axis, FALSE);
815                                         }
816                                 }
817                         }
818                         
819                         if (arm->flag & ARM_MIRROR_EDIT)
820                                 transform_armature_mirror_update(t->obedit);
821                         
822                 }
823                 else {
824                         if (t->state != TRANS_CANCEL) {
825                                 applyProject(t);
826                         }
827                         DAG_id_tag_update(t->obedit->data, 0);  /* sets recalc flags */
828                 }
829         }
830         else if ( (t->flag & T_POSE) && t->poseobj) {
831                 Object *ob= t->poseobj;
832                 bArmature *arm= ob->data;
833                 
834                 /* if animtimer is running, and the object already has animation data,
835                  * check if the auto-record feature means that we should record 'samples'
836                  * (i.e. uneditable animation values)
837                  *
838                  * context is needed for keying set poll() functions.
839                  */
840                 // TODO: autokeyframe calls need some setting to specify to add samples (FPoints) instead of keyframes?
841                 if ((t->animtimer) && (t->context) && IS_AUTOKEY_ON(t->scene)) {
842                         int targetless_ik= (t->flag & T_AUTOIK); // XXX this currently doesn't work, since flags aren't set yet!
843                         
844                         animrecord_check_state(t->scene, &ob->id, t->animtimer);
845                         autokeyframe_pose_cb_func(t->context, t->scene, (View3D *)t->view, ob, t->mode, targetless_ik);
846                 }
847                 
848                 /* old optimize trick... this enforces to bypass the depgraph */
849                 if (!(arm->flag & ARM_DELAYDEFORM)) {
850                         DAG_id_tag_update(&ob->id, OB_RECALC_DATA);  /* sets recalc flags */
851                 }
852                 else
853                         BKE_pose_where_is(t->scene, ob);
854         }
855         else if (base && (base->object->mode & OB_MODE_PARTICLE_EDIT) && PE_get_current(t->scene, base->object)) {
856                 if (t->state != TRANS_CANCEL) {
857                         applyProject(t);
858                 }
859                 flushTransParticles(t);
860         }
861         else {
862                 int i;
863                 
864                 if (t->state != TRANS_CANCEL) {
865                         applyProject(t);
866                 }
867                 
868                 for (i = 0; i < t->total; i++) {
869                         TransData *td = t->data + i;
870                         Object *ob = td->ob;
871                         
872                         if (td->flag & TD_NOACTION)
873                                 break;
874                         
875                         if (td->flag & TD_SKIP)
876                                 continue;
877                         
878                         /* if animtimer is running, and the object already has animation data,
879                          * check if the auto-record feature means that we should record 'samples'
880                          * (i.e. uneditable animation values)
881                          */
882                         // TODO: autokeyframe calls need some setting to specify to add samples (FPoints) instead of keyframes?
883                         if ((t->animtimer) && IS_AUTOKEY_ON(t->scene)) {
884                                 animrecord_check_state(t->scene, &ob->id, t->animtimer);
885                                 autokeyframe_ob_cb_func(t->context, t->scene, (View3D *)t->view, ob, t->mode);
886                         }
887                         
888                         /* sets recalc flags fully, instead of flushing existing ones 
889                          * otherwise proxies don't function correctly
890                          */
891                         DAG_id_tag_update(&ob->id, OB_RECALC_OB);
892                 }
893         }
894 }
895
896 /* called for updating while transform acts, once per redraw */
897 void recalcData(TransInfo *t)
898 {
899         if (t->spacetype==SPACE_NODE) {
900                 flushTransNodes(t);
901         }
902         else if (t->spacetype==SPACE_SEQ) {
903                 flushTransSeq(t);
904         }
905         else if (t->spacetype == SPACE_ACTION) {
906                 recalcData_actedit(t);
907         }
908         else if (t->spacetype == SPACE_IPO) {
909                 recalcData_graphedit(t);
910         }
911         else if (t->spacetype == SPACE_NLA) {
912                 recalcData_nla(t);
913         }
914         else if (t->spacetype == SPACE_IMAGE) {
915                 recalcData_image(t);
916         }
917         else if (t->spacetype == SPACE_VIEW3D) {
918                 recalcData_view3d(t);
919         }
920         else if (t->spacetype == SPACE_CLIP) {
921                 recalcData_spaceclip(t);
922         }
923 }
924
925 void drawLine(TransInfo *t, float *center, float *dir, char axis, short options)
926 {
927         float v1[3], v2[3], v3[3];
928         unsigned char col[3], col2[3];
929
930         if (t->spacetype == SPACE_VIEW3D) {
931                 View3D *v3d = t->view;
932                 
933                 glPushMatrix();
934                 
935                 //if (t->obedit) glLoadMatrixf(t->obedit->obmat);       // sets opengl viewing
936                 
937                 
938                 copy_v3_v3(v3, dir);
939                 mul_v3_fl(v3, v3d->far);
940                 
941                 sub_v3_v3v3(v2, center, v3);
942                 add_v3_v3v3(v1, center, v3);
943                 
944                 if (options & DRAWLIGHT) {
945                         col[0] = col[1] = col[2] = 220;
946                 }
947                 else {
948                         UI_GetThemeColor3ubv(TH_GRID, col);
949                 }
950                 UI_make_axis_color(col, col2, axis);
951                 glColor3ubv(col2);
952                 
953                 setlinestyle(0);
954                 glBegin(GL_LINE_STRIP);
955                         glVertex3fv(v1);
956                         glVertex3fv(v2);
957                 glEnd();
958                 
959                 glPopMatrix();
960         }
961 }
962
963 void resetTransRestrictions(TransInfo *t)
964 {
965         t->flag &= ~T_ALL_RESTRICTIONS;
966 }
967
968 /* the *op can be NULL */
969 int initTransInfo(bContext *C, TransInfo *t, wmOperator *op, wmEvent *event)
970 {
971         Scene *sce = CTX_data_scene(C);
972         ToolSettings *ts = CTX_data_tool_settings(C);
973         ARegion *ar = CTX_wm_region(C);
974         ScrArea *sa = CTX_wm_area(C);
975         Object *obedit = CTX_data_edit_object(C);
976         
977         /* moving: is shown in drawobject() (transform color) */
978 //  TRANSFORM_FIX_ME
979 //      if (obedit || (t->flag & T_POSE) ) G.moving= G_TRANSFORM_EDIT;
980 //      else if (G.f & G_PARTICLEEDIT) G.moving= G_TRANSFORM_PARTICLE;
981 //      else G.moving= G_TRANSFORM_OBJ;
982         
983         t->scene = sce;
984         t->sa = sa;
985         t->ar = ar;
986         t->obedit = obedit;
987         t->settings = ts;
988         
989         t->data = NULL;
990         t->ext = NULL;
991         
992         t->helpline = HLP_NONE;
993         
994         t->flag = 0;
995         
996         t->redraw = 1; /* redraw first time */
997         
998         if (event) {
999                 copy_v2_v2_int(t->imval, event->mval);
1000                 t->event_type = event->type;
1001         }
1002         else {
1003                 t->imval[0] = 0;
1004                 t->imval[1] = 0;
1005         }
1006         
1007         t->con.imval[0] = t->imval[0];
1008         t->con.imval[1] = t->imval[1];
1009         
1010         t->mval[0] = t->imval[0];
1011         t->mval[1] = t->imval[1];
1012         
1013         t->transform            = NULL;
1014         t->handleEvent          = NULL;
1015         
1016         t->total                        = 0;
1017         
1018         t->val = 0.0f;
1019         
1020         t->vec[0]                       =
1021                 t->vec[1]               =
1022                 t->vec[2]               = 0.0f;
1023         
1024         t->center[0]            =
1025                 t->center[1]    =
1026                 t->center[2]    = 0.0f;
1027         
1028         unit_m3(t->mat);
1029         
1030         /* if there's an event, we're modal */
1031         if (event) {
1032                 t->flag |= T_MODAL;
1033         }
1034
1035         /* Crease needs edge flag */
1036         if (ELEM(t->mode, TFM_CREASE, TFM_BWEIGHT)) {
1037                 t->options |= CTX_EDGE;
1038         }
1039
1040
1041         /* Assign the space type, some exceptions for running in different mode */
1042         if (sa == NULL) {
1043                 /* background mode */
1044                 t->spacetype= SPACE_EMPTY;
1045         }
1046         else if ((ar == NULL) && (sa->spacetype == SPACE_VIEW3D)) {
1047                 /* running in the text editor */
1048                 t->spacetype= SPACE_EMPTY;
1049         }
1050         else {
1051                 /* normal operation */
1052                 t->spacetype= sa->spacetype;
1053         }
1054
1055
1056         if (t->spacetype == SPACE_VIEW3D) {
1057                 View3D *v3d = sa->spacedata.first;
1058                 
1059                 t->view = v3d;
1060                 t->animtimer= CTX_wm_screen(C)->animtimer;
1061                 
1062                 /* turn manipulator off during transform */
1063                 // FIXME: but don't do this when USING the manipulator...
1064                 if (t->flag & T_MODAL) {
1065                         t->twtype = v3d->twtype;
1066                         v3d->twtype = 0;
1067                 }
1068
1069                 if (v3d->flag & V3D_ALIGN) t->flag |= T_V3D_ALIGN;
1070                 t->around = v3d->around;
1071                 
1072                 if (op && (RNA_struct_find_property(op->ptr, "constraint_orientation") &&
1073                            RNA_struct_property_is_set(op->ptr, "constraint_orientation")))
1074                 {
1075                         t->current_orientation = RNA_enum_get(op->ptr, "constraint_orientation");
1076
1077                         if (t->current_orientation >= V3D_MANIP_CUSTOM + BIF_countTransformOrientation(C)) {
1078                                 t->current_orientation = V3D_MANIP_GLOBAL;
1079                         }
1080                 }
1081                 else {
1082                         t->current_orientation = v3d->twmode;
1083                 }
1084
1085                 /* exceptional case */
1086                 if (t->around==V3D_LOCAL && (t->settings->selectmode & SCE_SELECT_FACE)) {
1087                         if (ELEM3(t->mode, TFM_ROTATION, TFM_RESIZE, TFM_TRACKBALL)) {
1088                                 t->options |= CTX_NO_PET;
1089                         }
1090                 }
1091
1092                 /* initialize UV transform from */
1093                 if (op && RNA_struct_find_property(op->ptr, "correct_uv")) {
1094                         if (RNA_struct_property_is_set(op->ptr, "correct_uv")) {
1095                                 if (RNA_boolean_get(op->ptr, "correct_uv")) {
1096                                         t->settings->uvcalc_flag |= UVCALC_TRANSFORM_CORRECT;
1097                                 }
1098                                 else {
1099                                         t->settings->uvcalc_flag &= ~UVCALC_TRANSFORM_CORRECT;
1100                                 }
1101                         }
1102                         else {
1103                                 RNA_boolean_set(op->ptr, "correct_uv", t->settings->uvcalc_flag & UVCALC_TRANSFORM_CORRECT);
1104                         }
1105                 }
1106
1107         }
1108         else if (t->spacetype==SPACE_IMAGE) {
1109                 SpaceImage *sima = sa->spacedata.first;
1110                 // XXX for now, get View2D from the active region
1111                 t->view = &ar->v2d;
1112                 t->around = sima->around;
1113         }
1114         else if (t->spacetype==SPACE_NODE) {
1115                 // XXX for now, get View2D from the active region
1116                 t->view = &ar->v2d;
1117                 t->around = V3D_CENTER;
1118         }
1119         else if (t->spacetype==SPACE_IPO) {
1120                 SpaceIpo *sipo= sa->spacedata.first;
1121                 t->view = &ar->v2d;
1122                 t->around = sipo->around;
1123         }
1124         else if (t->spacetype==SPACE_CLIP) {
1125                 SpaceClip *sclip = sa->spacedata.first;
1126                 t->view = &ar->v2d;
1127                 t->around = sclip->around;
1128         }
1129         else {
1130                 if (ar) {
1131                         // XXX for now, get View2D  from the active region
1132                         t->view = &ar->v2d;
1133                         // XXX for now, the center point is the midpoint of the data
1134                 }
1135                 else {
1136                         t->view= NULL;
1137                 }
1138                 t->around = V3D_CENTER;
1139         }
1140         
1141         if (op && RNA_struct_property_is_set(op->ptr, "release_confirm")) {
1142                 if (RNA_boolean_get(op->ptr, "release_confirm")) {
1143                         t->flag |= T_RELEASE_CONFIRM;
1144                 }
1145         }
1146         else {
1147                 if (U.flag & USER_RELEASECONFIRM) {
1148                         t->flag |= T_RELEASE_CONFIRM;
1149                 }
1150         }
1151
1152         if (op && (RNA_struct_find_property(op->ptr, "mirror") &&
1153                    RNA_struct_property_is_set(op->ptr, "mirror")))
1154         {
1155                 if (RNA_boolean_get(op->ptr, "mirror")) {
1156                         t->flag |= T_MIRROR;
1157                         t->mirror = 1;
1158                 }
1159         }
1160         // Need stuff to take it from edit mesh or whatnot here
1161         else if (t->spacetype == SPACE_VIEW3D) {
1162                 if (t->obedit && t->obedit->type == OB_MESH && (((Mesh *)t->obedit->data)->editflag & ME_EDIT_MIRROR_X)) {
1163                         t->flag |= T_MIRROR;
1164                         t->mirror = 1;
1165                 }
1166         }
1167         
1168         /* setting PET flag only if property exist in operator. Otherwise, assume it's not supported */
1169         if (op && RNA_struct_find_property(op->ptr, "proportional")) {
1170                 if (RNA_struct_property_is_set(op->ptr, "proportional")) {
1171                         switch (RNA_enum_get(op->ptr, "proportional")) {
1172                                 case PROP_EDIT_CONNECTED:
1173                                         t->flag |= T_PROP_CONNECTED;
1174                                 case PROP_EDIT_ON:
1175                                         t->flag |= T_PROP_EDIT;
1176                                         break;
1177                         }
1178                 }
1179                 else {
1180                         /* use settings from scene only if modal */
1181                         if (t->flag & T_MODAL) {
1182                                 if ((t->options & CTX_NO_PET) == 0) {
1183                                         if (t->obedit && ts->proportional != PROP_EDIT_OFF) {
1184                                                 t->flag |= T_PROP_EDIT;
1185
1186                                                 if (ts->proportional == PROP_EDIT_CONNECTED) {
1187                                                         t->flag |= T_PROP_CONNECTED;
1188                                                 }
1189                                         }
1190                                         else if (t->obedit == NULL && ts->proportional_objects) {
1191                                                 t->flag |= T_PROP_EDIT;
1192                                         }
1193                                 }
1194                         }
1195                 }
1196                 
1197                 if (op && (RNA_struct_find_property(op->ptr, "proportional_size") &&
1198                            RNA_struct_property_is_set(op->ptr, "proportional_size")))
1199                 {
1200                         t->prop_size = RNA_float_get(op->ptr, "proportional_size");
1201                 }
1202                 else {
1203                         t->prop_size = ts->proportional_size;
1204                 }
1205                 
1206                 
1207                 /* TRANSFORM_FIX_ME rna restrictions */
1208                 if (t->prop_size <= 0.00001f) {
1209                         printf("Proportional size (%f) under 0.00001, reseting to 1!\n", t->prop_size);
1210                         t->prop_size = 1.0f;
1211                 }
1212                 
1213                 if (op && (RNA_struct_find_property(op->ptr, "proportional_edit_falloff") &&
1214                            RNA_struct_property_is_set(op->ptr, "proportional_edit_falloff")))
1215                 {
1216                         t->prop_mode = RNA_enum_get(op->ptr, "proportional_edit_falloff");
1217                 }
1218                 else {
1219                         t->prop_mode = ts->prop_mode;
1220                 }
1221         }
1222         else { /* add not pet option to context when not available */
1223                 t->options |= CTX_NO_PET;
1224         }
1225         
1226         // Mirror is not supported with PET, turn it off.
1227         if (t->flag & T_PROP_EDIT) {
1228                 t->flag &= ~T_MIRROR;
1229         }
1230
1231         setTransformViewMatrices(t);
1232         initNumInput(&t->num);
1233         
1234         return 1;
1235 }
1236
1237 /* Here I would suggest only TransInfo related issues, like free data & reset vars. Not redraws */
1238 void postTrans(bContext *C, TransInfo *t)
1239 {
1240         TransData *td;
1241         
1242         if (t->draw_handle_view)
1243                 ED_region_draw_cb_exit(t->ar->type, t->draw_handle_view);
1244         if (t->draw_handle_apply)
1245                 ED_region_draw_cb_exit(t->ar->type, t->draw_handle_apply);
1246         if (t->draw_handle_pixel)
1247                 ED_region_draw_cb_exit(t->ar->type, t->draw_handle_pixel);
1248         if (t->draw_handle_cursor)
1249                 WM_paint_cursor_end(CTX_wm_manager(C), t->draw_handle_cursor);
1250
1251         if (t->customFree) {
1252                 /* Can take over freeing t->data and data2d etc... */
1253                 t->customFree(t);
1254         }
1255         else if ((t->customData != NULL) && (t->flag & T_FREE_CUSTOMDATA)) {
1256                 MEM_freeN(t->customData);
1257         }
1258
1259         /* postTrans can be called when nothing is selected, so data is NULL already */
1260         if (t->data) {
1261                 int a;
1262                 
1263                 /* free data malloced per trans-data */
1264                 for (a=0, td= t->data; a<t->total; a++, td++) {
1265                         if (td->flag & TD_BEZTRIPLE) 
1266                                 MEM_freeN(td->hdata);
1267                 }
1268                 MEM_freeN(t->data);
1269         }
1270         
1271         BLI_freelistN(&t->tsnap.points);
1272
1273         if (t->ext) MEM_freeN(t->ext);
1274         if (t->data2d) {
1275                 MEM_freeN(t->data2d);
1276                 t->data2d= NULL;
1277         }
1278         
1279         if (t->spacetype==SPACE_IMAGE) {
1280                 SpaceImage *sima= t->sa->spacedata.first;
1281                 if (sima->flag & SI_LIVE_UNWRAP)
1282                         ED_uvedit_live_unwrap_end(t->state == TRANS_CANCEL);
1283         }
1284         else if (t->spacetype==SPACE_VIEW3D) {
1285                 View3D *v3d = t->sa->spacedata.first;
1286                 /* restore manipulator */
1287                 if (t->flag & T_MODAL) {
1288                         v3d->twtype = t->twtype;
1289                 }
1290         }
1291         
1292         if (t->mouse.data) {
1293                 MEM_freeN(t->mouse.data);
1294         }
1295 }
1296
1297 void applyTransObjects(TransInfo *t)
1298 {
1299         TransData *td;
1300         
1301         for (td = t->data; td < t->data + t->total; td++) {
1302                 copy_v3_v3(td->iloc, td->loc);
1303                 if (td->ext->rot) {
1304                         copy_v3_v3(td->ext->irot, td->ext->rot);
1305                 }
1306                 if (td->ext->size) {
1307                         copy_v3_v3(td->ext->isize, td->ext->size);
1308                 }
1309         }
1310         recalcData(t);
1311 }
1312
1313 static void restoreElement(TransData *td)
1314 {
1315         /* TransData for crease has no loc */
1316         if (td->loc) {
1317                 copy_v3_v3(td->loc, td->iloc);
1318         }
1319         if (td->val) {
1320                 *td->val = td->ival;
1321         }
1322
1323         if (td->ext && (td->flag&TD_NO_EXT)==0) {
1324                 if (td->ext->rot) {
1325                         copy_v3_v3(td->ext->rot, td->ext->irot);
1326                 }
1327                 if (td->ext->rotAngle) {
1328                         *td->ext->rotAngle= td->ext->irotAngle;
1329                 }
1330                 if (td->ext->rotAxis) {
1331                         copy_v3_v3(td->ext->rotAxis, td->ext->irotAxis);
1332                 }
1333                 /* XXX, drotAngle & drotAxis not used yet */
1334                 if (td->ext->size) {
1335                         copy_v3_v3(td->ext->size, td->ext->isize);
1336                 }
1337                 if (td->ext->quat) {
1338                         copy_qt_qt(td->ext->quat, td->ext->iquat);
1339                 }
1340         }
1341         
1342         if (td->flag & TD_BEZTRIPLE) {
1343                 *(td->hdata->h1) = td->hdata->ih1;
1344                 *(td->hdata->h2) = td->hdata->ih2;
1345         }
1346 }
1347
1348 void restoreTransObjects(TransInfo *t)
1349 {
1350         TransData *td;
1351         TransData2D *td2d;
1352
1353         for (td = t->data; td < t->data + t->total; td++) {
1354                 restoreElement(td);
1355         }
1356         
1357         for (td2d=t->data2d; t->data2d && td2d < t->data2d + t->total; td2d++) {
1358                 if (td2d->h1) {
1359                         td2d->h1[0] = td2d->ih1[0];
1360                         td2d->h1[1] = td2d->ih1[1];
1361                 }
1362                 if (td2d->h2) {
1363                         td2d->h2[0] = td2d->ih2[0];
1364                         td2d->h2[1] = td2d->ih2[1];
1365                 }
1366         }
1367
1368         unit_m3(t->mat);
1369         
1370         recalcData(t);
1371 }
1372
1373 void calculateCenter2D(TransInfo *t)
1374 {
1375         if (t->flag & (T_EDIT|T_POSE)) {
1376                 Object *ob= t->obedit?t->obedit:t->poseobj;
1377                 float vec[3];
1378                 
1379                 copy_v3_v3(vec, t->center);
1380                 mul_m4_v3(ob->obmat, vec);
1381                 projectIntView(t, vec, t->center2d);
1382         }
1383         else {
1384                 projectIntView(t, t->center, t->center2d);
1385         }
1386 }
1387
1388 void calculateCenterCursor(TransInfo *t)
1389 {
1390         float *cursor;
1391         
1392         cursor = give_cursor(t->scene, t->view);
1393         copy_v3_v3(t->center, cursor);
1394         
1395         /* If edit or pose mode, move cursor in local space */
1396         if (t->flag & (T_EDIT|T_POSE)) {
1397                 Object *ob = t->obedit?t->obedit:t->poseobj;
1398                 float mat[3][3], imat[3][3];
1399                 
1400                 sub_v3_v3v3(t->center, t->center, ob->obmat[3]);
1401                 copy_m3_m4(mat, ob->obmat);
1402                 invert_m3_m3(imat, mat);
1403                 mul_m3_v3(imat, t->center);
1404         }
1405         
1406         calculateCenter2D(t);
1407 }
1408
1409 void calculateCenterCursor2D(TransInfo *t)
1410 {
1411         float aspx=1.0, aspy=1.0;
1412         float *cursor= NULL;
1413         
1414         if (t->spacetype==SPACE_IMAGE) {
1415                 SpaceImage *sima= (SpaceImage *)t->sa->spacedata.first;
1416                 /* only space supported right now but may change */
1417                 ED_space_image_uv_aspect(sima, &aspx, &aspy);
1418                 cursor = sima->cursor;
1419         }
1420         
1421         if (cursor) {
1422                 t->center[0] = cursor[0] * aspx;
1423                 t->center[1] = cursor[1] * aspy;
1424         }
1425         
1426         calculateCenter2D(t);
1427 }
1428
1429 static void calculateCenterCursorGraph2D(TransInfo *t)
1430 {
1431         SpaceIpo *sipo= (SpaceIpo *)t->sa->spacedata.first;
1432         Scene *scene= t->scene;
1433         
1434         /* cursor is combination of current frame, and graph-editor cursor value */
1435         t->center[0]= (float)(scene->r.cfra);
1436         t->center[1]= sipo->cursorVal;
1437         
1438         calculateCenter2D(t);
1439 }
1440
1441 void calculateCenterMedian(TransInfo *t)
1442 {
1443         float partial[3] = {0.0f, 0.0f, 0.0f};
1444         int total = 0;
1445         int i;
1446         
1447         for (i = 0; i < t->total; i++) {
1448                 if (t->data[i].flag & TD_SELECTED) {
1449                         if (!(t->data[i].flag & TD_NOCENTER)) {
1450                                 add_v3_v3(partial, t->data[i].center);
1451                                 total++;
1452                         }
1453                 }
1454                 else {
1455                         /*
1456                          * All the selected elements are at the head of the array
1457                          * which means we can stop when it finds unselected data
1458                          */
1459                         break;
1460                 }
1461         }
1462         if (i)
1463                 mul_v3_fl(partial, 1.0f / total);
1464         copy_v3_v3(t->center, partial);
1465         
1466         calculateCenter2D(t);
1467 }
1468
1469 void calculateCenterBound(TransInfo *t)
1470 {
1471         float max[3];
1472         float min[3];
1473         int i;
1474         for (i = 0; i < t->total; i++) {
1475                 if (i) {
1476                         if (t->data[i].flag & TD_SELECTED) {
1477                                 if (!(t->data[i].flag & TD_NOCENTER))
1478                                         minmax_v3v3_v3(min, max, t->data[i].center);
1479                         }
1480                         else {
1481                                 /*
1482                                  * All the selected elements are at the head of the array
1483                                  * which means we can stop when it finds unselected data
1484                                  */
1485                                 break;
1486                         }
1487                 }
1488                 else {
1489                         copy_v3_v3(max, t->data[i].center);
1490                         copy_v3_v3(min, t->data[i].center);
1491                 }
1492         }
1493         add_v3_v3v3(t->center, min, max);
1494         mul_v3_fl(t->center, 0.5);
1495         
1496         calculateCenter2D(t);
1497 }
1498
1499 void calculateCenter(TransInfo *t)
1500 {
1501         switch (t->around) {
1502         case V3D_CENTER:
1503                 calculateCenterBound(t);
1504                 break;
1505         case V3D_CENTROID:
1506                 calculateCenterMedian(t);
1507                 break;
1508         case V3D_CURSOR:
1509                 if (t->spacetype==SPACE_IMAGE)
1510                         calculateCenterCursor2D(t);
1511                 else if (t->spacetype==SPACE_IPO)
1512                         calculateCenterCursorGraph2D(t);
1513                 else
1514                         calculateCenterCursor(t);
1515                 break;
1516         case V3D_LOCAL:
1517                 /* Individual element center uses median center for helpline and such */
1518                 calculateCenterMedian(t);
1519                 break;
1520         case V3D_ACTIVE:
1521                 {
1522                 /* set median, and if if if... do object center */
1523                 
1524                 /* EDIT MODE ACTIVE EDITMODE ELEMENT */
1525
1526                 if (t->obedit) {
1527                         if (t->obedit && t->obedit->type == OB_MESH) {
1528                                 BMEditSelection ese;
1529                                 BMEditMesh *em = BMEdit_FromObject(t->obedit);
1530
1531                                 if (BM_select_history_active_get(em->bm, &ese)) {
1532                                         BM_editselection_center(&ese, t->center);
1533                                         calculateCenter2D(t);
1534                                         break;
1535                                 }
1536                         }
1537                         else if (ELEM(t->obedit->type, OB_CURVE, OB_SURF)) {
1538                                 float center[3];
1539                                 Curve *cu= (Curve *)t->obedit->data;
1540
1541                                 if (ED_curve_actSelection(cu, center)) {
1542                                         copy_v3_v3(t->center, center);
1543                                         calculateCenter2D(t);
1544                                         break;
1545                                 }
1546                         }
1547                 } /* END EDIT MODE ACTIVE ELEMENT */
1548
1549                 calculateCenterMedian(t);
1550                 if ((t->flag & (T_EDIT|T_POSE))==0) {
1551                         Scene *scene = t->scene;
1552                         Object *ob= OBACT;
1553                         if (ob) {
1554                                 copy_v3_v3(t->center, ob->obmat[3]);
1555                                 projectIntView(t, t->center, t->center2d);
1556                         }
1557                 }
1558                 
1559                 }
1560         }
1561         
1562         /* setting constraint center */
1563         copy_v3_v3(t->con.center, t->center);
1564         if (t->flag & (T_EDIT|T_POSE)) {
1565                 Object *ob= t->obedit?t->obedit:t->poseobj;
1566                 mul_m4_v3(ob->obmat, t->con.center);
1567         }
1568         
1569         /* for panning from cameraview */
1570         if (t->flag & T_OBJECT) {
1571                 if (t->spacetype==SPACE_VIEW3D && t->ar && t->ar->regiontype == RGN_TYPE_WINDOW) {
1572                         View3D *v3d = t->view;
1573                         Scene *scene = t->scene;
1574                         RegionView3D *rv3d = t->ar->regiondata;
1575                         
1576                         if (v3d->camera == OBACT && rv3d->persp==RV3D_CAMOB) {
1577                                 float axis[3];
1578                                 /* persinv is nasty, use viewinv instead, always right */
1579                                 copy_v3_v3(axis, t->viewinv[2]);
1580                                 normalize_v3(axis);
1581                                 
1582                                 /* 6.0 = 6 grid units */
1583                                 axis[0]= t->center[0]- 6.0f*axis[0];
1584                                 axis[1]= t->center[1]- 6.0f*axis[1];
1585                                 axis[2]= t->center[2]- 6.0f*axis[2];
1586                                 
1587                                 projectIntView(t, axis, t->center2d);
1588                                 
1589                                 /* rotate only needs correct 2d center, grab needs initgrabz() value */
1590                                 if (t->mode==TFM_TRANSLATION) {
1591                                         copy_v3_v3(t->center, axis);
1592                                         copy_v3_v3(t->con.center, t->center);
1593                                 }
1594                         }
1595                 }
1596         }
1597         
1598         if (t->spacetype==SPACE_VIEW3D) {
1599                 /* initgrabz() defines a factor for perspective depth correction, used in window_to_3d_delta() */
1600                 if (t->flag & (T_EDIT|T_POSE)) {
1601                         Object *ob= t->obedit?t->obedit:t->poseobj;
1602                         float vec[3];
1603                         
1604                         copy_v3_v3(vec, t->center);
1605                         mul_m4_v3(ob->obmat, vec);
1606                         initgrabz(t->ar->regiondata, vec[0], vec[1], vec[2]);
1607                 }
1608                 else {
1609                         initgrabz(t->ar->regiondata, t->center[0], t->center[1], t->center[2]);
1610                 }
1611         }
1612 }
1613
1614 void calculatePropRatio(TransInfo *t)
1615 {
1616         TransData *td = t->data;
1617         int i;
1618         float dist;
1619         short connected = t->flag & T_PROP_CONNECTED;
1620
1621         if (t->flag & T_PROP_EDIT) {
1622                 for (i = 0 ; i < t->total; i++, td++) {
1623                         if (td->flag & TD_SELECTED) {
1624                                 td->factor = 1.0f;
1625                         }
1626                         else if (t->flag & T_MIRROR && td->loc[0] * t->mirror < -0.00001f) {
1627                                 td->flag |= TD_SKIP;
1628                                 td->factor = 0.0f;
1629                                 restoreElement(td);
1630                         }
1631                         else if ((connected && (td->flag & TD_NOTCONNECTED || td->dist > t->prop_size)) ||
1632                                  (connected == 0 && td->rdist > t->prop_size))
1633                         {
1634                                 /*
1635                                  * The elements are sorted according to their dist member in the array,
1636                                  * that means we can stop when it finds one element outside of the propsize.
1637                                  */
1638                                 td->flag |= TD_NOACTION;
1639                                 td->factor = 0.0f;
1640                                 restoreElement(td);
1641                         }
1642                         else {
1643                                 /* Use rdist for falloff calculations, it is the real distance */
1644                                 td->flag &= ~TD_NOACTION;
1645                                 
1646                                 if (connected)
1647                                         dist= (t->prop_size-td->dist)/t->prop_size;
1648                                 else
1649                                         dist= (t->prop_size-td->rdist)/t->prop_size;
1650
1651                                 /*
1652                                  * Clamp to positive numbers.
1653                                  * Certain corner cases with connectivity and individual centers
1654                                  * can give values of rdist larger than propsize.
1655                                  */
1656                                 if (dist < 0.0f)
1657                                         dist = 0.0f;
1658                                 
1659                                 switch (t->prop_mode) {
1660                                 case PROP_SHARP:
1661                                         td->factor= dist*dist;
1662                                         break;
1663                                 case PROP_SMOOTH:
1664                                         td->factor= 3.0f*dist*dist - 2.0f*dist*dist*dist;
1665                                         break;
1666                                 case PROP_ROOT:
1667                                         td->factor = (float)sqrt(dist);
1668                                         break;
1669                                 case PROP_LIN:
1670                                         td->factor = dist;
1671                                         break;
1672                                 case PROP_CONST:
1673                                         td->factor = 1.0f;
1674                                         break;
1675                                 case PROP_SPHERE:
1676                                         td->factor = (float)sqrt(2*dist - dist * dist);
1677                                         break;
1678                                 case PROP_RANDOM:
1679                                         BLI_srand(BLI_rand()); /* random seed */
1680                                         td->factor = BLI_frand()*dist;
1681                                         break;
1682                                 default:
1683                                         td->factor = 1;
1684                                 }
1685                         }
1686                 }
1687                 switch (t->prop_mode) {
1688                 case PROP_SHARP:
1689                         strcpy(t->proptext, "(Sharp)");
1690                         break;
1691                 case PROP_SMOOTH:
1692                         strcpy(t->proptext, "(Smooth)");
1693                         break;
1694                 case PROP_ROOT:
1695                         strcpy(t->proptext, "(Root)");
1696                         break;
1697                 case PROP_LIN:
1698                         strcpy(t->proptext, "(Linear)");
1699                         break;
1700                 case PROP_CONST:
1701                         strcpy(t->proptext, "(Constant)");
1702                         break;
1703                 case PROP_SPHERE:
1704                         strcpy(t->proptext, "(Sphere)");
1705                         break;
1706                 case PROP_RANDOM:
1707                         strcpy(t->proptext, "(Random)");
1708                         break;
1709                 default:
1710                         t->proptext[0]= '\0';
1711                 }
1712         }
1713         else {
1714                 for (i = 0 ; i < t->total; i++, td++) {
1715                         td->factor = 1.0;
1716                 }
1717                 t->proptext[0]= '\0';
1718         }
1719 }