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