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