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