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