NLA SoC: Start of integration of Meta-strips in Transform
[blender.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., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
19  *
20  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
21  * All rights reserved.
22  *
23  * The Original Code is: all of this file.
24  *
25  * Contributor(s): none yet.
26  *
27  * ***** END GPL LICENSE BLOCK *****
28  */
29
30 #include <string.h>
31 #include <math.h>
32
33 #include "MEM_guardedalloc.h"
34
35 #include "BLO_sys_types.h" // for intptr_t support
36
37 #include "DNA_anim_types.h"
38 #include "DNA_action_types.h"
39 #include "DNA_armature_types.h"
40 #include "DNA_constraint_types.h"
41 #include "DNA_curve_types.h"
42 #include "DNA_lattice_types.h"
43 #include "DNA_mesh_types.h"
44 #include "DNA_modifier_types.h"
45 #include "DNA_nla_types.h"
46 #include "DNA_node_types.h"
47 #include "DNA_object_types.h"
48 #include "DNA_object_force.h"
49 #include "DNA_particle_types.h"
50 #include "DNA_screen_types.h"
51 #include "DNA_space_types.h"
52 #include "DNA_scene_types.h"
53 #include "DNA_userdef_types.h"
54 #include "DNA_view3d_types.h"
55 #include "DNA_windowmanager_types.h"
56
57 #include "RNA_access.h"
58
59 //#include "BIF_screen.h"
60 //#include "BIF_mywindow.h"
61 #include "BIF_gl.h"
62 //#include "BIF_editaction.h"
63 //#include "BIF_editmesh.h"
64 //#include "BIF_editnla.h"
65 //#include "BIF_editsima.h"
66 //#include "BIF_editparticle.h"
67 //#include "BIF_meshtools.h"
68 #include "BIF_retopo.h"
69
70 #include "BKE_action.h"
71 #include "BKE_anim.h"
72 #include "BKE_armature.h"
73 #include "BKE_cloth.h"
74 #include "BKE_curve.h"
75 #include "BKE_depsgraph.h"
76 #include "BKE_displist.h"
77 #include "BKE_depsgraph.h"
78 #include "BKE_fcurve.h"
79 #include "BKE_global.h"
80 #include "BKE_group.h"
81 #include "BKE_lattice.h"
82 #include "BKE_key.h"
83 #include "BKE_mesh.h"
84 #include "BKE_modifier.h"
85 #include "BKE_nla.h"
86 #include "BKE_object.h"
87 #include "BKE_utildefines.h"
88 #include "BKE_context.h"
89
90 #include "ED_anim_api.h"
91 #include "ED_armature.h"
92 #include "ED_image.h"
93 #include "ED_keyframing.h"
94 #include "ED_mesh.h"
95 #include "ED_space_api.h"
96 #include "ED_uvedit.h"
97 #include "ED_view3d.h"
98
99 //#include "BDR_unwrapper.h"
100
101 #include "BLI_arithb.h"
102 #include "BLI_blenlib.h"
103 #include "BLI_editVert.h"
104 #include "BLI_rand.h"
105
106 #include "RNA_access.h"
107
108 #include "WM_types.h"
109
110 #include "UI_resources.h"
111
112 //#include "blendef.h"
113 //
114 //#include "mydevice.h"
115
116 #include "transform.h"
117
118 extern ListBase editelems;
119
120 extern TransInfo Trans; /* From transform.c */
121
122 /* ************************** Functions *************************** */
123
124 void getViewVector(TransInfo *t, float coord[3], float vec[3])
125 {
126         if (t->persp != V3D_ORTHO)
127         {
128                 float p1[4], p2[4];
129
130                 VECCOPY(p1, coord);
131                 p1[3] = 1.0f;
132                 VECCOPY(p2, p1);
133                 p2[3] = 1.0f;
134                 Mat4MulVec4fl(t->viewmat, p2);
135
136                 p2[0] = 2.0f * p2[0];
137                 p2[1] = 2.0f * p2[1];
138                 p2[2] = 2.0f * p2[2];
139
140                 Mat4MulVec4fl(t->viewinv, p2);
141
142                 VecSubf(vec, p1, p2);
143         }
144         else {
145                 VECCOPY(vec, t->viewinv[2]);
146         }
147         Normalize(vec);
148 }
149
150 /* ************************** GENERICS **************************** */
151
152 static void clipMirrorModifier(TransInfo *t, Object *ob)
153 {
154         ModifierData *md= ob->modifiers.first;
155         float tolerance[3] = {0.0f, 0.0f, 0.0f};
156         int axis = 0;
157
158         for (; md; md=md->next) {
159                 if (md->type==eModifierType_Mirror) {
160                         MirrorModifierData *mmd = (MirrorModifierData*) md;     
161                 
162                         if(mmd->flag & MOD_MIR_CLIPPING) {
163                                 axis = 0;
164                                 if(mmd->flag & MOD_MIR_AXIS_X) {
165                                         axis |= 1;
166                                         tolerance[0] = mmd->tolerance;
167                                 }
168                                 if(mmd->flag & MOD_MIR_AXIS_Y) {
169                                         axis |= 2;
170                                         tolerance[1] = mmd->tolerance;
171                                 }
172                                 if(mmd->flag & MOD_MIR_AXIS_Z) {
173                                         axis |= 4;
174                                         tolerance[2] = mmd->tolerance;
175                                 }
176                                 if (axis) {
177                                         float mtx[4][4], imtx[4][4];
178                                         int i;
179                                         TransData *td = t->data;
180                 
181                                         if (mmd->mirror_ob) {
182                                                 float obinv[4][4];
183
184                                                 Mat4Invert(obinv, mmd->mirror_ob->obmat);
185                                                 Mat4MulMat4(mtx, ob->obmat, obinv);
186                                                 Mat4Invert(imtx, mtx);
187                                         }
188
189                                         for(i = 0 ; i < t->total; i++, td++) {
190                                                 int clip;
191                                                 float loc[3], iloc[3];
192
193                                                 if (td->flag & TD_NOACTION)
194                                                         break;
195                                                 if (td->loc==NULL)
196                                                         break;
197                                                         
198                                                 if (td->flag & TD_SKIP)
199                                                         continue;
200                         
201                                                 VecCopyf(loc,  td->loc);
202                                                 VecCopyf(iloc, td->iloc);
203
204                                                 if (mmd->mirror_ob) {
205                                                         VecMat4MulVecfl(loc, mtx, loc);
206                                                         VecMat4MulVecfl(iloc, mtx, iloc);
207                                                 }
208
209                                                 clip = 0;
210                                                 if(axis & 1) {
211                                                         if(fabs(iloc[0])<=tolerance[0] || 
212                                                            loc[0]*iloc[0]<0.0f) {
213                                                                 loc[0]= 0.0f;
214                                                                 clip = 1;
215                                                         }
216                                                 }
217                         
218                                                 if(axis & 2) {
219                                                         if(fabs(iloc[1])<=tolerance[1] || 
220                                                            loc[1]*iloc[1]<0.0f) {
221                                                                 loc[1]= 0.0f;
222                                                                 clip = 1;
223                                                         }
224                                                 }
225                                                 if(axis & 4) {
226                                                         if(fabs(iloc[2])<=tolerance[2] || 
227                                                            loc[2]*iloc[2]<0.0f) {
228                                                                 loc[2]= 0.0f;
229                                                                 clip = 1;
230                                                         }
231                                                 }
232                                                 if (clip) {
233                                                         if (mmd->mirror_ob) {
234                                                                 VecMat4MulVecfl(loc, imtx, loc);
235                                                         }
236                                                         VecCopyf(td->loc, loc);
237                                                 }
238                                         }
239                                 }
240
241                         }
242                 }
243         }
244 }
245
246 /* assumes obedit set to mesh object */
247 static void editmesh_apply_to_mirror(TransInfo *t)
248 {
249         TransData *td = t->data;
250         EditVert *eve;
251         int i;
252         
253         for(i = 0 ; i < t->total; i++, td++) {
254                 if (td->flag & TD_NOACTION)
255                         break;
256                 if (td->loc==NULL)
257                         break;
258                 if (td->flag & TD_SKIP)
259                         continue;
260                 
261                 eve = td->extra;
262                 if(eve) {
263                         eve->co[0]= -td->loc[0];
264                         eve->co[1]= td->loc[1];
265                         eve->co[2]= td->loc[2];
266                 }               
267         }               
268 }
269
270 /* called for updating while transform acts, once per redraw */
271 void recalcData(TransInfo *t)
272 {
273         Scene *scene = t->scene;
274         Base *base;
275         
276         if (t->obedit) {
277         }
278         else if(G.f & G_PARTICLEEDIT) {
279                 flushTransParticles(t);
280         }
281         if (t->spacetype==SPACE_NODE) {
282                 flushTransNodes(t);
283         }
284         else if (t->spacetype==SPACE_SEQ) {
285                 flushTransSeq(t);
286         }
287         else if (t->spacetype == SPACE_IPO) {
288                 SpaceIpo *sipo= (SpaceIpo *)t->sa->spacedata.first;
289                 Scene *scene;
290                 
291                 ListBase anim_data = {NULL, NULL};
292                 bAnimContext ac;
293                 int filter;
294                 
295                 bAnimListElem *ale;
296                 int dosort = 0;
297                 
298                 
299                 /* initialise relevant anim-context 'context' data from TransInfo data */
300                         /* NOTE: sync this with the code in ANIM_animdata_get_context() */
301                 memset(&ac, 0, sizeof(bAnimContext));
302                 
303                 scene= ac.scene= t->scene;
304                 ac.obact= OBACT;
305                 ac.sa= t->sa;
306                 ac.ar= t->ar;
307                 ac.spacetype= (t->sa)? t->sa->spacetype : 0;
308                 ac.regiontype= (t->ar)? t->ar->regiontype : 0;
309                 
310                 ANIM_animdata_context_getdata(&ac);
311                 
312                 /* do the flush first */
313                 flushTransGraphData(t);
314                 
315                 /* get curves to check if a re-sort is needed */
316                 filter= (ANIMFILTER_VISIBLE | ANIMFILTER_FOREDIT | ANIMFILTER_CURVESONLY | ANIMFILTER_CURVEVISIBLE);
317                 ANIM_animdata_filter(&ac, &anim_data, filter, ac.data, ac.datatype);
318                 
319                 /* now test if there is a need to re-sort */
320                 for (ale= anim_data.first; ale; ale= ale->next) {
321                         FCurve *fcu= (FCurve *)ale->key_data;
322                         
323                         /* watch it: if the time is wrong: do not correct handles yet */
324                         if (test_time_fcurve(fcu))
325                                 dosort++;
326                         else
327                                 calchandles_fcurve(fcu);
328                 }
329                 
330                 /* do resort and other updates? */
331                 if (dosort) remake_graph_transdata(t, &anim_data);
332                 //if (sipo->showkey) update_ipokey_val();
333                 
334                 /* now free temp channels */
335                 BLI_freelistN(&anim_data);
336                 
337                 /* update realtime - not working? */
338                 if (sipo->lock) {
339                 
340                 }
341         }
342         else if (t->spacetype == SPACE_NLA) {
343                 TransData *td= t->data;
344                 int i;
345                 
346                 /* for each point we've captured, look at its 'extra' data, which is basically a wrapper around the strip 
347                  * it is for + some extra storage for the values that get set, and use RNA to set this value (performing validation
348                  * work so that we don't need to repeat it here)
349                  */
350                 for (i = 0; i < t->total; i++, td++)
351                 {
352                         if (td->extra)
353                         {
354                                 TransDataNla *tdn= td->extra;
355                                 NlaStrip *strip= tdn->strip;
356                                 
357                                 /* if we're just cancelling (i.e. the user aborted the transform), 
358                                  * just restore the data by directly overwriting the values with the original 
359                                  * ones (i.e. don't go through RNA), as we get some artifacts...
360                                  */
361                                 if (t->state == TRANS_CANCEL) {
362                                         /* clear the values by directly overwriting the originals, but also need to restore 
363                                          * endpoints of neighboring transition-strips
364                                          */
365                                         if (tdn->handle) {
366                                                 strip->end= tdn->val;
367                                                 
368                                                 if ((strip->next) && (strip->next->type == NLASTRIP_TYPE_TRANSITION))
369                                                         strip->next->start= tdn->val;
370                                         }
371                                         else {
372                                                 strip->start= tdn->val;
373                                                 
374                                                 if ((strip->prev) && (strip->prev->type == NLASTRIP_TYPE_TRANSITION))
375                                                         strip->prev->end= tdn->val;
376                                         }
377                                 }
378                                 else {
379                                         PointerRNA strip_ptr;
380                                         
381                                         /* make RNA-pointer */
382                                         RNA_pointer_create(NULL, &RNA_NlaStrip, strip, &strip_ptr);
383                                         
384                                         /* write the value set by the transform tools to the appropriate property using RNA */
385                                         if (tdn->handle)
386                                                 RNA_float_set(&strip_ptr, "end_frame", tdn->val);
387                                         else
388                                                 RNA_float_set(&strip_ptr, "start_frame", tdn->val);
389                                 }
390                         }
391                 }
392                 
393                 /* loop over the TransDataNla again, flushing the transforms (since we use Metas to make transforms easier) */
394                 td= t->data;
395                 for (i = 0; i < t->total; i++, td++)
396                 {
397                         if (td->extra)
398                         {
399                                 TransDataNla *tdn= td->extra;
400                                 NlaStrip *strip= tdn->strip;
401                                 
402                                 // TODO: this may flush some things twice, but that's fine as there's no impact from that
403                                 BKE_nlameta_flush_transforms(strip);
404                         }
405                 }
406         }
407         else if (t->obedit) {
408                 if ELEM(t->obedit->type, OB_CURVE, OB_SURF) {
409                         Curve *cu= t->obedit->data;
410                         Nurb *nu= cu->editnurb->first;
411                         
412                         DAG_object_flush_update(scene, t->obedit, OB_RECALC_DATA);  /* sets recalc flags */
413                         
414                         if (t->state == TRANS_CANCEL) {
415                                 while(nu) {
416                                         calchandlesNurb(nu); /* Cant do testhandlesNurb here, it messes up the h1 and h2 flags */
417                                         nu= nu->next;
418                                 }
419                         } else {
420                                 /* Normal updating */
421                                 while(nu) {
422                                         test2DNurb(nu);
423                                         calchandlesNurb(nu);
424                                         nu= nu->next;
425                                 }
426                                 /* TRANSFORM_FIX_ME */
427                                 // retopo_do_all();
428                         }
429                 }
430                 else if(t->obedit->type==OB_LATTICE) {
431                         Lattice *la= t->obedit->data;
432                         DAG_object_flush_update(scene, t->obedit, OB_RECALC_DATA);  /* sets recalc flags */
433                         
434                         if(la->editlatt->flag & LT_OUTSIDE) outside_lattice(la->editlatt);
435                 }
436                 else if (t->obedit->type == OB_MESH) {
437                         if(t->spacetype==SPACE_IMAGE) {
438                                 SpaceImage *sima= t->sa->spacedata.first;
439
440                                 flushTransUVs(t);
441                                 if(sima->flag & SI_LIVE_UNWRAP)
442                                         ED_uvedit_live_unwrap_re_solve();
443         
444                                 DAG_object_flush_update(scene, t->obedit, OB_RECALC_DATA);
445                         } else {
446                                 EditMesh *em = ((Mesh*)t->obedit->data)->edit_mesh;
447                                 /* mirror modifier clipping? */
448                                 if(t->state != TRANS_CANCEL) {
449                                         /* TRANSFORM_FIX_ME */
450 //                                      if ((G.qual & LR_CTRLKEY)==0) {
451 //                                              /* Only retopo if not snapping, Note, this is the only case of G.qual being used, but we have no T_SHIFT_MOD - Campbell */
452 //                                              retopo_do_all();
453 //                                      }
454                                         clipMirrorModifier(t, t->obedit);
455                                 }
456                                 if((t->options & CTX_NO_MIRROR) == 0 && (t->flag & T_MIRROR))
457                                         editmesh_apply_to_mirror(t);
458                                 
459                                 DAG_object_flush_update(scene, t->obedit, OB_RECALC_DATA);  /* sets recalc flags */
460                                 
461                                 recalc_editnormals(em);
462                         }
463                 }
464                 else if(t->obedit->type==OB_ARMATURE) { /* no recalc flag, does pose */
465                         bArmature *arm= t->obedit->data;
466                         ListBase *edbo = arm->edbo;
467                         EditBone *ebo;
468                         TransData *td = t->data;
469                         int i;
470                         
471                         /* Ensure all bones are correctly adjusted */
472                         for (ebo = edbo->first; ebo; ebo = ebo->next){
473                                 
474                                 if ((ebo->flag & BONE_CONNECTED) && ebo->parent){
475                                         /* If this bone has a parent tip that has been moved */
476                                         if (ebo->parent->flag & BONE_TIPSEL){
477                                                 VECCOPY (ebo->head, ebo->parent->tail);
478                                                 if(t->mode==TFM_BONE_ENVELOPE) ebo->rad_head= ebo->parent->rad_tail;
479                                         }
480                                         /* If this bone has a parent tip that has NOT been moved */
481                                         else{
482                                                 VECCOPY (ebo->parent->tail, ebo->head);
483                                                 if(t->mode==TFM_BONE_ENVELOPE) ebo->parent->rad_tail= ebo->rad_head;
484                                         }
485                                 }
486                                 
487                                 /* on extrude bones, oldlength==0.0f, so we scale radius of points */
488                                 ebo->length= VecLenf(ebo->head, ebo->tail);
489                                 if(ebo->oldlength==0.0f) {
490                                         ebo->rad_head= 0.25f*ebo->length;
491                                         ebo->rad_tail= 0.10f*ebo->length;
492                                         ebo->dist= 0.25f*ebo->length;
493                                         if(ebo->parent) {
494                                                 if(ebo->rad_head > ebo->parent->rad_tail)
495                                                         ebo->rad_head= ebo->parent->rad_tail;
496                                         }
497                                 }
498                                 else if(t->mode!=TFM_BONE_ENVELOPE) {
499                                         /* if bones change length, lets do that for the deform distance as well */
500                                         ebo->dist*= ebo->length/ebo->oldlength;
501                                         ebo->rad_head*= ebo->length/ebo->oldlength;
502                                         ebo->rad_tail*= ebo->length/ebo->oldlength;
503                                         ebo->oldlength= ebo->length;
504                                 }
505                         }
506                         
507                         
508                         if (t->mode != TFM_BONE_ROLL)
509                         {
510                                 /* fix roll */
511                                 for(i = 0; i < t->total; i++, td++)
512                                 {
513                                         if (td->extra)
514                                         {
515                                                 float vec[3], up_axis[3];
516                                                 float qrot[4];
517                                                 
518                                                 ebo = td->extra;
519                                                 VECCOPY(up_axis, td->axismtx[2]);
520                                                 
521                                                 if (t->mode != TFM_ROTATION)
522                                                 {
523                                                         VecSubf(vec, ebo->tail, ebo->head);
524                                                         Normalize(vec);
525                                                         RotationBetweenVectorsToQuat(qrot, td->axismtx[1], vec);
526                                                         QuatMulVecf(qrot, up_axis);
527                                                 }
528                                                 else
529                                                 {
530                                                         Mat3MulVecfl(t->mat, up_axis);
531                                                 }
532                                                 
533                                                 ebo->roll = ED_rollBoneToVector(ebo, up_axis);
534                                         }
535                                 }
536                         }
537                         
538                         if(arm->flag & ARM_MIRROR_EDIT) 
539                                 transform_armature_mirror_update(t->obedit);
540                         
541                 }
542                 else
543                         DAG_object_flush_update(scene, t->obedit, OB_RECALC_DATA);  /* sets recalc flags */
544         }
545         else if( (t->flag & T_POSE) && t->poseobj) {
546                 Object *ob= t->poseobj;
547                 bArmature *arm= ob->data;
548                 
549                 /* if animtimer is running, and the object already has animation data,
550                  * check if the auto-record feature means that we should record 'samples'
551                  * (i.e. uneditable animation values)
552                  */
553                 // TODO: autokeyframe calls need some setting to specify to add samples (FPoints) instead of keyframes?
554                 // TODO: maybe the ob->adt check isn't really needed? makes it too difficult to use...
555                 if (/*(ob->adt) && */(t->animtimer) && IS_AUTOKEY_ON(t->scene)) {
556                         short targetless_ik= (t->flag & T_AUTOIK); // XXX this currently doesn't work, since flags aren't set yet!
557                         autokeyframe_pose_cb_func(t->scene, (View3D *)t->view, ob, t->mode, targetless_ik);
558                 }
559                 
560                 /* old optimize trick... this enforces to bypass the depgraph */
561                 if (!(arm->flag & ARM_DELAYDEFORM)) {
562                         DAG_object_flush_update(scene, ob, OB_RECALC_DATA);  /* sets recalc flags */
563                 }
564                 else
565                         where_is_pose(scene, ob);
566         }
567         else {
568                 for(base= FIRSTBASE; base; base= base->next) {
569                         Object *ob= base->object;
570                         
571                         /* this flag is from depgraph, was stored in initialize phase, handled in drawview.c */
572                         if(base->flag & BA_HAS_RECALC_OB)
573                                 ob->recalc |= OB_RECALC_OB;
574                         if(base->flag & BA_HAS_RECALC_DATA)
575                                 ob->recalc |= OB_RECALC_DATA;
576                         
577                         /* if object/base is selected */
578                         if ((base->flag & SELECT) || (ob->flag & SELECT)) {
579                                 /* if animtimer is running, and the object already has animation data,
580                                  * check if the auto-record feature means that we should record 'samples'
581                                  * (i.e. uneditable animation values)
582                                  */
583                                 // TODO: autokeyframe calls need some setting to specify to add samples (FPoints) instead of keyframes?
584                                 // TODO: maybe the ob->adt check isn't really needed? makes it too difficult to use...
585                                 if (/*(ob->adt) && */(t->animtimer) && IS_AUTOKEY_ON(t->scene)) {
586                                         autokeyframe_ob_cb_func(t->scene, (View3D *)t->view, ob, t->mode);
587                                 }
588                         }
589                         
590                         /* proxy exception */
591                         if(ob->proxy)
592                                 ob->proxy->recalc |= ob->recalc;
593                         if(ob->proxy_group)
594                                 group_tag_recalc(ob->proxy_group->dup_group);
595                 } 
596         }
597
598         /* update shaded drawmode while transform */
599         if(t->spacetype==SPACE_VIEW3D && ((View3D*)t->view)->drawtype == OB_SHADED)
600                 reshadeall_displist(t->scene);
601 }
602
603 void drawLine(TransInfo *t, float *center, float *dir, char axis, short options)
604 {
605         float v1[3], v2[3], v3[3];
606         char col[3], col2[3];
607         
608         if (t->spacetype == SPACE_VIEW3D)
609         {
610                 View3D *v3d = t->view;
611                 
612                 glPushMatrix();
613                 
614                 //if(t->obedit) glLoadMatrixf(t->obedit->obmat);        // sets opengl viewing
615                 
616         
617                 VecCopyf(v3, dir);
618                 VecMulf(v3, v3d->far);
619                 
620                 VecSubf(v2, center, v3);
621                 VecAddf(v1, center, v3);
622         
623                 if (options & DRAWLIGHT) {
624                         col[0] = col[1] = col[2] = 220;
625                 }
626                 else {
627                         UI_GetThemeColor3ubv(TH_GRID, col);
628                 }
629                 UI_make_axis_color(col, col2, axis);
630                 glColor3ubv((GLubyte *)col2);
631         
632                 setlinestyle(0);
633                 glBegin(GL_LINE_STRIP); 
634                         glVertex3fv(v1); 
635                         glVertex3fv(v2); 
636                 glEnd();
637                 
638                 glPopMatrix();
639         }
640 }
641
642 void resetTransRestrictions(TransInfo *t)
643 {
644         t->flag &= ~T_ALL_RESTRICTIONS;
645 }
646
647 int initTransInfo (bContext *C, TransInfo *t, wmOperator *op, wmEvent *event)
648 {
649         Scene *sce = CTX_data_scene(C);
650         ToolSettings *ts = CTX_data_tool_settings(C);
651         ARegion *ar = CTX_wm_region(C);
652         ScrArea *sa = CTX_wm_area(C);
653         Object *obedit = CTX_data_edit_object(C);
654         
655         /* moving: is shown in drawobject() (transform color) */
656 //  TRANSFORM_FIX_ME    
657 //      if(obedit || (t->flag & T_POSE) ) G.moving= G_TRANSFORM_EDIT;
658 //      else if(G.f & G_PARTICLEEDIT) G.moving= G_TRANSFORM_PARTICLE;
659 //      else G.moving= G_TRANSFORM_OBJ;
660         
661         t->scene = sce;
662         t->sa = sa;
663         t->ar = ar;
664         t->obedit = obedit;
665         t->settings = ts;
666
667         t->data = NULL;
668         t->ext = NULL;
669
670         t->helpline = HLP_NONE;
671
672         t->flag = 0;
673         
674         t->redraw = 1; /* redraw first time */
675         
676         if (event)
677         {
678                 t->imval[0] = event->x - t->ar->winrct.xmin;
679                 t->imval[1] = event->y - t->ar->winrct.ymin;
680                 
681                 t->event_type = event->type;
682         }
683         else
684         {
685                 t->imval[0] = 0;
686                 t->imval[1] = 0;
687         }
688         
689         t->con.imval[0] = t->imval[0];
690         t->con.imval[1] = t->imval[1];
691
692         t->mval[0] = t->imval[0];
693         t->mval[1] = t->imval[1];
694
695         t->transform            = NULL;
696         t->handleEvent          = NULL;
697
698         t->total                        = 0;
699
700         t->val = 0.0f;
701
702         t->vec[0]                       =
703                 t->vec[1]               =
704                 t->vec[2]               = 0.0f;
705         
706         t->center[0]            =
707                 t->center[1]    =
708                 t->center[2]    = 0.0f;
709         
710         Mat3One(t->mat);
711         
712         t->spacetype = sa->spacetype;
713         if(t->spacetype == SPACE_VIEW3D)
714         {
715                 View3D *v3d = sa->spacedata.first;
716                 
717                 t->view = v3d;
718                 t->animtimer= CTX_wm_screen(C)->animtimer;
719                 
720                 if(v3d->flag & V3D_ALIGN) t->flag |= T_V3D_ALIGN;
721                 t->around = v3d->around;
722
723                 if (op && RNA_struct_find_property(op->ptr, "constraint_axis") && RNA_property_is_set(op->ptr, "constraint_orientation"))
724                 {
725                         t->current_orientation = RNA_int_get(op->ptr, "constraint_orientation");
726
727                         if (t->current_orientation >= V3D_MANIP_CUSTOM + BIF_countTransformOrientation(C) - 1)
728                         {
729                                 t->current_orientation = V3D_MANIP_GLOBAL;
730                         }
731                 }
732                 else
733                 {
734                         t->current_orientation = v3d->twmode;
735                 }
736         }
737         else if(t->spacetype==SPACE_IMAGE || t->spacetype==SPACE_NODE)
738         {
739                 SpaceImage *sima = sa->spacedata.first;
740                 // XXX for now, get View2D  from the active region
741                 t->view = &ar->v2d;
742                 t->around = sima->around;
743         }
744         else
745         {
746                 // XXX for now, get View2D  from the active region
747                 t->view = &ar->v2d;
748                 
749                 t->around = V3D_CENTER;
750         }
751
752         if (op && RNA_struct_find_property(op->ptr, "mirror") && RNA_property_is_set(op->ptr, "mirror"))
753         {
754                 if (RNA_boolean_get(op->ptr, "mirror"))
755                 {
756                         t->flag |= T_MIRROR;
757                 }
758         }
759         // Need stuff to take it from edit mesh or whatnot here
760         else
761         {
762                 if (t->obedit && t->obedit->type == OB_MESH && ts->editbutflag & B_MESH_X_MIRROR)
763                 {
764                         t->flag |= T_MIRROR;
765                 }
766         }
767
768         /* setting PET flag */
769         if (op && RNA_struct_find_property(op->ptr, "proportional") && RNA_property_is_set(op->ptr, "proportional"))
770         {
771                 switch(RNA_enum_get(op->ptr, "proportional"))
772                 {
773                 case 2: /* XXX connected constant */
774                         t->flag |= T_PROP_CONNECTED;
775                 case 1: /* XXX prop on constant */
776                         t->flag |= T_PROP_EDIT;
777                         break;
778                 }
779         }
780         else
781         {
782                 if ((t->options & CTX_NO_PET) == 0 && (ts->proportional)) {
783                         t->flag |= T_PROP_EDIT;
784                         
785                         if(ts->proportional == 2)
786                                 t->flag |= T_PROP_CONNECTED;    // yes i know, has to become define
787                 }
788         }
789
790         if (op && RNA_struct_find_property(op->ptr, "proportional_size") && RNA_property_is_set(op->ptr, "proportional_size"))
791         {
792                 t->prop_size = RNA_float_get(op->ptr, "proportional_size");
793         }
794         else
795         {
796                 t->prop_size = ts->proportional_size;
797         }
798         
799         if (op && RNA_struct_find_property(op->ptr, "proportional_editing_falloff") && RNA_property_is_set(op->ptr, "proportional_editing_falloff"))
800         {
801                 t->prop_mode = RNA_enum_get(op->ptr, "proportional_editing_falloff");
802         }
803         else
804         {
805                 t->prop_mode = ts->prop_mode;
806         }
807
808         /* TRANSFORM_FIX_ME rna restrictions */
809         if (t->prop_size <= 0)
810         {
811                 t->prop_size = 1.0f;
812         }
813
814         setTransformViewMatrices(t);
815         initNumInput(&t->num);
816         initNDofInput(&t->ndof);
817         
818         return 1;
819 }
820
821 /* Here I would suggest only TransInfo related issues, like free data & reset vars. Not redraws */
822 void postTrans (TransInfo *t) 
823 {
824         TransData *td;
825
826         if (t->draw_handle)
827         {
828                 ED_region_draw_cb_exit(t->ar->type, t->draw_handle);
829         }
830         
831         /* postTrans can be called when nothing is selected, so data is NULL already */
832         if (t->data) {
833                 int a;
834
835                 /* since ipokeys are optional on objects, we mallocced them per trans-data */
836                 for(a=0, td= t->data; a<t->total; a++, td++) {
837                         if(td->tdi) MEM_freeN(td->tdi);
838                         if (td->flag & TD_BEZTRIPLE) MEM_freeN(td->hdata); 
839                 }
840                 MEM_freeN(t->data);
841         }
842
843         if (t->ext) MEM_freeN(t->ext);
844         if (t->data2d) {
845                 MEM_freeN(t->data2d);
846                 t->data2d= NULL;
847         }
848
849         if(t->spacetype==SPACE_IMAGE) {
850                 SpaceImage *sima= t->sa->spacedata.first;
851                 if(sima->flag & SI_LIVE_UNWRAP)
852                         ED_uvedit_live_unwrap_end(t->state == TRANS_CANCEL);
853         }
854         else if(ELEM(t->spacetype, SPACE_ACTION, SPACE_NLA)) {
855                 if (t->customData)
856                         MEM_freeN(t->customData);
857         }
858 }
859
860 void applyTransObjects(TransInfo *t)
861 {
862         TransData *td;
863         
864         for (td = t->data; td < t->data + t->total; td++) {
865                 VECCOPY(td->iloc, td->loc);
866                 if (td->ext->rot) {
867                         VECCOPY(td->ext->irot, td->ext->rot);
868                 }
869                 if (td->ext->size) {
870                         VECCOPY(td->ext->isize, td->ext->size);
871                 }
872         }       
873         recalcData(t);
874
875
876 /* helper for below */
877 static void restore_ipokey(float *poin, float *old)
878 {
879         if(poin) {
880                 poin[0]= old[0];
881                 poin[-3]= old[3];
882                 poin[3]= old[6];
883         }
884 }
885
886 static void restoreElement(TransData *td) {
887         /* TransData for crease has no loc */
888         if (td->loc) {
889                 VECCOPY(td->loc, td->iloc);
890         }
891         if (td->val) {
892                 *td->val = td->ival;
893         }
894         if (td->ext && (td->flag&TD_NO_EXT)==0) {
895                 if (td->ext->rot) {
896                         VECCOPY(td->ext->rot, td->ext->irot);
897                 }
898                 if (td->ext->size) {
899                         VECCOPY(td->ext->size, td->ext->isize);
900                 }
901                 if(td->flag & TD_USEQUAT) {
902                         if (td->ext->quat) {
903                                 QUATCOPY(td->ext->quat, td->ext->iquat);
904                         }
905                 }
906         }
907         
908         if (td->flag & TD_BEZTRIPLE) {
909                 *(td->hdata->h1) = td->hdata->ih1;
910                 *(td->hdata->h2) = td->hdata->ih2;
911         }
912         
913         if(td->tdi) {
914                 TransDataIpokey *tdi= td->tdi;
915                 
916                 restore_ipokey(tdi->locx, tdi->oldloc);
917                 restore_ipokey(tdi->locy, tdi->oldloc+1);
918                 restore_ipokey(tdi->locz, tdi->oldloc+2);
919
920                 restore_ipokey(tdi->rotx, tdi->oldrot);
921                 restore_ipokey(tdi->roty, tdi->oldrot+1);
922                 restore_ipokey(tdi->rotz, tdi->oldrot+2);
923                 
924                 restore_ipokey(tdi->sizex, tdi->oldsize);
925                 restore_ipokey(tdi->sizey, tdi->oldsize+1);
926                 restore_ipokey(tdi->sizez, tdi->oldsize+2);
927         }
928 }
929
930 void restoreTransObjects(TransInfo *t)
931 {
932         TransData *td;
933         
934         for (td = t->data; td < t->data + t->total; td++) {
935                 restoreElement(td);
936         }
937         
938         Mat3One(t->mat);
939         
940         recalcData(t);
941 }
942
943 void calculateCenter2D(TransInfo *t)
944 {
945         if (t->flag & (T_EDIT|T_POSE)) {
946                 Object *ob= t->obedit?t->obedit:t->poseobj;
947                 float vec[3];
948                 
949                 VECCOPY(vec, t->center);
950                 Mat4MulVecfl(ob->obmat, vec);
951                 projectIntView(t, vec, t->center2d);
952         }
953         else {
954                 projectIntView(t, t->center, t->center2d);
955         }
956 }
957
958 void calculateCenterCursor(TransInfo *t)
959 {
960         float *cursor;
961
962         cursor = give_cursor(t->scene, t->view);
963         VECCOPY(t->center, cursor);
964
965         /* If edit or pose mode, move cursor in local space */
966         if (t->flag & (T_EDIT|T_POSE)) {
967                 Object *ob = t->obedit?t->obedit:t->poseobj;
968                 float mat[3][3], imat[3][3];
969                 
970                 VecSubf(t->center, t->center, ob->obmat[3]);
971                 Mat3CpyMat4(mat, ob->obmat);
972                 Mat3Inv(imat, mat);
973                 Mat3MulVecfl(imat, t->center);
974         }
975         
976         calculateCenter2D(t);
977 }
978
979 void calculateCenterCursor2D(TransInfo *t)
980 {
981         View2D *v2d= t->view;
982         float aspx=1.0, aspy=1.0;
983         
984         if(t->spacetype==SPACE_IMAGE) /* only space supported right now but may change */
985                 ED_space_image_uv_aspect(t->sa->spacedata.first, &aspx, &aspy);
986
987         if (v2d) {
988                 t->center[0] = v2d->cursor[0] * aspx; 
989                 t->center[1] = v2d->cursor[1] * aspy; 
990         }
991
992         calculateCenter2D(t);
993 }
994
995 void calculateCenterMedian(TransInfo *t)
996 {
997         float partial[3] = {0.0f, 0.0f, 0.0f};
998         int total = 0;
999         int i;
1000         
1001         for(i = 0; i < t->total; i++) {
1002                 if (t->data[i].flag & TD_SELECTED) {
1003                         if (!(t->data[i].flag & TD_NOCENTER))
1004                         {
1005                                 VecAddf(partial, partial, t->data[i].center);
1006                                 total++;
1007                         }
1008                 }
1009                 else {
1010                         /* 
1011                            All the selected elements are at the head of the array 
1012                            which means we can stop when it finds unselected data
1013                         */
1014                         break;
1015                 }
1016         }
1017         if(i)
1018                 VecMulf(partial, 1.0f / total);
1019         VECCOPY(t->center, partial);
1020
1021         calculateCenter2D(t);
1022 }
1023
1024 void calculateCenterBound(TransInfo *t)
1025 {
1026         float max[3];
1027         float min[3];
1028         int i;
1029         for(i = 0; i < t->total; i++) {
1030                 if (i) {
1031                         if (t->data[i].flag & TD_SELECTED) {
1032                                 if (!(t->data[i].flag & TD_NOCENTER))
1033                                         MinMax3(min, max, t->data[i].center);
1034                         }
1035                         else {
1036                                 /* 
1037                                    All the selected elements are at the head of the array 
1038                                    which means we can stop when it finds unselected data
1039                                 */
1040                                 break;
1041                         }
1042                 }
1043                 else {
1044                         VECCOPY(max, t->data[i].center);
1045                         VECCOPY(min, t->data[i].center);
1046                 }
1047         }
1048         VecAddf(t->center, min, max);
1049         VecMulf(t->center, 0.5);
1050
1051         calculateCenter2D(t);
1052 }
1053
1054 void calculateCenter(TransInfo *t) 
1055 {
1056         switch(t->around) {
1057         case V3D_CENTER:
1058                 calculateCenterBound(t);
1059                 break;
1060         case V3D_CENTROID:
1061                 calculateCenterMedian(t);
1062                 break;
1063         case V3D_CURSOR:
1064                 if(t->spacetype==SPACE_IMAGE)
1065                         calculateCenterCursor2D(t);
1066                 else
1067                         calculateCenterCursor(t);
1068                 break;
1069         case V3D_LOCAL:
1070                 /* Individual element center uses median center for helpline and such */
1071                 calculateCenterMedian(t);
1072                 break;
1073         case V3D_ACTIVE:
1074                 {
1075                 /* set median, and if if if... do object center */
1076 #if 0 // TRANSFORM_FIX_ME
1077                 EditSelection ese;
1078                 /* EDIT MODE ACTIVE EDITMODE ELEMENT */
1079
1080                 if (t->obedit && t->obedit->type == OB_MESH && EM_get_actSelection(&ese)) {
1081                         EM_editselection_center(t->center, &ese);
1082                         calculateCenter2D(t);
1083                         break;
1084                 } /* END EDIT MODE ACTIVE ELEMENT */
1085 #endif
1086                 
1087                 calculateCenterMedian(t);
1088                 if((t->flag & (T_EDIT|T_POSE))==0)
1089                 {
1090                         Scene *scene = t->scene;
1091                         Object *ob= OBACT;
1092                         if(ob)
1093                         {
1094                                 VECCOPY(t->center, ob->obmat[3]);
1095                                 projectIntView(t, t->center, t->center2d);
1096                         }
1097                 }
1098                 
1099                 }
1100         }
1101
1102         /* setting constraint center */
1103         VECCOPY(t->con.center, t->center);
1104         if(t->flag & (T_EDIT|T_POSE))
1105         {
1106                 Object *ob= t->obedit?t->obedit:t->poseobj;
1107                 Mat4MulVecfl(ob->obmat, t->con.center);
1108         }
1109
1110         /* voor panning from cameraview */
1111         if(t->flag & T_OBJECT)
1112         {
1113                 if(t->spacetype==SPACE_VIEW3D)
1114                 {
1115                         View3D *v3d = t->view;
1116                         Scene *scene = t->scene;
1117                         RegionView3D *rv3d = t->ar->regiondata;
1118                         
1119                         if(v3d->camera == OBACT && rv3d->persp==V3D_CAMOB)
1120                         {
1121                                 float axis[3];
1122                                 /* persinv is nasty, use viewinv instead, always right */
1123                                 VECCOPY(axis, t->viewinv[2]);
1124                                 Normalize(axis);
1125         
1126                                 /* 6.0 = 6 grid units */
1127                                 axis[0]= t->center[0]- 6.0f*axis[0];
1128                                 axis[1]= t->center[1]- 6.0f*axis[1];
1129                                 axis[2]= t->center[2]- 6.0f*axis[2];
1130                                 
1131                                 projectIntView(t, axis, t->center2d);
1132                                 
1133                                 /* rotate only needs correct 2d center, grab needs initgrabz() value */
1134                                 if(t->mode==TFM_TRANSLATION)
1135                                 {
1136                                         VECCOPY(t->center, axis);
1137                                         VECCOPY(t->con.center, t->center);
1138                                 }
1139                         }
1140                 }
1141         }       
1142
1143         if(t->spacetype==SPACE_VIEW3D)
1144         {
1145                 /* initgrabz() defines a factor for perspective depth correction, used in window_to_3d_delta() */
1146                 if(t->flag & (T_EDIT|T_POSE)) {
1147                         Object *ob= t->obedit?t->obedit:t->poseobj;
1148                         float vec[3];
1149                         
1150                         VECCOPY(vec, t->center);
1151                         Mat4MulVecfl(ob->obmat, vec);
1152                         initgrabz(t->ar->regiondata, vec[0], vec[1], vec[2]);
1153                 }
1154                 else {
1155                         initgrabz(t->ar->regiondata, t->center[0], t->center[1], t->center[2]);
1156                 } 
1157         }
1158 }
1159
1160 void calculatePropRatio(TransInfo *t)
1161 {
1162         TransData *td = t->data;
1163         int i;
1164         float dist;
1165         short connected = t->flag & T_PROP_CONNECTED;
1166         
1167         if (t->flag & T_PROP_EDIT) {
1168                 for(i = 0 ; i < t->total; i++, td++) {
1169                         if (td->flag & TD_SELECTED) {
1170                                 td->factor = 1.0f;
1171                         }
1172                         else if ((connected && 
1173                                                 (td->flag & TD_NOTCONNECTED || td->dist > t->prop_size))
1174                                 ||
1175                                         (connected == 0 &&
1176                                                 td->rdist > t->prop_size)) {
1177                                 /* 
1178                                    The elements are sorted according to their dist member in the array,
1179                                    that means we can stop when it finds one element outside of the propsize.
1180                                 */
1181                                 td->flag |= TD_NOACTION;
1182                                 td->factor = 0.0f;
1183                                 restoreElement(td);
1184                         }
1185                         else {
1186                                 /* Use rdist for falloff calculations, it is the real distance */
1187                                 td->flag &= ~TD_NOACTION;
1188                                 dist= (t->prop_size-td->rdist)/t->prop_size;
1189                                 
1190                                 /*
1191                                  * Clamp to positive numbers.
1192                                  * Certain corner cases with connectivity and individual centers
1193                                  * can give values of rdist larger than propsize.
1194                                  */
1195                                 if (dist < 0.0f)
1196                                         dist = 0.0f;
1197                                 
1198                                 switch(t->prop_mode) {
1199                                 case PROP_SHARP:
1200                                         td->factor= dist*dist;
1201                                         break;
1202                                 case PROP_SMOOTH:
1203                                         td->factor= 3.0f*dist*dist - 2.0f*dist*dist*dist;
1204                                         break;
1205                                 case PROP_ROOT:
1206                                         td->factor = (float)sqrt(dist);
1207                                         break;
1208                                 case PROP_LIN:
1209                                         td->factor = dist;
1210                                         break;
1211                                 case PROP_CONST:
1212                                         td->factor = 1.0f;
1213                                         break;
1214                                 case PROP_SPHERE:
1215                                         td->factor = (float)sqrt(2*dist - dist * dist);
1216                                         break;
1217                                 case PROP_RANDOM:
1218                                         BLI_srand( BLI_rand() ); /* random seed */
1219                                         td->factor = BLI_frand()*dist;
1220                                         break;
1221                                 default:
1222                                         td->factor = 1;
1223                                 }
1224                         }
1225                 }
1226                 switch(t->prop_mode) {
1227                 case PROP_SHARP:
1228                         strcpy(t->proptext, "(Sharp)");
1229                         break;
1230                 case PROP_SMOOTH:
1231                         strcpy(t->proptext, "(Smooth)");
1232                         break;
1233                 case PROP_ROOT:
1234                         strcpy(t->proptext, "(Root)");
1235                         break;
1236                 case PROP_LIN:
1237                         strcpy(t->proptext, "(Linear)");
1238                         break;
1239                 case PROP_CONST:
1240                         strcpy(t->proptext, "(Constant)");
1241                         break;
1242                 case PROP_SPHERE:
1243                         strcpy(t->proptext, "(Sphere)");
1244                         break;
1245                 case PROP_RANDOM:
1246                         strcpy(t->proptext, "(Random)");
1247                         break;
1248                 default:
1249                         strcpy(t->proptext, "");
1250                 }
1251         }
1252         else {
1253                 for(i = 0 ; i < t->total; i++, td++) {
1254                         td->factor = 1.0;
1255                 }
1256                 strcpy(t->proptext, "");
1257         }
1258 }
1259
1260 TransInfo *BIF_GetTransInfo()
1261 {
1262         return NULL;
1263 }
1264
1265 float get_drawsize(ARegion *ar, float *co)
1266 {
1267         RegionView3D *rv3d= ar->regiondata;
1268         float size, vec[3], len1, len2;
1269         
1270         /* size calculus, depending ortho/persp settings, like initgrabz() */
1271         size= rv3d->persmat[0][3]*co[0]+ rv3d->persmat[1][3]*co[1]+ rv3d->persmat[2][3]*co[2]+ rv3d->persmat[3][3];
1272         
1273         VECCOPY(vec, rv3d->persinv[0]);
1274         len1= Normalize(vec);
1275         VECCOPY(vec, rv3d->persinv[1]);
1276         len2= Normalize(vec);
1277         
1278         size*= 0.01f*(len1>len2?len1:len2);
1279
1280         /* correct for window size to make widgets appear fixed size */
1281         if(ar->winx > ar->winy) size*= 1000.0f/(float)ar->winx;
1282         else size*= 1000.0f/(float)ar->winy;
1283
1284         return size;
1285 }