Merging r41555 through r41563 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_meshdata_types.h"
48 #include "DNA_view3d_types.h"
49 #include "DNA_modifier_types.h"
50 #include "DNA_movieclip_types.h"
51
52 #include "RNA_access.h"
53
54 //#include "BIF_screen.h"
55 //#include "BIF_mywindow.h"
56 #include "BIF_gl.h"
57 #include "BIF_glutil.h"
58 //#include "BIF_editmesh.h"
59 //#include "BIF_editsima.h"
60 //#include "BIF_editparticle.h"
61 //#include "BIF_meshtools.h"
62
63 #include "BKE_animsys.h"
64 #include "BKE_action.h"
65 #include "BKE_armature.h"
66 #include "BKE_curve.h"
67 #include "BKE_depsgraph.h"
68 #include "BKE_displist.h"
69 #include "BKE_fcurve.h"
70 #include "BKE_lattice.h"
71 #include "BKE_mesh.h"
72 #include "BKE_nla.h"
73 #include "BKE_context.h"
74 #include "BKE_tracking.h"
75
76 #include "ED_anim_api.h"
77 #include "ED_armature.h"
78 #include "ED_image.h"
79 #include "ED_keyframing.h"
80 #include "ED_markers.h"
81 #include "ED_mesh.h"
82 #include "ED_particle.h"
83 #include "ED_screen_types.h"
84 #include "ED_space_api.h"
85 #include "ED_uvedit.h"
86 #include "ED_view3d.h"
87 #include "ED_curve.h" /* for curve_editnurbs */
88 #include "ED_clip.h"
89
90 //#include "BDR_unwrapper.h"
91
92 #include "BLI_math.h"
93 #include "BLI_blenlib.h"
94 #include "BLI_editVert.h"
95 #include "BLI_rand.h"
96 #include "BLI_utildefines.h"
97
98 #include "WM_types.h"
99 #include "WM_api.h"
100
101 #include "UI_resources.h"
102
103 //#include "blendef.h"
104 //
105 //#include "mydevice.h"
106
107 #include "transform.h"
108
109 extern ListBase editelems;
110
111 /* ************************** Functions *************************** */
112
113 void getViewVector(TransInfo *t, float coord[3], float vec[3])
114 {
115         if (t->persp != RV3D_ORTHO)
116         {
117                 float p1[4], p2[4];
118                 
119                 copy_v3_v3(p1, coord);
120                 p1[3] = 1.0f;
121                 copy_v3_v3(p2, p1);
122                 p2[3] = 1.0f;
123                 mul_m4_v4(t->viewmat, p2);
124                 
125                 p2[0] = 2.0f * p2[0];
126                 p2[1] = 2.0f * p2[1];
127                 p2[2] = 2.0f * p2[2];
128                 
129                 mul_m4_v4(t->viewinv, p2);
130                 
131                 sub_v3_v3v3(vec, p1, p2);
132         }
133         else {
134                 copy_v3_v3(vec, t->viewinv[2]);
135         }
136         normalize_v3(vec);
137 }
138
139 /* ************************** GENERICS **************************** */
140
141 static void clipMirrorModifier(TransInfo *t, Object *ob)
142 {
143         ModifierData *md= ob->modifiers.first;
144         float tolerance[3] = {0.0f, 0.0f, 0.0f};
145         int axis = 0;
146         
147         for (; md; md=md->next) {
148                 if ((md->type==eModifierType_Mirror) && (md->mode & eModifierMode_Realtime)) {
149                         MirrorModifierData *mmd = (MirrorModifierData*) md;
150                         
151                         if(mmd->flag & MOD_MIR_CLIPPING) {
152                                 axis = 0;
153                                 if(mmd->flag & MOD_MIR_AXIS_X) {
154                                         axis |= 1;
155                                         tolerance[0] = mmd->tolerance;
156                                 }
157                                 if(mmd->flag & MOD_MIR_AXIS_Y) {
158                                         axis |= 2;
159                                         tolerance[1] = mmd->tolerance;
160                                 }
161                                 if(mmd->flag & MOD_MIR_AXIS_Z) {
162                                         axis |= 4;
163                                         tolerance[2] = mmd->tolerance;
164                                 }
165                                 if (axis) {
166                                         float mtx[4][4], imtx[4][4];
167                                         int i;
168                                         TransData *td = t->data;
169                                         
170                                         if (mmd->mirror_ob) {
171                                                 float obinv[4][4];
172                                                 
173                                                 invert_m4_m4(obinv, mmd->mirror_ob->obmat);
174                                                 mul_m4_m4m4(mtx, ob->obmat, obinv);
175                                                 invert_m4_m4(imtx, mtx);
176                                         }
177                                         
178                                         for(i = 0 ; i < t->total; i++, td++) {
179                                                 int clip;
180                                                 float loc[3], iloc[3];
181                                                 
182                                                 if (td->flag & TD_NOACTION)
183                                                         break;
184                                                 if (td->loc==NULL)
185                                                         break;
186                                                 
187                                                 if (td->flag & TD_SKIP)
188                                                         continue;
189                                                 
190                                                 copy_v3_v3(loc,  td->loc);
191                                                 copy_v3_v3(iloc, td->iloc);
192                                                 
193                                                 if (mmd->mirror_ob) {
194                                                         mul_m4_v3(mtx, loc);
195                                                         mul_m4_v3(mtx, iloc);
196                                                 }
197                                                 
198                                                 clip = 0;
199                                                 if(axis & 1) {
200                                                         if(fabs(iloc[0])<=tolerance[0] ||
201                                                            loc[0]*iloc[0]<0.0f) {
202                                                                 loc[0]= 0.0f;
203                                                                 clip = 1;
204                                                         }
205                                                 }
206                                                 
207                                                 if(axis & 2) {
208                                                         if(fabs(iloc[1])<=tolerance[1] ||
209                                                            loc[1]*iloc[1]<0.0f) {
210                                                                 loc[1]= 0.0f;
211                                                                 clip = 1;
212                                                         }
213                                                 }
214                                                 if(axis & 4) {
215                                                         if(fabs(iloc[2])<=tolerance[2] ||
216                                                            loc[2]*iloc[2]<0.0f) {
217                                                                 loc[2]= 0.0f;
218                                                                 clip = 1;
219                                                         }
220                                                 }
221                                                 if (clip) {
222                                                         if (mmd->mirror_ob) {
223                                                                 mul_m4_v3(imtx, loc);
224                                                         }
225                                                         copy_v3_v3(td->loc, loc);
226                                                 }
227                                         }
228                                 }
229                                 
230                         }
231                 }
232         }
233 }
234
235 /* assumes obedit set to mesh object */
236 static void editmesh_apply_to_mirror(TransInfo *t)
237 {
238         TransData *td = t->data;
239         EditVert *eve;
240         int i;
241         
242         for(i = 0 ; i < t->total; i++, td++) {
243                 if (td->flag & TD_NOACTION)
244                         break;
245                 if (td->loc==NULL)
246                         break;
247                 if (td->flag & TD_SKIP)
248                         continue;
249                 
250                 eve = td->extra;
251                 if (eve) {
252                         eve->co[0]= -td->loc[0];
253                         eve->co[1]= td->loc[1];
254                         eve->co[2]= td->loc[2];
255                 }
256                 
257                 if (td->flag & TD_MIRROR_EDGE)
258                 {
259                         td->loc[0] = 0;
260                 }
261         }
262 }
263
264 /* for the realtime animation recording feature, handle overlapping data */
265 static void animrecord_check_state (Scene *scene, ID *id, wmTimer *animtimer)
266 {
267         ScreenAnimData *sad= (animtimer) ? animtimer->customdata : NULL;
268         
269         /* sanity checks */
270         if ELEM3(NULL, scene, id, sad)
271                 return;
272         
273         /* check if we need a new strip if:
274          *      - if animtimer is running 
275          *      - we're not only keying for available channels
276          *      - the option to add new actions for each round is not enabled
277          */
278         if (IS_AUTOKEY_FLAG(scene, INSERTAVAIL)==0 && (scene->toolsettings->autokey_flag & ANIMRECORD_FLAG_WITHNLA)) {
279                 /* if playback has just looped around, we need to add a new NLA track+strip to allow a clean pass to occur */
280                 if ((sad) && (sad->flag & ANIMPLAY_FLAG_JUMPED)) {
281                         AnimData *adt= BKE_animdata_from_id(id);
282                         
283                         /* perform push-down manually with some differences 
284                          * NOTE: BKE_nla_action_pushdown() sync warning...
285                          */
286                         if ((adt->action) && !(adt->flag & ADT_NLA_EDIT_ON)) {
287                                 float astart, aend;
288                                 
289                                 /* only push down if action is more than 1-2 frames long */
290                                 calc_action_range(adt->action, &astart, &aend, 1);
291                                 if (aend > astart+2.0f) {
292                                         NlaStrip *strip= add_nlastrip_to_stack(adt, adt->action);
293                                         
294                                         /* clear reference to action now that we've pushed it onto the stack */
295                                         adt->action->id.us--;
296                                         adt->action= NULL;
297                                         
298                                         /* adjust blending + extend so that they will behave correctly */
299                                         strip->extendmode= NLASTRIP_EXTEND_NOTHING;
300                                         strip->flag &= ~(NLASTRIP_FLAG_AUTO_BLENDS|NLASTRIP_FLAG_SELECT|NLASTRIP_FLAG_ACTIVE);
301                                         
302                                         /* also, adjust the AnimData's action extend mode to be on 
303                                          * 'nothing' so that previous result still play 
304                                          */
305                                         adt->act_extendmode= NLASTRIP_EXTEND_NOTHING;
306                                 }
307                         }
308                 }
309         }
310 }
311
312 static int fcu_test_selected(FCurve *fcu)
313 {
314         BezTriple *bezt= fcu->bezt;
315         unsigned int i;
316
317         if (bezt==NULL) /* ignore baked */
318                 return 0;
319
320         for (i=0; i < fcu->totvert; i++, bezt++) {
321                 if (BEZSELECTED(bezt)) return 1;
322         }
323
324         return 0;
325 }
326
327 /* helper for recalcData() - for Action Editor transforms */
328 static void recalcData_actedit(TransInfo *t)
329 {
330         Scene *scene= t->scene;
331         SpaceAction *saction= (SpaceAction *)t->sa->spacedata.first;
332         
333         bAnimContext ac= {NULL};
334         ListBase anim_data = {NULL, NULL};
335         bAnimListElem *ale;
336         int filter;
337         
338         /* initialise relevant anim-context 'context' data from TransInfo data */
339                 /* NOTE: sync this with the code in ANIM_animdata_get_context() */
340         ac.scene= t->scene;
341         ac.obact= OBACT;
342         ac.sa= t->sa;
343         ac.ar= t->ar;
344         ac.sl= (t->sa)? t->sa->spacedata.first : NULL;
345         ac.spacetype= (t->sa)? t->sa->spacetype : 0;
346         ac.regiontype= (t->ar)? t->ar->regiontype : 0;
347         
348         ANIM_animdata_context_getdata(&ac);
349         
350         /* perform flush */
351         if (ac.datatype == ANIMCONT_GPENCIL) {
352                 /* flush transform values back to actual coordinates */
353                 flushTransGPactionData(t);
354         }
355         else {
356                 /* get animdata blocks visible in editor, assuming that these will be the ones where things changed */
357                 filter= (ANIMFILTER_DATA_VISIBLE | ANIMFILTER_ANIMDATA);
358                 ANIM_animdata_filter(&ac, &anim_data, filter, ac.data, ac.datatype);
359                 
360                 /* just tag these animdata-blocks to recalc, assuming that some data there changed 
361                  * BUT only do this if realtime updates are enabled
362                  */
363                 if ((saction->flag & SACTION_NOREALTIMEUPDATES) == 0) {
364                         for (ale= anim_data.first; ale; ale= ale->next) {
365                                 /* set refresh tags for objects using this animation */
366                                 ANIM_list_elem_update(t->scene, ale);
367                         }
368                 }
369                 
370                 /* now free temp channels */
371                 BLI_freelistN(&anim_data);
372         }
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         /* initialise 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 cancelling 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 neighbouring 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 neighbours, 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((tdn->h1[0]/secf) + 0.5f) * secf );
546                                         tdn->h2[0]= (float)( floor((tdn->h2[0]/secf) + 0.5f) * secf );
547                                 }
548                                 else {
549                                         tdn->h1[0]= (float)( floor(tdn->h1[0]+0.5f) );
550                                         tdn->h2[0]= (float)( floor(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 3d-view transforms */
623 static void recalcData_view3d(TransInfo *t)
624 {
625         Base *base = t->scene->basact;
626         
627         if (t->obedit) {
628                 if ELEM(t->obedit->type, OB_CURVE, OB_SURF) {
629                         Curve *cu= t->obedit->data;
630                         ListBase *nurbs= curve_editnurbs(cu);
631                         Nurb *nu= nurbs->first;
632                         
633                         if(t->state != TRANS_CANCEL) {
634                                 clipMirrorModifier(t, t->obedit);
635                                 applyProject(t);
636                         }
637                         
638                         DAG_id_tag_update(t->obedit->data, 0);  /* sets recalc flags */
639                                 
640                         if (t->state == TRANS_CANCEL) {
641                                 while(nu) {
642                                         calchandlesNurb(nu); /* Cant do testhandlesNurb here, it messes up the h1 and h2 flags */
643                                         nu= nu->next;
644                                 }
645                         } 
646                         else {
647                                 /* Normal updating */
648                                 while(nu) {
649                                         test2DNurb(nu);
650                                         calchandlesNurb(nu);
651                                         nu= nu->next;
652                                 }
653                         }
654                 }
655                 else if(t->obedit->type==OB_LATTICE) {
656                         Lattice *la= t->obedit->data;
657                         
658                         if(t->state != TRANS_CANCEL) {
659                                 applyProject(t);
660                         }
661                         
662                         DAG_id_tag_update(t->obedit->data, 0);  /* sets recalc flags */
663                         
664                         if(la->editlatt->latt->flag & LT_OUTSIDE) outside_lattice(la->editlatt->latt);
665                 }
666                 else if (t->obedit->type == OB_MESH) {
667                         EditMesh *em = ((Mesh*)t->obedit->data)->edit_mesh;
668                         /* mirror modifier clipping? */
669                         if(t->state != TRANS_CANCEL) {
670                                 /* apply clipping after so we never project past the clip plane [#25423] */
671                                 applyProject(t);
672                                 clipMirrorModifier(t, t->obedit);
673                         }
674                         if((t->options & CTX_NO_MIRROR) == 0 && (t->flag & T_MIRROR))
675                                 editmesh_apply_to_mirror(t);
676                                 
677                         DAG_id_tag_update(t->obedit->data, 0);  /* sets recalc flags */
678                         
679                         recalc_editnormals(em);
680                 }
681                 else if(t->obedit->type==OB_ARMATURE) { /* no recalc flag, does pose */
682                         bArmature *arm= t->obedit->data;
683                         ListBase *edbo = arm->edbo;
684                         EditBone *ebo;
685                         TransData *td = t->data;
686                         int i;
687                         
688                         if(t->state != TRANS_CANCEL) {
689                                 applyProject(t);
690                         }
691                         
692                         /* Ensure all bones are correctly adjusted */
693                         for (ebo = edbo->first; ebo; ebo = ebo->next){
694                                 
695                                 if ((ebo->flag & BONE_CONNECTED) && ebo->parent){
696                                         /* If this bone has a parent tip that has been moved */
697                                         if (ebo->parent->flag & BONE_TIPSEL){
698                                                 copy_v3_v3 (ebo->head, ebo->parent->tail);
699                                                 if(t->mode==TFM_BONE_ENVELOPE) ebo->rad_head= ebo->parent->rad_tail;
700                                         }
701                                         /* If this bone has a parent tip that has NOT been moved */
702                                         else{
703                                                 copy_v3_v3 (ebo->parent->tail, ebo->head);
704                                                 if(t->mode==TFM_BONE_ENVELOPE) ebo->parent->rad_tail= ebo->rad_head;
705                                         }
706                                 }
707                                 
708                                 /* on extrude bones, oldlength==0.0f, so we scale radius of points */
709                                 ebo->length= len_v3v3(ebo->head, ebo->tail);
710                                 if(ebo->oldlength==0.0f) {
711                                         ebo->rad_head= 0.25f*ebo->length;
712                                         ebo->rad_tail= 0.10f*ebo->length;
713                                         ebo->dist= 0.25f*ebo->length;
714                                         if(ebo->parent) {
715                                                 if(ebo->rad_head > ebo->parent->rad_tail)
716                                                         ebo->rad_head= ebo->parent->rad_tail;
717                                         }
718                                 }
719                                 else if(t->mode!=TFM_BONE_ENVELOPE) {
720                                         /* if bones change length, lets do that for the deform distance as well */
721                                         ebo->dist*= ebo->length/ebo->oldlength;
722                                         ebo->rad_head*= ebo->length/ebo->oldlength;
723                                         ebo->rad_tail*= ebo->length/ebo->oldlength;
724                                         ebo->oldlength= ebo->length;
725                                 }
726                         }
727                         
728                         
729                         if (t->mode != TFM_BONE_ROLL)
730                         {
731                                 /* fix roll */
732                                 for(i = 0; i < t->total; i++, td++)
733                                 {
734                                         if (td->extra)
735                                         {
736                                                 float vec[3], up_axis[3];
737                                                 float qrot[4];
738                                                 
739                                                 ebo = td->extra;
740                                                 copy_v3_v3(up_axis, td->axismtx[2]);
741                                                 
742                                                 if (t->mode != TFM_ROTATION)
743                                                 {
744                                                         sub_v3_v3v3(vec, ebo->tail, ebo->head);
745                                                         normalize_v3(vec);
746                                                         rotation_between_vecs_to_quat(qrot, td->axismtx[1], vec);
747                                                         mul_qt_v3(qrot, up_axis);
748                                                 }
749                                                 else
750                                                 {
751                                                         mul_m3_v3(t->mat, up_axis);
752                                                 }
753                                                 
754                                                 ebo->roll = ED_rollBoneToVector(ebo, up_axis, FALSE);
755                                         }
756                                 }
757                         }
758                         
759                         if(arm->flag & ARM_MIRROR_EDIT)
760                                 transform_armature_mirror_update(t->obedit);
761                         
762                 }
763                 else
764                 {
765                         if(t->state != TRANS_CANCEL) {
766                                 applyProject(t);
767                         }
768                         DAG_id_tag_update(t->obedit->data, 0);  /* sets recalc flags */
769                 }
770         }
771         else if( (t->flag & T_POSE) && t->poseobj) {
772                 Object *ob= t->poseobj;
773                 bArmature *arm= ob->data;
774                 
775                 /* if animtimer is running, and the object already has animation data,
776                  * check if the auto-record feature means that we should record 'samples'
777                  * (i.e. uneditable animation values)
778                  *
779                  * context is needed for keying set poll() functions.
780                  */
781                 // TODO: autokeyframe calls need some setting to specify to add samples (FPoints) instead of keyframes?
782                 if ((t->animtimer) && (t->context) && IS_AUTOKEY_ON(t->scene)) {
783                         int targetless_ik= (t->flag & T_AUTOIK); // XXX this currently doesn't work, since flags aren't set yet!
784                         
785                         animrecord_check_state(t->scene, &ob->id, t->animtimer);
786                         autokeyframe_pose_cb_func(t->context, t->scene, (View3D *)t->view, ob, t->mode, targetless_ik);
787                 }
788                 
789                 /* old optimize trick... this enforces to bypass the depgraph */
790                 if (!(arm->flag & ARM_DELAYDEFORM)) {
791                         DAG_id_tag_update(&ob->id, OB_RECALC_DATA);  /* sets recalc flags */
792                 }
793                 else
794                         where_is_pose(t->scene, ob);
795         }
796         else if(base && (base->object->mode & OB_MODE_PARTICLE_EDIT) && PE_get_current(t->scene, base->object)) {
797                 if(t->state != TRANS_CANCEL) {
798                         applyProject(t);
799                 }
800                 flushTransParticles(t);
801         }
802         else {
803                 int i;
804                 
805                 if(t->state != TRANS_CANCEL) {
806                         applyProject(t);
807                 }
808                 
809                 for (i = 0; i < t->total; i++) {
810                         TransData *td = t->data + i;
811                         Object *ob = td->ob;
812                         
813                         if (td->flag & TD_NOACTION)
814                                 break;
815                         
816                         if (td->flag & TD_SKIP)
817                                 continue;
818                         
819                         /* if animtimer is running, and the object already has animation data,
820                          * check if the auto-record feature means that we should record 'samples'
821                          * (i.e. uneditable animation values)
822                          */
823                         // TODO: autokeyframe calls need some setting to specify to add samples (FPoints) instead of keyframes?
824                         if ((t->animtimer) && IS_AUTOKEY_ON(t->scene)) {
825                                 animrecord_check_state(t->scene, &ob->id, t->animtimer);
826                                 autokeyframe_ob_cb_func(t->context, t->scene, (View3D *)t->view, ob, t->mode);
827                         }
828                         
829                         /* sets recalc flags fully, instead of flushing existing ones 
830                          * otherwise proxies don't function correctly
831                          */
832                         DAG_id_tag_update(&ob->id, OB_RECALC_OB);
833                 }
834         }
835 }
836
837 /* called for updating while transform acts, once per redraw */
838 void recalcData(TransInfo *t)
839 {
840         if (t->spacetype==SPACE_NODE) {
841                 flushTransNodes(t);
842         }
843         else if (t->spacetype==SPACE_SEQ) {
844                 flushTransSeq(t);
845         }
846         else if (t->spacetype == SPACE_ACTION) {
847                 recalcData_actedit(t);
848         }
849         else if (t->spacetype == SPACE_IPO) {
850                 recalcData_graphedit(t);
851         }
852         else if (t->spacetype == SPACE_NLA) {
853                 recalcData_nla(t);
854         }
855         else if (t->spacetype == SPACE_IMAGE) {
856                 if (t->obedit && t->obedit->type == OB_MESH) {
857                         SpaceImage *sima= t->sa->spacedata.first;
858                         
859                         flushTransUVs(t);
860                         if(sima->flag & SI_LIVE_UNWRAP)
861                                 ED_uvedit_live_unwrap_re_solve();
862                         
863                         DAG_id_tag_update(t->obedit->data, 0);
864                 }
865         }
866         else if (t->spacetype == SPACE_VIEW3D) {
867                 recalcData_view3d(t);
868         }
869         else if (t->spacetype == SPACE_CLIP) {
870                 SpaceClip *sc= t->sa->spacedata.first;
871                 MovieClip *clip= ED_space_clip(sc);
872                 MovieTrackingTrack *track;
873
874                 if(t->state == TRANS_CANCEL) {
875                         track= clip->tracking.tracks.first;
876                         while(track) {
877                                 if(TRACK_VIEW_SELECTED(sc, track)) {
878                                         MovieTrackingMarker *marker= BKE_tracking_ensure_marker(track, sc->user.framenr);
879
880                                         marker->flag= track->transflag;
881                                 }
882
883                                 track= track->next;
884                         }
885                 }
886
887                 flushTransTracking(t);
888
889                 track= clip->tracking.tracks.first;
890                 while(track) {
891                         if(TRACK_VIEW_SELECTED(sc, track)) {
892                                 if (t->mode == TFM_TRANSLATION) {
893                                         if(TRACK_AREA_SELECTED(track, TRACK_AREA_PAT))
894                                                 BKE_tracking_clamp_track(track, CLAMP_PAT_POS);
895                                         if(TRACK_AREA_SELECTED(track, TRACK_AREA_SEARCH))
896                                                 BKE_tracking_clamp_track(track, CLAMP_SEARCH_POS);
897                                 }
898                                 else if (t->mode == TFM_RESIZE) {
899                                         if(TRACK_AREA_SELECTED(track, TRACK_AREA_PAT))
900                                                 BKE_tracking_clamp_track(track, CLAMP_PAT_DIM);
901                                         if(TRACK_AREA_SELECTED(track, TRACK_AREA_SEARCH))
902                                                 BKE_tracking_clamp_track(track, CLAMP_SEARCH_DIM);
903                                 }
904                         }
905
906                         track= track->next;
907                 }
908
909                 DAG_id_tag_update(&clip->id, 0);
910         }
911 }
912
913 void drawLine(TransInfo *t, float *center, float *dir, char axis, short options)
914 {
915         float v1[3], v2[3], v3[3];
916         unsigned char col[3], col2[3];
917
918         if (t->spacetype == SPACE_VIEW3D)
919         {
920                 View3D *v3d = t->view;
921                 
922                 glPushMatrix();
923                 
924                 //if(t->obedit) glLoadMatrixf(t->obedit->obmat);        // sets opengl viewing
925                 
926                 
927                 copy_v3_v3(v3, dir);
928                 mul_v3_fl(v3, v3d->far);
929                 
930                 sub_v3_v3v3(v2, center, v3);
931                 add_v3_v3v3(v1, center, v3);
932                 
933                 if (options & DRAWLIGHT) {
934                         col[0] = col[1] = col[2] = 220;
935                 }
936                 else {
937                         UI_GetThemeColor3ubv(TH_GRID, col);
938                 }
939                 UI_make_axis_color(col, col2, axis);
940                 glColor3ubv(col2);
941                 
942                 setlinestyle(0);
943                 glBegin(GL_LINE_STRIP);
944                         glVertex3fv(v1);
945                         glVertex3fv(v2);
946                 glEnd();
947                 
948                 glPopMatrix();
949         }
950 }
951
952 void resetTransRestrictions(TransInfo *t)
953 {
954         t->flag &= ~T_ALL_RESTRICTIONS;
955 }
956
957 /* the *op can be NULL */
958 int initTransInfo (bContext *C, TransInfo *t, wmOperator *op, wmEvent *event)
959 {
960         Scene *sce = CTX_data_scene(C);
961         ToolSettings *ts = CTX_data_tool_settings(C);
962         ARegion *ar = CTX_wm_region(C);
963         ScrArea *sa = CTX_wm_area(C);
964         Object *obedit = CTX_data_edit_object(C);
965         
966         /* moving: is shown in drawobject() (transform color) */
967 //  TRANSFORM_FIX_ME
968 //      if(obedit || (t->flag & T_POSE) ) G.moving= G_TRANSFORM_EDIT;
969 //      else if(G.f & G_PARTICLEEDIT) G.moving= G_TRANSFORM_PARTICLE;
970 //      else G.moving= G_TRANSFORM_OBJ;
971         
972         t->scene = sce;
973         t->sa = sa;
974         t->ar = ar;
975         t->obedit = obedit;
976         t->settings = ts;
977         
978         t->data = NULL;
979         t->ext = NULL;
980         
981         t->helpline = HLP_NONE;
982         
983         t->flag = 0;
984         
985         t->redraw = 1; /* redraw first time */
986         
987         if (event)
988         {
989                 VECCOPY2D(t->imval, event->mval);
990                 t->event_type = event->type;
991         }
992         else
993         {
994                 t->imval[0] = 0;
995                 t->imval[1] = 0;
996         }
997         
998         t->con.imval[0] = t->imval[0];
999         t->con.imval[1] = t->imval[1];
1000         
1001         t->mval[0] = t->imval[0];
1002         t->mval[1] = t->imval[1];
1003         
1004         t->transform            = NULL;
1005         t->handleEvent          = NULL;
1006         
1007         t->total                        = 0;
1008         
1009         t->val = 0.0f;
1010         
1011         t->vec[0]                       =
1012                 t->vec[1]               =
1013                 t->vec[2]               = 0.0f;
1014         
1015         t->center[0]            =
1016                 t->center[1]    =
1017                 t->center[2]    = 0.0f;
1018         
1019         unit_m3(t->mat);
1020         
1021         /* if there's an event, we're modal */
1022         if (event) {
1023                 t->flag |= T_MODAL;
1024         }
1025
1026         /* Crease needs edge flag */
1027         if (t->mode == TFM_CREASE) {
1028                 t->options |= CTX_EDGE;
1029         }
1030
1031
1032         /* Assign the space type, some exceptions for running in different mode */
1033         if(sa == NULL) {
1034                 /* background mode */
1035                 t->spacetype= SPACE_EMPTY;
1036         }
1037         else if ((ar == NULL) && (sa->spacetype == SPACE_VIEW3D)) {
1038                 /* running in the text editor */
1039                 t->spacetype= SPACE_EMPTY;
1040         }
1041         else {
1042                 /* normal operation */
1043                 t->spacetype= sa->spacetype;
1044         }
1045
1046
1047         if(t->spacetype == SPACE_VIEW3D)
1048         {
1049                 View3D *v3d = sa->spacedata.first;
1050                 
1051                 t->view = v3d;
1052                 t->animtimer= CTX_wm_screen(C)->animtimer;
1053                 
1054                 /* turn manipulator off during transform */
1055                 // FIXME: but don't do this when USING the manipulator...
1056                 if (t->flag & T_MODAL) {
1057                         t->twtype = v3d->twtype;
1058                         v3d->twtype = 0;
1059                 }
1060
1061                 if(v3d->flag & V3D_ALIGN) t->flag |= T_V3D_ALIGN;
1062                 t->around = v3d->around;
1063                 
1064                 if (op && RNA_struct_find_property(op->ptr, "constraint_orientation") && RNA_property_is_set(op->ptr, "constraint_orientation"))
1065                 {
1066                         t->current_orientation = RNA_enum_get(op->ptr, "constraint_orientation");
1067                         
1068                         if (t->current_orientation >= V3D_MANIP_CUSTOM + BIF_countTransformOrientation(C))
1069                         {
1070                                 t->current_orientation = V3D_MANIP_GLOBAL;
1071                         }
1072                 }
1073                 else
1074                 {
1075                         t->current_orientation = v3d->twmode;
1076                 }
1077
1078                 /* exceptional case */
1079                 if(t->around==V3D_LOCAL && (t->settings->selectmode & SCE_SELECT_FACE)) {
1080                         if(ELEM3(t->mode, TFM_ROTATION, TFM_RESIZE, TFM_TRACKBALL)) {
1081                                 t->options |= CTX_NO_PET;
1082                         }
1083                 }
1084
1085                 /* initialize UV transform from */
1086                 if (op && RNA_struct_find_property(op->ptr, "correct_uv")) {
1087                         if(RNA_property_is_set(op->ptr, "correct_uv")) {
1088                                 if(RNA_boolean_get(op->ptr, "correct_uv")) {
1089                                         t->settings->uvcalc_flag |= UVCALC_TRANSFORM_CORRECT;
1090                                 }
1091                                 else {
1092                                         t->settings->uvcalc_flag &= ~UVCALC_TRANSFORM_CORRECT;
1093                                 }
1094                         }
1095                         else {
1096                                 RNA_boolean_set(op->ptr, "correct_uv", t->settings->uvcalc_flag & UVCALC_TRANSFORM_CORRECT);
1097                         }
1098                 }
1099
1100         }
1101         else if(t->spacetype==SPACE_IMAGE)
1102         {
1103                 SpaceImage *sima = sa->spacedata.first;
1104                 // XXX for now, get View2D from the active region
1105                 t->view = &ar->v2d;
1106                 t->around = sima->around;
1107         }
1108         else if(t->spacetype==SPACE_NODE)
1109         {
1110                 // XXX for now, get View2D from the active region
1111                 t->view = &ar->v2d;
1112                 t->around = V3D_CENTER;
1113         }
1114         else if(t->spacetype==SPACE_IPO) 
1115         {
1116                 SpaceIpo *sipo= sa->spacedata.first;
1117                 t->view = &ar->v2d;
1118                 t->around = sipo->around;
1119         }
1120         else
1121         {
1122                 if(ar) {
1123                         // XXX for now, get View2D  from the active region
1124                         t->view = &ar->v2d;
1125                         // XXX for now, the center point is the midpoint of the data
1126                 }
1127                 else {
1128                         t->view= NULL;
1129                 }
1130                 t->around = V3D_CENTER;
1131         }
1132         
1133         if (op && RNA_property_is_set(op->ptr, "release_confirm"))
1134         {
1135                 if (RNA_boolean_get(op->ptr, "release_confirm"))
1136                 {
1137                         t->flag |= T_RELEASE_CONFIRM;
1138                 }
1139         }
1140         else
1141         {
1142                 if (U.flag & USER_RELEASECONFIRM)
1143                 {
1144                         t->flag |= T_RELEASE_CONFIRM;
1145                 }
1146         }
1147
1148         if (op && RNA_struct_find_property(op->ptr, "mirror") && RNA_property_is_set(op->ptr, "mirror"))
1149         {
1150                 if (RNA_boolean_get(op->ptr, "mirror"))
1151                 {
1152                         t->flag |= T_MIRROR;
1153                         t->mirror = 1;
1154                 }
1155         }
1156         // Need stuff to take it from edit mesh or whatnot here
1157         else if (t->spacetype == SPACE_VIEW3D)
1158         {
1159                 if (t->obedit && t->obedit->type == OB_MESH && (((Mesh *)t->obedit->data)->editflag & ME_EDIT_MIRROR_X))
1160                 {
1161                         t->flag |= T_MIRROR;
1162                         t->mirror = 1;
1163                 }
1164         }
1165         
1166         /* setting PET flag only if property exist in operator. Otherwise, assume it's not supported */
1167         if (op && RNA_struct_find_property(op->ptr, "proportional"))
1168         {
1169                 if (RNA_property_is_set(op->ptr, "proportional"))
1170                 {
1171                         switch(RNA_enum_get(op->ptr, "proportional"))
1172                         {
1173                         case PROP_EDIT_CONNECTED:
1174                                 t->flag |= T_PROP_CONNECTED;
1175                         case PROP_EDIT_ON:
1176                                 t->flag |= T_PROP_EDIT;
1177                                 break;
1178                         }
1179                 }
1180                 else
1181                 {
1182                         /* use settings from scene only if modal */
1183                         if (t->flag & T_MODAL)
1184                         {
1185                                 if ((t->options & CTX_NO_PET) == 0)
1186                                 {
1187                                         if (t->obedit && ts->proportional != PROP_EDIT_OFF)
1188                                         {
1189                                                 t->flag |= T_PROP_EDIT;
1190
1191                                                 if(ts->proportional == PROP_EDIT_CONNECTED)
1192                                                         t->flag |= T_PROP_CONNECTED;
1193                                         }
1194                                         else if (t->obedit == NULL && ts->proportional_objects)
1195                                         {
1196                                                 t->flag |= T_PROP_EDIT;
1197                                         }
1198                                 }
1199                         }
1200                 }
1201                 
1202                 if (op && RNA_struct_find_property(op->ptr, "proportional_size") && RNA_property_is_set(op->ptr, "proportional_size"))
1203                 {
1204                         t->prop_size = RNA_float_get(op->ptr, "proportional_size");
1205                 }
1206                 else
1207                 {
1208                         t->prop_size = ts->proportional_size;
1209                 }
1210                 
1211                 
1212                 /* TRANSFORM_FIX_ME rna restrictions */
1213                 if (t->prop_size <= 0.00001f)
1214                 {
1215                         printf("Proportional size (%f) under 0.00001, reseting to 1!\n", t->prop_size);
1216                         t->prop_size = 1.0f;
1217                 }
1218                 
1219                 if (op && RNA_struct_find_property(op->ptr, "proportional_edit_falloff") && RNA_property_is_set(op->ptr, "proportional_edit_falloff"))
1220                 {
1221                         t->prop_mode = RNA_enum_get(op->ptr, "proportional_edit_falloff");
1222                 }
1223                 else
1224                 {
1225                         t->prop_mode = ts->prop_mode;
1226                 }
1227         }
1228         else /* add not pet option to context when not available */
1229         {
1230                 t->options |= CTX_NO_PET;
1231         }
1232         
1233         // Mirror is not supported with PET, turn it off.
1234         if (t->flag & T_PROP_EDIT)
1235         {
1236                 t->flag &= ~T_MIRROR;
1237         }
1238
1239         setTransformViewMatrices(t);
1240         initNumInput(&t->num);
1241         
1242         return 1;
1243 }
1244
1245 /* Here I would suggest only TransInfo related issues, like free data & reset vars. Not redraws */
1246 void postTrans (bContext *C, TransInfo *t)
1247 {
1248         TransData *td;
1249         
1250         if (t->draw_handle_view)
1251                 ED_region_draw_cb_exit(t->ar->type, t->draw_handle_view);
1252         if (t->draw_handle_apply)
1253                 ED_region_draw_cb_exit(t->ar->type, t->draw_handle_apply);
1254         if (t->draw_handle_pixel)
1255                 ED_region_draw_cb_exit(t->ar->type, t->draw_handle_pixel);
1256         if (t->draw_handle_cursor)
1257                 WM_paint_cursor_end(CTX_wm_manager(C), t->draw_handle_cursor);
1258
1259         if (t->customFree) {
1260                 /* Can take over freeing t->data and data2d etc... */
1261                 t->customFree(t);
1262         }
1263         else if (t->customData) {
1264                 MEM_freeN(t->customData);
1265         }
1266
1267         /* postTrans can be called when nothing is selected, so data is NULL already */
1268         if (t->data) {
1269                 int a;
1270                 
1271                 /* free data malloced per trans-data */
1272                 for(a=0, td= t->data; a<t->total; a++, td++) {
1273                         if (td->flag & TD_BEZTRIPLE) 
1274                                 MEM_freeN(td->hdata);
1275                 }
1276                 MEM_freeN(t->data);
1277         }
1278         
1279         BLI_freelistN(&t->tsnap.points);
1280
1281         if (t->ext) MEM_freeN(t->ext);
1282         if (t->data2d) {
1283                 MEM_freeN(t->data2d);
1284                 t->data2d= NULL;
1285         }
1286         
1287         if(t->spacetype==SPACE_IMAGE) {
1288                 SpaceImage *sima= t->sa->spacedata.first;
1289                 if(sima->flag & SI_LIVE_UNWRAP)
1290                         ED_uvedit_live_unwrap_end(t->state == TRANS_CANCEL);
1291         }
1292         else if(t->spacetype==SPACE_VIEW3D) {
1293                 View3D *v3d = t->sa->spacedata.first;
1294                 /* restore manipulator */
1295                 if (t->flag & T_MODAL) {
1296                         v3d->twtype = t->twtype;
1297                 }
1298         }
1299         
1300         if (t->mouse.data)
1301         {
1302                 MEM_freeN(t->mouse.data);
1303         }
1304 }
1305
1306 void applyTransObjects(TransInfo *t)
1307 {
1308         TransData *td;
1309         
1310         for (td = t->data; td < t->data + t->total; td++) {
1311                 copy_v3_v3(td->iloc, td->loc);
1312                 if (td->ext->rot) {
1313                         copy_v3_v3(td->ext->irot, td->ext->rot);
1314                 }
1315                 if (td->ext->size) {
1316                         copy_v3_v3(td->ext->isize, td->ext->size);
1317                 }
1318         }
1319         recalcData(t);
1320 }
1321
1322 static void restoreElement(TransData *td)
1323 {
1324         /* TransData for crease has no loc */
1325         if (td->loc) {
1326                 copy_v3_v3(td->loc, td->iloc);
1327         }
1328         if (td->val) {
1329                 *td->val = td->ival;
1330         }
1331
1332         if (td->ext && (td->flag&TD_NO_EXT)==0) {
1333                 if (td->ext->rot) {
1334                         copy_v3_v3(td->ext->rot, td->ext->irot);
1335                 }
1336                 if(td->ext->rotAngle) {
1337                         *td->ext->rotAngle= td->ext->irotAngle;
1338                 }
1339                 if(td->ext->rotAxis) {
1340                         copy_v3_v3(td->ext->rotAxis, td->ext->irotAxis);
1341                 }
1342                 /* XXX, drotAngle & drotAxis not used yet */
1343                 if (td->ext->size) {
1344                         copy_v3_v3(td->ext->size, td->ext->isize);
1345                 }
1346                 if (td->ext->quat) {
1347                         copy_qt_qt(td->ext->quat, td->ext->iquat);
1348                 }
1349         }
1350         
1351         if (td->flag & TD_BEZTRIPLE) {
1352                 *(td->hdata->h1) = td->hdata->ih1;
1353                 *(td->hdata->h2) = td->hdata->ih2;
1354         }
1355 }
1356
1357 void restoreTransObjects(TransInfo *t)
1358 {
1359         TransData *td;
1360         TransData2D *td2d;
1361
1362         for (td = t->data; td < t->data + t->total; td++) {
1363                 restoreElement(td);
1364         }
1365         
1366         for (td2d=t->data2d; t->data2d && td2d < t->data2d + t->total; td2d++) {
1367                 if (td2d->h1) {
1368                         td2d->h1[0] = td2d->ih1[0];
1369                         td2d->h1[1] = td2d->ih1[1];
1370                 }
1371                 if (td2d->h2) {
1372                         td2d->h2[0] = td2d->ih2[0];
1373                         td2d->h2[1] = td2d->ih2[1];
1374                 }
1375         }
1376
1377         unit_m3(t->mat);
1378         
1379         recalcData(t);
1380 }
1381
1382 void calculateCenter2D(TransInfo *t)
1383 {
1384         if (t->flag & (T_EDIT|T_POSE)) {
1385                 Object *ob= t->obedit?t->obedit:t->poseobj;
1386                 float vec[3];
1387                 
1388                 copy_v3_v3(vec, t->center);
1389                 mul_m4_v3(ob->obmat, vec);
1390                 projectIntView(t, vec, t->center2d);
1391         }
1392         else {
1393                 projectIntView(t, t->center, t->center2d);
1394         }
1395 }
1396
1397 void calculateCenterCursor(TransInfo *t)
1398 {
1399         float *cursor;
1400         
1401         cursor = give_cursor(t->scene, t->view);
1402         copy_v3_v3(t->center, cursor);
1403         
1404         /* If edit or pose mode, move cursor in local space */
1405         if (t->flag & (T_EDIT|T_POSE)) {
1406                 Object *ob = t->obedit?t->obedit:t->poseobj;
1407                 float mat[3][3], imat[3][3];
1408                 
1409                 sub_v3_v3v3(t->center, t->center, ob->obmat[3]);
1410                 copy_m3_m4(mat, ob->obmat);
1411                 invert_m3_m3(imat, mat);
1412                 mul_m3_v3(imat, t->center);
1413         }
1414         
1415         calculateCenter2D(t);
1416 }
1417
1418 void calculateCenterCursor2D(TransInfo *t)
1419 {
1420         float aspx=1.0, aspy=1.0;
1421         float *cursor= NULL;
1422         
1423         if(t->spacetype==SPACE_IMAGE) {
1424                 SpaceImage *sima= (SpaceImage *)t->sa->spacedata.first;
1425                 /* only space supported right now but may change */
1426                 ED_space_image_uv_aspect(sima, &aspx, &aspy);
1427                 cursor = sima->cursor;
1428         }
1429         
1430         if (cursor) {
1431                 t->center[0] = cursor[0] * aspx;
1432                 t->center[1] = cursor[1] * aspy;
1433         }
1434         
1435         calculateCenter2D(t);
1436 }
1437
1438 static void calculateCenterCursorGraph2D(TransInfo *t)
1439 {
1440         SpaceIpo *sipo= (SpaceIpo *)t->sa->spacedata.first;
1441         Scene *scene= t->scene;
1442         
1443         /* cursor is combination of current frame, and graph-editor cursor value */
1444         t->center[0]= (float)(scene->r.cfra);
1445         t->center[1]= sipo->cursorVal;
1446         
1447         calculateCenter2D(t);
1448 }
1449
1450 void calculateCenterMedian(TransInfo *t)
1451 {
1452         float partial[3] = {0.0f, 0.0f, 0.0f};
1453         int total = 0;
1454         int i;
1455         
1456         for(i = 0; i < t->total; i++) {
1457                 if (t->data[i].flag & TD_SELECTED) {
1458                         if (!(t->data[i].flag & TD_NOCENTER))
1459                         {
1460                                 add_v3_v3(partial, t->data[i].center);
1461                                 total++;
1462                         }
1463                 }
1464                 else {
1465                         /*
1466                            All the selected elements are at the head of the array
1467                            which means we can stop when it finds unselected data
1468                         */
1469                         break;
1470                 }
1471         }
1472         if(i)
1473                 mul_v3_fl(partial, 1.0f / total);
1474         copy_v3_v3(t->center, partial);
1475         
1476         calculateCenter2D(t);
1477 }
1478
1479 void calculateCenterBound(TransInfo *t)
1480 {
1481         float max[3];
1482         float min[3];
1483         int i;
1484         for(i = 0; i < t->total; i++) {
1485                 if (i) {
1486                         if (t->data[i].flag & TD_SELECTED) {
1487                                 if (!(t->data[i].flag & TD_NOCENTER))
1488                                         minmax_v3v3_v3(min, max, t->data[i].center);
1489                         }
1490                         else {
1491                                 /*
1492                                    All the selected elements are at the head of the array
1493                                    which means we can stop when it finds unselected data
1494                                 */
1495                                 break;
1496                         }
1497                 }
1498                 else {
1499                         copy_v3_v3(max, t->data[i].center);
1500                         copy_v3_v3(min, t->data[i].center);
1501                 }
1502         }
1503         add_v3_v3v3(t->center, min, max);
1504         mul_v3_fl(t->center, 0.5);
1505         
1506         calculateCenter2D(t);
1507 }
1508
1509 void calculateCenter(TransInfo *t)
1510 {
1511         switch(t->around) {
1512         case V3D_CENTER:
1513                 calculateCenterBound(t);
1514                 break;
1515         case V3D_CENTROID:
1516                 calculateCenterMedian(t);
1517                 break;
1518         case V3D_CURSOR:
1519                 if(t->spacetype==SPACE_IMAGE)
1520                         calculateCenterCursor2D(t);
1521                 else if(t->spacetype==SPACE_IPO)
1522                         calculateCenterCursorGraph2D(t);
1523                 else
1524                         calculateCenterCursor(t);
1525                 break;
1526         case V3D_LOCAL:
1527                 /* Individual element center uses median center for helpline and such */
1528                 calculateCenterMedian(t);
1529                 break;
1530         case V3D_ACTIVE:
1531                 {
1532                 /* set median, and if if if... do object center */
1533                 
1534                 /* EDIT MODE ACTIVE EDITMODE ELEMENT */
1535
1536                 if (t->obedit && t->obedit->type == OB_MESH) {
1537                         EditSelection ese;
1538                         EditMesh *em = BKE_mesh_get_editmesh(t->obedit->data);
1539                         
1540                         if (EM_get_actSelection(em, &ese)) {
1541                                 EM_editselection_center(t->center, &ese);
1542                                 calculateCenter2D(t);
1543                                 break;
1544                         }
1545                 } /* END EDIT MODE ACTIVE ELEMENT */
1546                 
1547                 calculateCenterMedian(t);
1548                 if((t->flag & (T_EDIT|T_POSE))==0)
1549                 {
1550                         Scene *scene = t->scene;
1551                         Object *ob= OBACT;
1552                         if(ob)
1553                         {
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         {
1566                 Object *ob= t->obedit?t->obedit:t->poseobj;
1567                 mul_m4_v3(ob->obmat, t->con.center);
1568         }
1569         
1570         /* for panning from cameraview */
1571         if(t->flag & T_OBJECT)
1572         {
1573                 if(t->spacetype==SPACE_VIEW3D && t->ar && t->ar->regiontype == RGN_TYPE_WINDOW)
1574                 {
1575                         View3D *v3d = t->view;
1576                         Scene *scene = t->scene;
1577                         RegionView3D *rv3d = t->ar->regiondata;
1578                         
1579                         if(v3d->camera == OBACT && rv3d->persp==RV3D_CAMOB)
1580                         {
1581                                 float axis[3];
1582                                 /* persinv is nasty, use viewinv instead, always right */
1583                                 copy_v3_v3(axis, t->viewinv[2]);
1584                                 normalize_v3(axis);
1585                                 
1586                                 /* 6.0 = 6 grid units */
1587                                 axis[0]= t->center[0]- 6.0f*axis[0];
1588                                 axis[1]= t->center[1]- 6.0f*axis[1];
1589                                 axis[2]= t->center[2]- 6.0f*axis[2];
1590                                 
1591                                 projectIntView(t, axis, t->center2d);
1592                                 
1593                                 /* rotate only needs correct 2d center, grab needs initgrabz() value */
1594                                 if(t->mode==TFM_TRANSLATION)
1595                                 {
1596                                         copy_v3_v3(t->center, axis);
1597                                         copy_v3_v3(t->con.center, t->center);
1598                                 }
1599                         }
1600                 }
1601         }
1602         
1603         if(t->spacetype==SPACE_VIEW3D)
1604         {
1605                 /* initgrabz() defines a factor for perspective depth correction, used in window_to_3d_delta() */
1606                 if(t->flag & (T_EDIT|T_POSE)) {
1607                         Object *ob= t->obedit?t->obedit:t->poseobj;
1608                         float vec[3];
1609                         
1610                         copy_v3_v3(vec, t->center);
1611                         mul_m4_v3(ob->obmat, vec);
1612                         initgrabz(t->ar->regiondata, vec[0], vec[1], vec[2]);
1613                 }
1614                 else {
1615                         initgrabz(t->ar->regiondata, t->center[0], t->center[1], t->center[2]);
1616                 }
1617         }
1618 }
1619
1620 void calculatePropRatio(TransInfo *t)
1621 {
1622         TransData *td = t->data;
1623         int i;
1624         float dist;
1625         short connected = t->flag & T_PROP_CONNECTED;
1626
1627         if (t->flag & T_PROP_EDIT) {
1628                 for(i = 0 ; i < t->total; i++, td++) {
1629                         if (td->flag & TD_SELECTED) {
1630                                 td->factor = 1.0f;
1631                         }
1632                         else if (t->flag & T_MIRROR && td->loc[0] * t->mirror < -0.00001f)
1633                         {
1634                                 td->flag |= TD_SKIP;
1635                                 td->factor = 0.0f;
1636                                 restoreElement(td);
1637                         }
1638                         else if ((connected &&
1639                                                 (td->flag & TD_NOTCONNECTED || td->dist > t->prop_size))
1640                                 ||
1641                                         (connected == 0 &&
1642                                                 td->rdist > t->prop_size)) {
1643                                 /*
1644                                    The elements are sorted according to their dist member in the array,
1645                                    that means we can stop when it finds one element outside of the propsize.
1646                                 */
1647                                 td->flag |= TD_NOACTION;
1648                                 td->factor = 0.0f;
1649                                 restoreElement(td);
1650                         }
1651                         else {
1652                                 /* Use rdist for falloff calculations, it is the real distance */
1653                                 td->flag &= ~TD_NOACTION;
1654                                 
1655                                 if (connected)
1656                                         dist= (t->prop_size-td->dist)/t->prop_size;
1657                                 else
1658                                         dist= (t->prop_size-td->rdist)/t->prop_size;
1659
1660                                 /*
1661                                  * Clamp to positive numbers.
1662                                  * Certain corner cases with connectivity and individual centers
1663                                  * can give values of rdist larger than propsize.
1664                                  */
1665                                 if (dist < 0.0f)
1666                                         dist = 0.0f;
1667                                 
1668                                 switch(t->prop_mode) {
1669                                 case PROP_SHARP:
1670                                         td->factor= dist*dist;
1671                                         break;
1672                                 case PROP_SMOOTH:
1673                                         td->factor= 3.0f*dist*dist - 2.0f*dist*dist*dist;
1674                                         break;
1675                                 case PROP_ROOT:
1676                                         td->factor = (float)sqrt(dist);
1677                                         break;
1678                                 case PROP_LIN:
1679                                         td->factor = dist;
1680                                         break;
1681                                 case PROP_CONST:
1682                                         td->factor = 1.0f;
1683                                         break;
1684                                 case PROP_SPHERE:
1685                                         td->factor = (float)sqrt(2*dist - dist * dist);
1686                                         break;
1687                                 case PROP_RANDOM:
1688                                         BLI_srand( BLI_rand() ); /* random seed */
1689                                         td->factor = BLI_frand()*dist;
1690                                         break;
1691                                 default:
1692                                         td->factor = 1;
1693                                 }
1694                         }
1695                 }
1696                 switch(t->prop_mode) {
1697                 case PROP_SHARP:
1698                         strcpy(t->proptext, "(Sharp)");
1699                         break;
1700                 case PROP_SMOOTH:
1701                         strcpy(t->proptext, "(Smooth)");
1702                         break;
1703                 case PROP_ROOT:
1704                         strcpy(t->proptext, "(Root)");
1705                         break;
1706                 case PROP_LIN:
1707                         strcpy(t->proptext, "(Linear)");
1708                         break;
1709                 case PROP_CONST:
1710                         strcpy(t->proptext, "(Constant)");
1711                         break;
1712                 case PROP_SPHERE:
1713                         strcpy(t->proptext, "(Sphere)");
1714                         break;
1715                 case PROP_RANDOM:
1716                         strcpy(t->proptext, "(Random)");
1717                         break;
1718                 default:
1719                         t->proptext[0]= '\0';
1720                 }
1721         }
1722         else {
1723                 for(i = 0 ; i < t->total; i++, td++) {
1724                         td->factor = 1.0;
1725                 }
1726                 t->proptext[0]= '\0';
1727         }
1728 }