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