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