2.5/Paint:
[blender.git] / source / blender / editors / space_view3d / view3d_view.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) 2008 Blender Foundation.
21  * All rights reserved.
22  *
23  * 
24  * Contributor(s): Blender Foundation
25  *
26  * ***** END GPL LICENSE BLOCK *****
27  */
28
29 #include <string.h>
30 #include <stdio.h>
31 #include <math.h>
32 #include <float.h>
33
34 #include "DNA_action_types.h"
35 #include "DNA_armature_types.h"
36 #include "DNA_camera_types.h"
37 #include "DNA_lamp_types.h"
38 #include "DNA_object_types.h"
39 #include "DNA_space_types.h"
40 #include "DNA_scene_types.h"
41 #include "DNA_screen_types.h"
42 #include "DNA_userdef_types.h"
43 #include "DNA_view3d_types.h"
44 #include "DNA_world_types.h"
45
46 #include "MEM_guardedalloc.h"
47
48 #include "BLI_arithb.h"
49 #include "BLI_blenlib.h"
50 #include "BLI_editVert.h"
51 #include "BLI_rand.h"
52
53 #include "BKE_anim.h"
54 #include "BKE_action.h"
55 #include "BKE_context.h"
56 #include "BKE_object.h"
57 #include "BKE_global.h"
58 #include "BKE_main.h"
59 #include "BKE_scene.h"
60 #include "BKE_screen.h"
61 #include "BKE_utildefines.h"
62
63 #include "RE_pipeline.h"        // make_stars
64
65 #include "BIF_gl.h"
66 #include "BIF_glutil.h"
67
68 #include "WM_api.h"
69 #include "WM_types.h"
70
71 #include "ED_mesh.h"
72 #include "ED_screen.h"
73 #include "ED_view3d.h"
74 #include "ED_armature.h"
75
76 #include "UI_interface.h"
77 #include "UI_resources.h"
78 #include "UI_view2d.h"
79
80 #include "GPU_draw.h"
81
82 #include "PIL_time.h" /* smoothview */
83
84 #include "view3d_intern.h"      // own include
85
86 /* use this call when executing an operator,
87    event system doesn't set for each event the
88    opengl drawing context */
89 void view3d_operator_needs_opengl(const bContext *C)
90 {
91         ARegion *ar= CTX_wm_region(C);
92
93         /* for debugging purpose, context should always be OK */
94         if(ar->regiontype!=RGN_TYPE_WINDOW)
95                 printf("view3d_operator_needs_opengl error, wrong region\n");
96         else {
97                 RegionView3D *rv3d= ar->regiondata;
98                 
99                 wmSubWindowSet(CTX_wm_window(C), ar->swinid);
100                 glMatrixMode(GL_PROJECTION);
101                 wmLoadMatrix(rv3d->winmat);
102                 glMatrixMode(GL_MODELVIEW);
103                 wmLoadMatrix(rv3d->viewmat);
104         }
105 }
106
107 float *give_cursor(Scene *scene, View3D *v3d)
108 {
109         if(v3d && v3d->localview) return v3d->cursor;
110         else return scene->cursor;
111 }
112
113
114 /* Gets the lens and clipping values from a camera of lamp type object */
115 static void object_lens_clip_settings(Object *ob, float *lens, float *clipsta, float *clipend)
116 {       
117         if (!ob) return;
118         
119         if(ob->type==OB_LAMP ) {
120                 Lamp *la = ob->data;
121                 if (lens) {
122                         float x1, fac;
123                         fac= cos( M_PI*la->spotsize/360.0);
124                         x1= saacos(fac);
125                         *lens= 16.0*fac/sin(x1);
126                 }
127                 if (clipsta)    *clipsta= la->clipsta;
128                 if (clipend)    *clipend= la->clipend;
129         }
130         else if(ob->type==OB_CAMERA) {
131                 Camera *cam= ob->data;
132                 if (lens)               *lens= cam->lens;
133                 if (clipsta)    *clipsta= cam->clipsta;
134                 if (clipend)    *clipend= cam->clipend;
135         }
136         else {
137                 if (lens)               *lens= 35.0f;
138         }
139 }
140
141
142 /* Gets the view trasnformation from a camera
143 * currently dosnt take camzoom into account
144
145 * The dist is not modified for this function, if NULL its assimed zero
146 * */
147 static void view_settings_from_ob(Object *ob, float *ofs, float *quat, float *dist, float *lens)
148 {       
149         float bmat[4][4];
150         float imat[4][4];
151         float tmat[3][3];
152         
153         if (!ob) return;
154         
155         /* Offset */
156         if (ofs) {
157                 VECCOPY(ofs, ob->obmat[3]);
158                 VecMulf(ofs, -1.0f); /*flip the vector*/
159         }
160         
161         /* Quat */
162         if (quat) {
163                 Mat4CpyMat4(bmat, ob->obmat);
164                 Mat4Ortho(bmat);
165                 Mat4Invert(imat, bmat);
166                 Mat3CpyMat4(tmat, imat);
167                 Mat3ToQuat(tmat, quat);
168         }
169         
170         if (dist) {
171                 float vec[3];
172                 Mat3CpyMat4(tmat, ob->obmat);
173                 
174                 vec[0]= vec[1] = 0.0;
175                 vec[2]= -(*dist);
176                 Mat3MulVecfl(tmat, vec);
177                 VecSubf(ofs, ofs, vec);
178         }
179         
180         /* Lens */
181         if (lens)
182                 object_lens_clip_settings(ob, lens, NULL, NULL);
183 }
184
185
186 /* ****************** smooth view operator ****************** */
187
188 struct SmoothViewStore {
189         float orig_dist, new_dist;
190         float orig_lens, new_lens;
191         float orig_quat[4], new_quat[4];
192         float orig_ofs[3], new_ofs[3];
193         
194         int to_camera, orig_view;
195         
196         double time_allowed;
197 };
198
199 /* will start timer if appropriate */
200 /* the arguments are the desired situation */
201 void smooth_view(bContext *C, Object *oldcamera, Object *camera, float *ofs, float *quat, float *dist, float *lens)
202 {
203         View3D *v3d = CTX_wm_view3d(C);
204         RegionView3D *rv3d= CTX_wm_region_view3d(C);
205         struct SmoothViewStore sms;
206         
207         /* initialize sms */
208         memset(&sms,0,sizeof(struct SmoothViewStore));
209         VECCOPY(sms.new_ofs, rv3d->ofs);
210         QUATCOPY(sms.new_quat, rv3d->viewquat);
211         sms.new_dist= rv3d->dist;
212         sms.new_lens= v3d->lens;
213         sms.to_camera= 0;
214         
215         /* store the options we want to end with */
216         if(ofs) VECCOPY(sms.new_ofs, ofs);
217         if(quat) QUATCOPY(sms.new_quat, quat);
218         if(dist) sms.new_dist= *dist;
219         if(lens) sms.new_lens= *lens;
220         
221         if (camera) {
222                 view_settings_from_ob(camera, sms.new_ofs, sms.new_quat, &sms.new_dist, &sms.new_lens);
223                 sms.to_camera= 1; /* restore view3d values in end */
224         }
225         
226         if (C && U.smooth_viewtx) {
227                 int changed = 0; /* zero means no difference */
228                 
229                 if (sms.new_dist != rv3d->dist)
230                         changed = 1;
231                 if (sms.new_lens != v3d->lens)
232                         changed = 1;
233                 
234                 if ((sms.new_ofs[0]!=rv3d->ofs[0]) ||
235                         (sms.new_ofs[1]!=rv3d->ofs[1]) ||
236                         (sms.new_ofs[2]!=rv3d->ofs[2]) )
237                         changed = 1;
238                 
239                 if ((sms.new_quat[0]!=rv3d->viewquat[0]) ||
240                         (sms.new_quat[1]!=rv3d->viewquat[1]) ||
241                         (sms.new_quat[2]!=rv3d->viewquat[2]) ||
242                         (sms.new_quat[3]!=rv3d->viewquat[3]) )
243                         changed = 1;
244                 
245                 /* The new view is different from the old one
246                         * so animate the view */
247                 if (changed) {
248                         
249                         sms.time_allowed= (double)U.smooth_viewtx / 1000.0;
250                         
251                         /* if this is view rotation only
252                                 * we can decrease the time allowed by
253                                 * the angle between quats 
254                                 * this means small rotations wont lag */
255                         if (quat && !ofs && !dist) {
256                                 float vec1[3], vec2[3];
257                                 
258                                 VECCOPY(vec1, sms.new_quat);
259                                 VECCOPY(vec2, sms.orig_quat);
260                                 Normalize(vec1);
261                                 Normalize(vec2);
262                                 /* scale the time allowed by the rotation */
263                                 sms.time_allowed *= NormalizedVecAngle2(vec1, vec2)/(M_PI/2); 
264                         }
265                         
266                         /* original values */
267                         if (oldcamera) {
268                                 sms.orig_dist= rv3d->dist; // below function does weird stuff with it...
269                                 view_settings_from_ob(oldcamera, sms.orig_ofs, sms.orig_quat, &sms.orig_dist, &sms.orig_lens);
270                         }
271                         else {
272                                 VECCOPY(sms.orig_ofs, rv3d->ofs);
273                                 QUATCOPY(sms.orig_quat, rv3d->viewquat);
274                                 sms.orig_dist= rv3d->dist;
275                                 sms.orig_lens= v3d->lens;
276                         }
277                         /* grid draw as floor */
278                         sms.orig_view= rv3d->view;
279                         rv3d->view= 0;
280                         
281                         /* ensure it shows correct */
282                         if(sms.to_camera) rv3d->persp= V3D_PERSP;
283                         
284                         /* keep track of running timer! */
285                         if(rv3d->sms==NULL)
286                                 rv3d->sms= MEM_mallocN(sizeof(struct SmoothViewStore), "smoothview v3d");
287                         *rv3d->sms= sms;
288                         if(rv3d->smooth_timer)
289                                 WM_event_remove_window_timer(CTX_wm_window(C), rv3d->smooth_timer);
290                         /* TIMER1 is hardcoded in keymap */
291                         rv3d->smooth_timer= WM_event_add_window_timer(CTX_wm_window(C), TIMER1, 1.0/30.0);      /* max 30 frs/sec */
292                         
293                         return;
294                 }
295         }
296         
297         /* if we get here nothing happens */
298         if(sms.to_camera==0) {
299                 VECCOPY(rv3d->ofs, sms.new_ofs);
300                 QUATCOPY(rv3d->viewquat, sms.new_quat);
301                 rv3d->dist = sms.new_dist;
302                 v3d->lens = sms.new_lens;
303         }
304         ED_region_tag_redraw(CTX_wm_region(C));
305 }
306
307 /* only meant for timer usage */
308 static int view3d_smoothview_invoke(bContext *C, wmOperator *op, wmEvent *event)
309 {
310         View3D *v3d = CTX_wm_view3d(C);
311         RegionView3D *rv3d= CTX_wm_region_view3d(C);
312         struct SmoothViewStore *sms= rv3d->sms;
313         double step, step_inv;
314         
315         /* escape if not our timer */
316         if(rv3d->smooth_timer==NULL || rv3d->smooth_timer!=event->customdata)
317                 return OPERATOR_PASS_THROUGH;
318         
319         step =  (rv3d->smooth_timer->duration)/sms->time_allowed;
320         
321         /* end timer */
322         if(step >= 1.0f) {
323                 
324                 /* if we went to camera, store the original */
325                 if(sms->to_camera) {
326                         rv3d->persp= V3D_CAMOB;
327                         VECCOPY(rv3d->ofs, sms->orig_ofs);
328                         QUATCOPY(rv3d->viewquat, sms->orig_quat);
329                         rv3d->dist = sms->orig_dist;
330                         v3d->lens = sms->orig_lens;
331                 }
332                 else {
333                         VECCOPY(rv3d->ofs, sms->new_ofs);
334                         QUATCOPY(rv3d->viewquat, sms->new_quat);
335                         rv3d->dist = sms->new_dist;
336                         v3d->lens = sms->new_lens;
337                 }
338                 rv3d->view= sms->orig_view;
339                 
340                 MEM_freeN(rv3d->sms);
341                 rv3d->sms= NULL;
342                 
343                 WM_event_remove_window_timer(CTX_wm_window(C), rv3d->smooth_timer);
344                 rv3d->smooth_timer= NULL;
345         }
346         else {
347                 int i;
348                 
349                 /* ease in/out */
350                 if (step < 0.5) step = (float)pow(step*2, 2)/2;
351                 else                    step = (float)1-(pow(2*(1-step),2)/2);
352
353                 step_inv = 1.0-step;
354
355                 for (i=0; i<3; i++)
356                         rv3d->ofs[i] = sms->new_ofs[i]*step + sms->orig_ofs[i]*step_inv;
357
358                 QuatInterpol(rv3d->viewquat, sms->orig_quat, sms->new_quat, step);
359                 
360                 rv3d->dist = sms->new_dist*step + sms->orig_dist*step_inv;
361                 v3d->lens = sms->new_lens*step + sms->orig_lens*step_inv;
362         }
363         
364         ED_region_tag_redraw(CTX_wm_region(C));
365         
366         return OPERATOR_FINISHED;
367 }
368
369 void VIEW3D_OT_smoothview(wmOperatorType *ot)
370 {
371         
372         /* identifiers */
373         ot->name= "Smooth View";
374         ot->idname= "VIEW3D_OT_smoothview";
375         
376         /* api callbacks */
377         ot->invoke= view3d_smoothview_invoke;
378         
379         ot->poll= ED_operator_view3d_active;
380 }
381
382 static int view3d_setcameratoview_exec(bContext *C, wmOperator *op)
383 {
384         View3D *v3d = CTX_wm_view3d(C);
385         RegionView3D *rv3d= CTX_wm_region_view3d(C);
386         Object *ob;
387         float dvec[3];
388         
389         ob= v3d->camera;
390         dvec[0]= rv3d->dist*rv3d->viewinv[2][0];
391         dvec[1]= rv3d->dist*rv3d->viewinv[2][1];
392         dvec[2]= rv3d->dist*rv3d->viewinv[2][2];
393         
394         VECCOPY(ob->loc, dvec);
395         VecSubf(ob->loc, ob->loc, v3d->ofs);
396         rv3d->viewquat[0]= -rv3d->viewquat[0];
397
398         QuatToEul(rv3d->viewquat, ob->rot);
399         rv3d->viewquat[0]= -rv3d->viewquat[0];
400         
401         ob->recalc= OB_RECALC_OB;
402         
403         WM_event_add_notifier(C, NC_OBJECT|ND_TRANSFORM, CTX_data_scene(C));
404         
405         return OPERATOR_FINISHED;
406
407 }
408
409 void VIEW3D_OT_setcameratoview(wmOperatorType *ot)
410 {
411         
412         /* identifiers */
413         ot->name= "Align Camera To View";
414         ot->idname= "VIEW3D_OT_camera_to_view";
415         
416         /* api callbacks */
417         ot->exec= view3d_setcameratoview_exec;  
418         ot->poll= ED_operator_view3d_active;
419         
420         /* flags */
421         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
422 }
423
424 /* ********************************** */
425
426 /* create intersection coordinates in view Z direction at mouse coordinates */
427 void viewline(ARegion *ar, View3D *v3d, short mval[2], float ray_start[3], float ray_end[3])
428 {
429         RegionView3D *rv3d= ar->regiondata;
430         float vec[4];
431         
432         if(rv3d->persp != V3D_ORTHO){
433                 vec[0]= 2.0f * mval[0] / ar->winx - 1;
434                 vec[1]= 2.0f * mval[1] / ar->winy - 1;
435                 vec[2]= -1.0f;
436                 vec[3]= 1.0f;
437                 
438                 Mat4MulVec4fl(rv3d->persinv, vec);
439                 VecMulf(vec, 1.0f / vec[3]);
440                 
441                 VECCOPY(ray_start, rv3d->viewinv[3]);
442                 VECSUB(vec, vec, ray_start);
443                 Normalize(vec);
444                 
445                 VECADDFAC(ray_start, rv3d->viewinv[3], vec, v3d->near);
446                 VECADDFAC(ray_end, rv3d->viewinv[3], vec, v3d->far);
447         }
448         else {
449                 vec[0] = 2.0f * mval[0] / ar->winx - 1;
450                 vec[1] = 2.0f * mval[1] / ar->winy - 1;
451                 vec[2] = 0.0f;
452                 vec[3] = 1.0f;
453                 
454                 Mat4MulVec4fl(rv3d->persinv, vec);
455                 
456                 VECADDFAC(ray_start, vec, rv3d->viewinv[2],  1000.0f);
457                 VECADDFAC(ray_end, vec, rv3d->viewinv[2], -1000.0f);
458         }
459 }
460
461 /* create intersection ray in view Z direction at mouse coordinates */
462 void viewray(ARegion *ar, View3D *v3d, short mval[2], float ray_start[3], float ray_normal[3])
463 {
464         float ray_end[3];
465         
466         viewline(ar, v3d, mval, ray_start, ray_end);
467         VecSubf(ray_normal, ray_end, ray_start);
468         Normalize(ray_normal);
469 }
470
471
472 void initgrabz(RegionView3D *rv3d, float x, float y, float z)
473 {
474         if(rv3d==NULL) return;
475         rv3d->zfac= rv3d->persmat[0][3]*x+ rv3d->persmat[1][3]*y+ rv3d->persmat[2][3]*z+ rv3d->persmat[3][3];
476         
477         /* if x,y,z is exactly the viewport offset, zfac is 0 and we don't want that 
478                 * (accounting for near zero values)
479                 * */
480         if (rv3d->zfac < 1.e-6f && rv3d->zfac > -1.e-6f) rv3d->zfac = 1.0f;
481         
482         /* Negative zfac means x, y, z was behind the camera (in perspective).
483                 * This gives flipped directions, so revert back to ok default case.
484         */
485         if (rv3d->zfac < 0.0f) rv3d->zfac = 1.0f;
486 }
487
488 /* always call initgrabz */
489 void window_to_3d(ARegion *ar, float *vec, short mx, short my)
490 {
491         RegionView3D *rv3d= ar->regiondata;
492         
493         float dx= ((float)(mx-(ar->winx/2)))*rv3d->zfac/(ar->winx/2);
494         float dy= ((float)(my-(ar->winy/2)))*rv3d->zfac/(ar->winy/2);
495         
496         float fz= rv3d->persmat[0][3]*vec[0]+ rv3d->persmat[1][3]*vec[1]+ rv3d->persmat[2][3]*vec[2]+ rv3d->persmat[3][3];
497         fz= fz/rv3d->zfac;
498         
499         vec[0]= (rv3d->persinv[0][0]*dx + rv3d->persinv[1][0]*dy+ rv3d->persinv[2][0]*fz)-rv3d->ofs[0];
500         vec[1]= (rv3d->persinv[0][1]*dx + rv3d->persinv[1][1]*dy+ rv3d->persinv[2][1]*fz)-rv3d->ofs[1];
501         vec[2]= (rv3d->persinv[0][2]*dx + rv3d->persinv[1][2]*dy+ rv3d->persinv[2][2]*fz)-rv3d->ofs[2];
502         
503 }
504
505 /* always call initgrabz */
506 /* only to detect delta motion */
507 void window_to_3d_delta(ARegion *ar, float *vec, short mx, short my)
508 {
509         RegionView3D *rv3d= ar->regiondata;
510         float dx, dy;
511         
512         dx= 2.0f*mx*rv3d->zfac/ar->winx;
513         dy= 2.0f*my*rv3d->zfac/ar->winy;
514         
515         vec[0]= (rv3d->persinv[0][0]*dx + rv3d->persinv[1][0]*dy);
516         vec[1]= (rv3d->persinv[0][1]*dx + rv3d->persinv[1][1]*dy);
517         vec[2]= (rv3d->persinv[0][2]*dx + rv3d->persinv[1][2]*dy);
518 }
519
520 float read_cached_depth(ViewContext *vc, int x, int y)
521 {
522         ViewDepths *vd = vc->rv3d->depths;
523                 
524         x -= vc->ar->winrct.xmin;
525         y -= vc->ar->winrct.ymin;
526
527         if(vd && vd->depths && x > 0 && y > 0 && x < vd->w && y < vd->h)
528                 return vd->depths[y * vd->w + x];
529         else
530                 return 1;
531 }
532
533 void request_depth_update(RegionView3D *rv3d)
534 {
535         if(rv3d->depths)
536                 rv3d->depths->damaged= 1;
537 }
538
539 void view3d_get_object_project_mat(RegionView3D *rv3d, Object *ob, float pmat[4][4])
540 {
541         float vmat[4][4];
542         
543         Mat4MulMat4(vmat, ob->obmat, rv3d->viewmat);
544         Mat4MulMat4(pmat, vmat, rv3d->winmat);
545 }
546
547 /* Uses window coordinates (x,y) and depth component z to find a point in
548    modelspace */
549 void view3d_unproject(bglMats *mats, float out[3], const short x, const short y, const float z)
550 {
551         double ux, uy, uz;
552
553         gluUnProject(x,y,z, mats->modelview, mats->projection,
554                      (GLint *)mats->viewport, &ux, &uy, &uz );
555         out[0] = ux;
556         out[1] = uy;
557         out[2] = uz;
558 }
559
560 /* use above call to get projecting mat */
561 void view3d_project_float(ARegion *ar, float *vec, float *adr, float mat[4][4])
562 {
563         float vec4[4];
564         
565         adr[0]= IS_CLIPPED;
566         VECCOPY(vec4, vec);
567         vec4[3]= 1.0;
568         
569         Mat4MulVec4fl(mat, vec4);
570         
571         if( vec4[3]>FLT_EPSILON ) {
572                 adr[0] = (float)(ar->winx/2.0f)+(ar->winx/2.0f)*vec4[0]/vec4[3];        
573                 adr[1] = (float)(ar->winy/2.0f)+(ar->winy/2.0f)*vec4[1]/vec4[3];
574         } else {
575                 adr[0] = adr[1] = 0.0f;
576         }
577 }
578
579 int boundbox_clip(RegionView3D *rv3d, float obmat[][4], BoundBox *bb)
580 {
581         /* return 1: draw */
582         
583         float mat[4][4];
584         float vec[4], min, max;
585         int a, flag= -1, fl;
586         
587         if(bb==NULL) return 1;
588         if(bb->flag & OB_BB_DISABLED) return 1;
589         
590         Mat4MulMat4(mat, obmat, rv3d->persmat);
591         
592         for(a=0; a<8; a++) {
593                 VECCOPY(vec, bb->vec[a]);
594                 vec[3]= 1.0;
595                 Mat4MulVec4fl(mat, vec);
596                 max= vec[3];
597                 min= -vec[3];
598                 
599                 fl= 0;
600                 if(vec[0] < min) fl+= 1;
601                 if(vec[0] > max) fl+= 2;
602                 if(vec[1] < min) fl+= 4;
603                 if(vec[1] > max) fl+= 8;
604                 if(vec[2] < min) fl+= 16;
605                 if(vec[2] > max) fl+= 32;
606                 
607                 flag &= fl;
608                 if(flag==0) return 1;
609         }
610         
611         return 0;
612 }
613
614 void project_short(ARegion *ar, float *vec, short *adr) /* clips */
615 {
616         RegionView3D *rv3d= ar->regiondata;
617         float fx, fy, vec4[4];
618         
619         adr[0]= IS_CLIPPED;
620         
621         if(rv3d->rflag & RV3D_CLIPPING) {
622                 if(view3d_test_clipping(rv3d, vec))
623                         return;
624         }
625         
626         VECCOPY(vec4, vec);
627         vec4[3]= 1.0;
628         Mat4MulVec4fl(rv3d->persmat, vec4);
629         
630         if( vec4[3]>BL_NEAR_CLIP ) {    /* 0.001 is the NEAR clipping cutoff for picking */
631                 fx= (ar->winx/2)*(1 + vec4[0]/vec4[3]);
632                 
633                 if( fx>0 && fx<ar->winx) {
634                         
635                         fy= (ar->winy/2)*(1 + vec4[1]/vec4[3]);
636                         
637                         if(fy>0.0 && fy< (float)ar->winy) {
638                                 adr[0]= (short)floor(fx); 
639                                 adr[1]= (short)floor(fy);
640                         }
641                 }
642         }
643 }
644
645 void project_int(ARegion *ar, float *vec, int *adr)
646 {
647         RegionView3D *rv3d= ar->regiondata;
648         float fx, fy, vec4[4];
649         
650         adr[0]= (int)2140000000.0f;
651         VECCOPY(vec4, vec);
652         vec4[3]= 1.0;
653         
654         Mat4MulVec4fl(rv3d->persmat, vec4);
655         
656         if( vec4[3]>BL_NEAR_CLIP ) {    /* 0.001 is the NEAR clipping cutoff for picking */
657                 fx= (ar->winx/2)*(1 + vec4[0]/vec4[3]);
658                 
659                 if( fx>-2140000000.0f && fx<2140000000.0f) {
660                         fy= (ar->winy/2)*(1 + vec4[1]/vec4[3]);
661                         
662                         if(fy>-2140000000.0f && fy<2140000000.0f) {
663                                 adr[0]= (int)floor(fx); 
664                                 adr[1]= (int)floor(fy);
665                         }
666                 }
667         }
668 }
669
670 void project_int_noclip(ARegion *ar, float *vec, int *adr)
671 {
672         RegionView3D *rv3d= ar->regiondata;
673         float fx, fy, vec4[4];
674         
675         VECCOPY(vec4, vec);
676         vec4[3]= 1.0;
677         
678         Mat4MulVec4fl(rv3d->persmat, vec4);
679         
680         if( fabs(vec4[3]) > BL_NEAR_CLIP ) {
681                 fx = (ar->winx/2)*(1 + vec4[0]/vec4[3]);
682                 fy = (ar->winy/2)*(1 + vec4[1]/vec4[3]);
683                 
684                 adr[0] = (int)floor(fx); 
685                 adr[1] = (int)floor(fy);
686         }
687         else
688         {
689                 adr[0] = ar->winx / 2;
690                 adr[1] = ar->winy / 2;
691         }
692 }
693
694 void project_short_noclip(ARegion *ar, float *vec, short *adr)
695 {
696         RegionView3D *rv3d= ar->regiondata;
697         float fx, fy, vec4[4];
698         
699         adr[0]= IS_CLIPPED;
700         VECCOPY(vec4, vec);
701         vec4[3]= 1.0;
702         
703         Mat4MulVec4fl(rv3d->persmat, vec4);
704         
705         if( vec4[3]>BL_NEAR_CLIP ) {    /* 0.001 is the NEAR clipping cutoff for picking */
706                 fx= (ar->winx/2)*(1 + vec4[0]/vec4[3]);
707                 
708                 if( fx>-32700 && fx<32700) {
709                         
710                         fy= (ar->winy/2)*(1 + vec4[1]/vec4[3]);
711                         
712                         if(fy>-32700.0 && fy<32700.0) {
713                                 adr[0]= (short)floor(fx); 
714                                 adr[1]= (short)floor(fy);
715                         }
716                 }
717         }
718 }
719
720 void project_float(ARegion *ar, float *vec, float *adr)
721 {
722         RegionView3D *rv3d= ar->regiondata;
723         float vec4[4];
724         
725         adr[0]= IS_CLIPPED;
726         VECCOPY(vec4, vec);
727         vec4[3]= 1.0;
728         
729         Mat4MulVec4fl(rv3d->persmat, vec4);
730         
731         if( vec4[3]>BL_NEAR_CLIP ) {
732                 adr[0] = (float)(ar->winx/2.0)+(ar->winx/2.0)*vec4[0]/vec4[3];  
733                 adr[1] = (float)(ar->winy/2.0)+(ar->winy/2.0)*vec4[1]/vec4[3];
734         }
735 }
736
737 void project_float_noclip(ARegion *ar, float *vec, float *adr)
738 {
739         RegionView3D *rv3d= ar->regiondata;
740         float vec4[4];
741         
742         VECCOPY(vec4, vec);
743         vec4[3]= 1.0;
744         
745         Mat4MulVec4fl(rv3d->persmat, vec4);
746         
747         if( fabs(vec4[3]) > BL_NEAR_CLIP ) {
748                 adr[0] = (float)(ar->winx/2.0)+(ar->winx/2.0)*vec4[0]/vec4[3];  
749                 adr[1] = (float)(ar->winy/2.0)+(ar->winy/2.0)*vec4[1]/vec4[3];
750         }
751         else
752         {
753                 adr[0] = ar->winx / 2.0f;
754                 adr[1] = ar->winy / 2.0f;
755         }
756 }
757
758 int get_view3d_ortho(View3D *v3d, RegionView3D *rv3d)
759 {
760   Camera *cam;
761   
762   if(rv3d->persp==V3D_CAMOB) {
763       if(v3d->camera && v3d->camera->type==OB_CAMERA) {
764           cam= v3d->camera->data;
765
766           if(cam && cam->type==CAM_ORTHO)
767               return 1;
768           else
769               return 0;
770       }
771       else
772           return 0;
773   }
774   
775   if(rv3d->persp==V3D_ORTHO)
776       return 1;
777
778   return 0;
779 }
780
781 /* also exposed in previewrender.c */
782 int get_view3d_viewplane(View3D *v3d, RegionView3D *rv3d, int winxi, int winyi, rctf *viewplane, float *clipsta, float *clipend, float *pixsize)
783 {
784         Camera *cam=NULL;
785         float lens, fac, x1, y1, x2, y2;
786         float winx= (float)winxi, winy= (float)winyi;
787         int orth= 0;
788         
789         lens= v3d->lens;        
790         
791         *clipsta= v3d->near;
792         *clipend= v3d->far;
793         
794         if(rv3d->persp==V3D_CAMOB) {
795                 if(v3d->camera) {
796                         if(v3d->camera->type==OB_LAMP ) {
797                                 Lamp *la;
798                                 
799                                 la= v3d->camera->data;
800                                 fac= cos( M_PI*la->spotsize/360.0);
801                                 
802                                 x1= saacos(fac);
803                                 lens= 16.0*fac/sin(x1);
804                                 
805                                 *clipsta= la->clipsta;
806                                 *clipend= la->clipend;
807                         }
808                         else if(v3d->camera->type==OB_CAMERA) {
809                                 cam= v3d->camera->data;
810                                 lens= cam->lens;
811                                 *clipsta= cam->clipsta;
812                                 *clipend= cam->clipend;
813                         }
814                 }
815         }
816         
817         if(rv3d->persp==V3D_ORTHO) {
818                 if(winx>winy) x1= -rv3d->dist;
819                 else x1= -winx*rv3d->dist/winy;
820                 x2= -x1;
821                 
822                 if(winx>winy) y1= -winy*rv3d->dist/winx;
823                 else y1= -rv3d->dist;
824                 y2= -y1;
825                 
826                 *clipend *= 0.5;        // otherwise too extreme low zbuffer quality
827                 *clipsta= - *clipend;
828                 orth= 1;
829         }
830         else {
831                 /* fac for zoom, also used for camdx */
832                 if(rv3d->persp==V3D_CAMOB) {
833                         fac= (1.41421+( (float)rv3d->camzoom )/50.0);
834                         fac*= fac;
835                 }
836                 else fac= 2.0;
837                 
838                 /* viewplane size depends... */
839                 if(cam && cam->type==CAM_ORTHO) {
840                         /* ortho_scale == 1 means exact 1 to 1 mapping */
841                         float dfac= 2.0*cam->ortho_scale/fac;
842                         
843                         if(winx>winy) x1= -dfac;
844                         else x1= -winx*dfac/winy;
845                         x2= -x1;
846                         
847                         if(winx>winy) y1= -winy*dfac/winx;
848                         else y1= -dfac;
849                         y2= -y1;
850                         orth= 1;
851                 }
852                 else {
853                         float dfac;
854                         
855                         if(winx>winy) dfac= 64.0/(fac*winx*lens);
856                         else dfac= 64.0/(fac*winy*lens);
857                         
858                         x1= - *clipsta * winx*dfac;
859                         x2= -x1;
860                         y1= - *clipsta * winy*dfac;
861                         y2= -y1;
862                         orth= 0;
863                 }
864                 /* cam view offset */
865                 if(cam) {
866                         float dx= 0.5*fac*rv3d->camdx*(x2-x1);
867                         float dy= 0.5*fac*rv3d->camdy*(y2-y1);
868                         x1+= dx;
869                         x2+= dx;
870                         y1+= dy;
871                         y2+= dy;
872                 }
873         }
874         
875         if(pixsize) {
876                 float viewfac;
877                 
878                 if(orth) {
879                         viewfac= (winx >= winy)? winx: winy;
880                         *pixsize= 1.0f/viewfac;
881                 }
882                 else {
883                         viewfac= (((winx >= winy)? winx: winy)*lens)/32.0;
884                         *pixsize= *clipsta/viewfac;
885                 }
886         }
887         
888         viewplane->xmin= x1;
889         viewplane->ymin= y1;
890         viewplane->xmax= x2;
891         viewplane->ymax= y2;
892         
893         return orth;
894 }
895
896 void setwinmatrixview3d(ARegion *ar, View3D *v3d, rctf *rect)           /* rect: for picking */
897 {
898         RegionView3D *rv3d= ar->regiondata;
899         rctf viewplane;
900         float clipsta, clipend, x1, y1, x2, y2;
901         int orth;
902         
903         orth= get_view3d_viewplane(v3d, rv3d, ar->winx, ar->winy, &viewplane, &clipsta, &clipend, NULL);
904         //      printf("%d %d %f %f %f %f %f %f\n", winx, winy, viewplane.xmin, viewplane.ymin, viewplane.xmax, viewplane.ymax, clipsta, clipend);
905         x1= viewplane.xmin;
906         y1= viewplane.ymin;
907         x2= viewplane.xmax;
908         y2= viewplane.ymax;
909         
910         if(rect) {              /* picking */
911                 rect->xmin/= (float)ar->winx;
912                 rect->xmin= x1+rect->xmin*(x2-x1);
913                 rect->ymin/= (float)ar->winy;
914                 rect->ymin= y1+rect->ymin*(y2-y1);
915                 rect->xmax/= (float)ar->winx;
916                 rect->xmax= x1+rect->xmax*(x2-x1);
917                 rect->ymax/= (float)ar->winy;
918                 rect->ymax= y1+rect->ymax*(y2-y1);
919                 
920                 if(orth) wmOrtho(rect->xmin, rect->xmax, rect->ymin, rect->ymax, -clipend, clipend);
921                 else wmFrustum(rect->xmin, rect->xmax, rect->ymin, rect->ymax, clipsta, clipend);
922                 
923         }
924         else {
925                 if(orth) wmOrtho(x1, x2, y1, y2, clipsta, clipend);
926                 else wmFrustum(x1, x2, y1, y2, clipsta, clipend);
927         }
928
929         /* not sure what this was for? (ton) */
930         glMatrixMode(GL_PROJECTION);
931         wmGetMatrix(rv3d->winmat);
932         glMatrixMode(GL_MODELVIEW);
933 }
934
935
936 static void obmat_to_viewmat(View3D *v3d, RegionView3D *rv3d, Object *ob, short smooth)
937 {
938         float bmat[4][4];
939         float tmat[3][3];
940         
941         rv3d->view= 0; /* dont show the grid */
942         
943         Mat4CpyMat4(bmat, ob->obmat);
944         Mat4Ortho(bmat);
945         Mat4Invert(rv3d->viewmat, bmat);
946         
947         /* view quat calculation, needed for add object */
948         Mat3CpyMat4(tmat, rv3d->viewmat);
949         if (smooth) {
950                 float new_quat[4];
951                 if (rv3d->persp==V3D_CAMOB && v3d->camera) {
952                         /* were from a camera view */
953                         
954                         float orig_ofs[3];
955                         float orig_dist= rv3d->dist;
956                         float orig_lens= v3d->lens;
957                         VECCOPY(orig_ofs, rv3d->ofs);
958                         
959                         /* Switch from camera view */
960                         Mat3ToQuat(tmat, new_quat);
961                         
962                         rv3d->persp=V3D_PERSP;
963                         rv3d->dist= 0.0;
964                         
965                         view_settings_from_ob(v3d->camera, rv3d->ofs, NULL, NULL, &v3d->lens);
966                         smooth_view(NULL, NULL, NULL, orig_ofs, new_quat, &orig_dist, &orig_lens); // XXX
967                         
968                         rv3d->persp=V3D_CAMOB; /* just to be polite, not needed */
969                         
970                 } else {
971                         Mat3ToQuat(tmat, new_quat);
972                         smooth_view(NULL, NULL, NULL, NULL, new_quat, NULL, NULL); // XXX
973                 }
974         } else {
975                 Mat3ToQuat(tmat, rv3d->viewquat);
976         }
977 }
978
979 #define QUATSET(a, b, c, d, e)  a[0]=b; a[1]=c; a[2]=d; a[3]=e; 
980
981 static void view3d_viewlock(RegionView3D *rv3d)
982 {
983         switch(rv3d->view) {
984         case V3D_VIEW_BOTTOM :
985                 QUATSET(rv3d->viewquat,0.0, -1.0, 0.0, 0.0);
986                 break;
987                 
988         case V3D_VIEW_BACK:
989                 QUATSET(rv3d->viewquat,0.0, 0.0, (float)-cos(M_PI/4.0), (float)-cos(M_PI/4.0));
990                 break;
991                 
992         case V3D_VIEW_LEFT:
993                 QUATSET(rv3d->viewquat,0.5, -0.5, 0.5, 0.5);
994                 break;
995                 
996         case V3D_VIEW_TOP:
997                 QUATSET(rv3d->viewquat,1.0, 0.0, 0.0, 0.0);
998                 break;
999                 
1000         case V3D_VIEW_FRONT:
1001                 QUATSET(rv3d->viewquat,(float)cos(M_PI/4.0), (float)-sin(M_PI/4.0), 0.0, 0.0);
1002                 break;
1003                 
1004         case V3D_VIEW_RIGHT:
1005                 QUATSET(rv3d->viewquat, 0.5, -0.5, -0.5, -0.5);
1006                 break;
1007         }
1008 }
1009
1010 /* dont set windows active in in here, is used by renderwin too */
1011 void setviewmatrixview3d(Scene *scene, View3D *v3d, RegionView3D *rv3d)
1012 {
1013         if(rv3d->persp==V3D_CAMOB) {        /* obs/camera */
1014                 if(v3d->camera) {
1015                         where_is_object(scene, v3d->camera);    
1016                         obmat_to_viewmat(v3d, rv3d, v3d->camera, 0);
1017                 }
1018                 else {
1019                         QuatToMat4(rv3d->viewquat, rv3d->viewmat);
1020                         rv3d->viewmat[3][2]-= rv3d->dist;
1021                 }
1022         }
1023         else {
1024                 /* should be moved to better initialize later on XXX */
1025                 if(rv3d->viewlock)
1026                         view3d_viewlock(rv3d);
1027                 
1028                 QuatToMat4(rv3d->viewquat, rv3d->viewmat);
1029                 if(rv3d->persp==V3D_PERSP) rv3d->viewmat[3][2]-= rv3d->dist;
1030                 if(v3d->ob_centre) {
1031                         Object *ob= v3d->ob_centre;
1032                         float vec[3];
1033                         
1034                         VECCOPY(vec, ob->obmat[3]);
1035                         if(ob->type==OB_ARMATURE && v3d->ob_centre_bone[0]) {
1036                                 bPoseChannel *pchan= get_pose_channel(ob->pose, v3d->ob_centre_bone);
1037                                 if(pchan) {
1038                                         VECCOPY(vec, pchan->pose_mat[3]);
1039                                         Mat4MulVecfl(ob->obmat, vec);
1040                                 }
1041                         }
1042                         i_translate(-vec[0], -vec[1], -vec[2], rv3d->viewmat);
1043                 }
1044                 else i_translate(rv3d->ofs[0], rv3d->ofs[1], rv3d->ofs[2], rv3d->viewmat);
1045         }
1046 }
1047
1048 /* IGLuint-> GLuint*/
1049 /* Warning: be sure to account for a negative return value
1050 *   This is an error, "Too many objects in select buffer"
1051 *   and no action should be taken (can crash blender) if this happens
1052 */
1053 short view3d_opengl_select(ViewContext *vc, unsigned int *buffer, unsigned int bufsize, rcti *input)
1054 {
1055         Scene *scene= vc->scene;
1056         View3D *v3d= vc->v3d;
1057         ARegion *ar= vc->ar;
1058         rctf rect;
1059         short code, hits;
1060         
1061         G.f |= G_PICKSEL;
1062         
1063         /* case not a border select */
1064         if(input->xmin==input->xmax) {
1065                 rect.xmin= input->xmin-12;      // seems to be default value for bones only now
1066                 rect.xmax= input->xmin+12;
1067                 rect.ymin= input->ymin-12;
1068                 rect.ymax= input->ymin+12;
1069         }
1070         else {
1071                 rect.xmin= input->xmin;
1072                 rect.xmax= input->xmax;
1073                 rect.ymin= input->ymin;
1074                 rect.ymax= input->ymax;
1075         }
1076         
1077         setwinmatrixview3d(ar, v3d, &rect);
1078         Mat4MulMat4(vc->rv3d->persmat, vc->rv3d->viewmat, vc->rv3d->winmat);
1079         
1080         if(v3d->drawtype > OB_WIRE) {
1081                 v3d->zbuf= TRUE;
1082                 glEnable(GL_DEPTH_TEST);
1083         }
1084         
1085         if(vc->rv3d->rflag & RV3D_CLIPPING)
1086                 view3d_set_clipping(vc->rv3d);
1087         
1088         glSelectBuffer( bufsize, (GLuint *)buffer);
1089         glRenderMode(GL_SELECT);
1090         glInitNames();  /* these two calls whatfor? It doesnt work otherwise */
1091         glPushName(-1);
1092         code= 1;
1093         
1094         if(vc->obedit && vc->obedit->type==OB_MBALL) {
1095                 draw_object(scene, ar, v3d, BASACT, DRAW_PICKING|DRAW_CONSTCOLOR);
1096         }
1097         else if((vc->obedit && vc->obedit->type==OB_ARMATURE)) {
1098                 /* if not drawing sketch, draw bones */
1099                 if(!BDR_drawSketchNames(vc)) {
1100                         draw_object(scene, ar, v3d, BASACT, DRAW_PICKING|DRAW_CONSTCOLOR);
1101                 }
1102         }
1103         else {
1104                 Base *base;
1105                 
1106                 v3d->xray= TRUE;        // otherwise it postpones drawing
1107                 for(base= scene->base.first; base; base= base->next) {
1108                         if(base->lay & v3d->lay) {
1109                                 
1110                                 if (base->object->restrictflag & OB_RESTRICT_SELECT)
1111                                         base->selcol= 0;
1112                                 else {
1113                                         base->selcol= code;
1114                                         glLoadName(code);
1115                                         draw_object(scene, ar, v3d, base, DRAW_PICKING|DRAW_CONSTCOLOR);
1116                                         
1117                                         /* we draw group-duplicators for selection too */
1118                                         if((base->object->transflag & OB_DUPLI) && base->object->dup_group) {
1119                                                 ListBase *lb;
1120                                                 DupliObject *dob;
1121                                                 Base tbase;
1122                                                 
1123                                                 tbase.flag= OB_FROMDUPLI;
1124                                                 lb= object_duplilist(scene, base->object);
1125                                                 
1126                                                 for(dob= lb->first; dob; dob= dob->next) {
1127                                                         tbase.object= dob->ob;
1128                                                         Mat4CpyMat4(dob->ob->obmat, dob->mat);
1129                                                         
1130                                                         draw_object(scene, ar, v3d, &tbase, DRAW_PICKING|DRAW_CONSTCOLOR);
1131                                                         
1132                                                         Mat4CpyMat4(dob->ob->obmat, dob->omat);
1133                                                 }
1134                                                 free_object_duplilist(lb);
1135                                         }
1136                                         code++;
1137                                 }                               
1138                         }
1139                 }
1140                 v3d->xray= FALSE;       // restore
1141         }
1142         
1143         glPopName();    /* see above (pushname) */
1144         hits= glRenderMode(GL_RENDER);
1145         
1146         G.f &= ~G_PICKSEL;
1147         setwinmatrixview3d(ar, v3d, NULL);
1148         Mat4MulMat4(vc->rv3d->persmat, vc->rv3d->viewmat, vc->rv3d->winmat);
1149         
1150         if(v3d->drawtype > OB_WIRE) {
1151                 v3d->zbuf= 0;
1152                 glDisable(GL_DEPTH_TEST);
1153         }
1154 // XXX  persp(PERSP_WIN);
1155         
1156         if(vc->rv3d->rflag & RV3D_CLIPPING)
1157                 view3d_clr_clipping();
1158         
1159         if(hits<0) printf("Too many objects in select buffer\n");       // XXX make error message
1160         
1161         return hits;
1162 }
1163
1164 /* ********************** local view operator ******************** */
1165
1166 static unsigned int free_localbit(void)
1167 {
1168         unsigned int lay;
1169         ScrArea *sa;
1170         bScreen *sc;
1171         
1172         lay= 0;
1173         
1174         /* sometimes we loose a localview: when an area is closed */
1175         /* check all areas: which localviews are in use? */
1176         for(sc= G.main->screen.first; sc; sc= sc->id.next) {
1177                 for(sa= sc->areabase.first; sa; sa= sa->next) {
1178                         SpaceLink *sl= sa->spacedata.first;
1179                         for(; sl; sl= sl->next) {
1180                                 if(sl->spacetype==SPACE_VIEW3D) {
1181                                         View3D *v3d= (View3D*) sl;
1182                                         lay |= v3d->lay;
1183                                 }
1184                         }
1185                 }
1186         }
1187         
1188         if( (lay & 0x01000000)==0) return 0x01000000;
1189         if( (lay & 0x02000000)==0) return 0x02000000;
1190         if( (lay & 0x04000000)==0) return 0x04000000;
1191         if( (lay & 0x08000000)==0) return 0x08000000;
1192         if( (lay & 0x10000000)==0) return 0x10000000;
1193         if( (lay & 0x20000000)==0) return 0x20000000;
1194         if( (lay & 0x40000000)==0) return 0x40000000;
1195         if( (lay & 0x80000000)==0) return 0x80000000;
1196         
1197         return 0;
1198 }
1199
1200
1201 static void initlocalview(Scene *scene, ScrArea *sa)
1202 {
1203         View3D *v3d= sa->spacedata.first;
1204         Base *base;
1205         float size = 0.0, min[3], max[3], box[3];
1206         unsigned int locallay;
1207         int ok=0;
1208
1209         if(v3d->localvd) return;
1210
1211         INIT_MINMAX(min, max);
1212
1213         locallay= free_localbit();
1214
1215         if(locallay==0) {
1216                 printf("Sorry, no more than 8 localviews\n");   // XXX error 
1217                 ok= 0;
1218         }
1219         else {
1220                 if(scene->obedit) {
1221                         minmax_object(scene->obedit, min, max);
1222                         
1223                         ok= 1;
1224                 
1225                         BASACT->lay |= locallay;
1226                         scene->obedit->lay= BASACT->lay;
1227                 }
1228                 else {
1229                         for(base= FIRSTBASE; base; base= base->next) {
1230                                 if(TESTBASE(v3d, base))  {
1231                                         minmax_object(base->object, min, max);
1232                                         base->lay |= locallay;
1233                                         base->object->lay= base->lay;
1234                                         ok= 1;
1235                                 }
1236                         }
1237                 }
1238                 
1239                 box[0]= (max[0]-min[0]);
1240                 box[1]= (max[1]-min[1]);
1241                 box[2]= (max[2]-min[2]);
1242                 size= MAX3(box[0], box[1], box[2]);
1243                 if(size<=0.01) size= 0.01;
1244         }
1245         
1246         if(ok) {
1247                 ARegion *ar;
1248                 
1249                 v3d->localvd= MEM_mallocN(sizeof(View3D), "localview");
1250                 
1251                 memcpy(v3d->localvd, v3d, sizeof(View3D));
1252
1253                 for(ar= sa->regionbase.first; ar; ar= ar->next) {
1254                         if(ar->regiontype == RGN_TYPE_WINDOW) {
1255                                 RegionView3D *rv3d= ar->regiondata;
1256
1257                                 rv3d->localvd= MEM_mallocN(sizeof(RegionView3D), "localview region");
1258                                 memcpy(rv3d->localvd, rv3d, sizeof(RegionView3D));
1259                                 
1260                                 rv3d->ofs[0]= -(min[0]+max[0])/2.0;
1261                                 rv3d->ofs[1]= -(min[1]+max[1])/2.0;
1262                                 rv3d->ofs[2]= -(min[2]+max[2])/2.0;
1263
1264                                 rv3d->dist= size;
1265                                 /* perspective should be a bit farther away to look nice */
1266                                 if(rv3d->persp==V3D_ORTHO)
1267                                         rv3d->dist*= 0.7;
1268
1269                                 // correction for window aspect ratio
1270                                 if(ar->winy>2 && ar->winx>2) {
1271                                         float asp= (float)ar->winx/(float)ar->winy;
1272                                         if(asp<1.0) asp= 1.0/asp;
1273                                         rv3d->dist*= asp;
1274                                 }
1275                                 
1276                                 if (rv3d->persp==V3D_CAMOB) rv3d->persp= V3D_PERSP;
1277                                 
1278                                 v3d->cursor[0]= -rv3d->ofs[0];
1279                                 v3d->cursor[1]= -rv3d->ofs[1];
1280                                 v3d->cursor[2]= -rv3d->ofs[2];
1281                         }
1282                 }
1283                 if (v3d->near> 0.1) v3d->near= 0.1;
1284                 
1285                 v3d->lay= locallay;
1286         }
1287         else {
1288                 /* clear flags */ 
1289                 for(base= FIRSTBASE; base; base= base->next) {
1290                         if( base->lay & locallay ) {
1291                                 base->lay-= locallay;
1292                                 if(base->lay==0) base->lay= v3d->layact;
1293                                 if(base->object != scene->obedit) base->flag |= SELECT;
1294                                 base->object->lay= base->lay;
1295                         }
1296                 }               
1297                 v3d->localview= 0;
1298         }
1299
1300 }
1301
1302 static void restore_localviewdata(ScrArea *sa, int free)
1303 {
1304         ARegion *ar;
1305         View3D *v3d= sa->spacedata.first;
1306         
1307         if(v3d->localvd==NULL) return;
1308         
1309         v3d->near= v3d->localvd->near;
1310         v3d->far= v3d->localvd->far;
1311         v3d->lay= v3d->localvd->lay;
1312         v3d->layact= v3d->localvd->layact;
1313         v3d->drawtype= v3d->localvd->drawtype;
1314         v3d->camera= v3d->localvd->camera;
1315         
1316         if(free) {
1317                 MEM_freeN(v3d->localvd);
1318                 v3d->localvd= NULL;
1319                 v3d->localview= 0;
1320         }
1321         
1322         for(ar= sa->regionbase.first; ar; ar= ar->next) {
1323                 if(ar->regiontype == RGN_TYPE_WINDOW) {
1324                         RegionView3D *rv3d= ar->regiondata;
1325                         
1326                         if(rv3d->localvd) {
1327                                 rv3d->dist= rv3d->localvd->dist;
1328                                 VECCOPY(rv3d->ofs, rv3d->localvd->ofs);
1329                                 QUATCOPY(rv3d->viewquat, rv3d->localvd->viewquat);
1330                                 rv3d->view= rv3d->localvd->view;
1331                                 rv3d->persp= rv3d->localvd->persp;
1332                                 rv3d->camzoom= rv3d->localvd->camzoom;
1333
1334                                 if(free) {
1335                                         MEM_freeN(rv3d->localvd);
1336                                         rv3d->localvd= NULL;
1337                                 }
1338                         }
1339                 }
1340         }
1341 }
1342
1343 static void endlocalview(Scene *scene, ScrArea *sa)
1344 {
1345         View3D *v3d= sa->spacedata.first;
1346         struct Base *base;
1347         unsigned int locallay;
1348         
1349         if(v3d->localvd) {
1350                 
1351                 locallay= v3d->lay & 0xFF000000;
1352                 
1353                 restore_localviewdata(sa, 1); // 1 = free
1354
1355                 /* for when in other window the layers have changed */
1356                 if(v3d->scenelock) v3d->lay= scene->lay;
1357                 
1358                 for(base= FIRSTBASE; base; base= base->next) {
1359                         if( base->lay & locallay ) {
1360                                 base->lay-= locallay;
1361                                 if(base->lay==0) base->lay= v3d->layact;
1362                                 if(base->object != scene->obedit) {
1363                                         base->flag |= SELECT;
1364                                         base->object->flag |= SELECT;
1365                                 }
1366                                 base->object->lay= base->lay;
1367                         }
1368                 }
1369         } 
1370 }
1371
1372 static int localview_exec(bContext *C, wmOperator *unused)
1373 {
1374         View3D *v3d= CTX_wm_view3d(C);
1375         
1376         if(v3d->localvd)
1377                 endlocalview(CTX_data_scene(C), CTX_wm_area(C));
1378         else
1379                 initlocalview(CTX_data_scene(C), CTX_wm_area(C));
1380         
1381         ED_area_tag_redraw(CTX_wm_area(C));
1382         
1383         return OPERATOR_FINISHED;
1384 }
1385
1386 void VIEW3D_OT_localview(wmOperatorType *ot)
1387 {
1388         
1389         /* identifiers */
1390         ot->name= "Local View";
1391         ot->idname= "VIEW3D_OT_localview";
1392         
1393         /* api callbacks */
1394         ot->exec= localview_exec;
1395         
1396         ot->poll= ED_operator_view3d_active;
1397 }
1398
1399 #if GAMEBLENDER == 1
1400
1401 static ListBase queue_back;
1402 static void SaveState(bContext *C)
1403 {
1404         wmWindow *win= CTX_wm_window(C);
1405         Object *obact = CTX_data_active_object(C);
1406         
1407         glPushAttrib(GL_ALL_ATTRIB_BITS);
1408
1409         GPU_state_init();
1410
1411         if(obact && obact->mode & OB_MODE_TEXTURE_PAINT)
1412                 GPU_paint_set_mipmap(1);
1413         
1414         queue_back= win->queue;
1415         
1416         win->queue.first= win->queue.last= NULL;
1417         
1418         //XXX waitcursor(1);
1419 }
1420
1421 static void RestoreState(bContext *C)
1422 {
1423         wmWindow *win= CTX_wm_window(C);
1424         Object *obact = CTX_data_active_object(C);
1425         
1426         if(obact && obact->mode & OB_MODE_TEXTURE_PAINT)
1427                 GPU_paint_set_mipmap(0);
1428
1429         //XXX curarea->win_swap = 0;
1430         //XXX curarea->head_swap=0;
1431         //XXX allqueue(REDRAWVIEW3D, 1);
1432         //XXX allqueue(REDRAWBUTSALL, 0);
1433         //XXX reset_slowparents();
1434         //XXX waitcursor(0);
1435         //XXX G.qual= 0;
1436         
1437         win->queue= queue_back;
1438         
1439         glPopAttrib();
1440 }
1441
1442 /* maybe we need this defined somewhere else */
1443 extern void StartKetsjiShell(struct bContext *C, struct ARegion *ar, int always_use_expand_framing);
1444
1445 #endif // GAMEBLENDER == 1
1446
1447 static int game_engine_exec(bContext *C, wmOperator *unused)
1448 {
1449 #if GAMEBLENDER == 1
1450         Scene *startscene = CTX_data_scene(C);
1451         bScreen *sc= CTX_wm_screen(C);
1452         ScrArea *sa, *prevsa= CTX_wm_area(C);
1453         ARegion *ar, *prevar= CTX_wm_region(C);
1454
1455         sa= prevsa;
1456         if(sa->spacetype != SPACE_VIEW3D) {
1457                 for(sa=sc->areabase.first; sa; sa= sa->next)
1458                         if(sa->spacetype==SPACE_VIEW3D)
1459                                 break;
1460         }
1461
1462         if(!sa)
1463                 return OPERATOR_CANCELLED;
1464         
1465         for(ar=sa->regionbase.first; ar; ar=ar->next)
1466                 if(ar->regiontype == RGN_TYPE_WINDOW)
1467                         break;
1468         
1469         if(!ar)
1470                 return OPERATOR_CANCELLED;
1471         
1472         // bad context switch ..
1473         CTX_wm_area_set(C, sa);
1474         CTX_wm_region_set(C, ar);
1475
1476         view3d_operator_needs_opengl(C);
1477         
1478         SaveState(C);
1479         StartKetsjiShell(C, ar, 1);
1480         RestoreState(C);
1481         
1482         CTX_wm_region_set(C, prevar);
1483         CTX_wm_area_set(C, prevsa);
1484
1485         //XXX restore_all_scene_cfra(scene_cfra_store);
1486         set_scene_bg(startscene);
1487         //XXX scene_update_for_newframe(G.scene, G.scene->lay);
1488         
1489 #else
1490         printf("GameEngine Disabled\n");
1491 #endif
1492         ED_area_tag_redraw(CTX_wm_area(C));
1493         return OPERATOR_FINISHED;
1494 }
1495
1496 void VIEW3D_OT_game_start(wmOperatorType *ot)
1497 {
1498         
1499         /* identifiers */
1500         ot->name= "Start Game Engine";
1501         ot->idname= "VIEW3D_OT_game_start";
1502         
1503         /* api callbacks */
1504         ot->exec= game_engine_exec;
1505         
1506         //ot->poll= ED_operator_view3d_active;
1507 }
1508
1509 /* ************************************** */
1510
1511 void view3d_align_axis_to_vector(View3D *v3d, RegionView3D *rv3d, int axisidx, float vec[3])
1512 {
1513         float alignaxis[3] = {0.0, 0.0, 0.0};
1514         float norm[3], axis[3], angle, new_quat[4];
1515         
1516         if(axisidx > 0) alignaxis[axisidx-1]= 1.0;
1517         else alignaxis[-axisidx-1]= -1.0;
1518         
1519         VECCOPY(norm, vec);
1520         Normalize(norm);
1521         
1522         angle= (float)acos(Inpf(alignaxis, norm));
1523         Crossf(axis, alignaxis, norm);
1524         VecRotToQuat(axis, -angle, new_quat);
1525         
1526         rv3d->view= 0;
1527         
1528         if (rv3d->persp==V3D_CAMOB && v3d->camera) {
1529                 /* switch out of camera view */
1530                 float orig_ofs[3];
1531                 float orig_dist= rv3d->dist;
1532                 float orig_lens= v3d->lens;
1533                 
1534                 VECCOPY(orig_ofs, rv3d->ofs);
1535                 rv3d->persp= V3D_PERSP;
1536                 rv3d->dist= 0.0;
1537                 view_settings_from_ob(v3d->camera, rv3d->ofs, NULL, NULL, &v3d->lens);
1538                 smooth_view(NULL, NULL, NULL, orig_ofs, new_quat, &orig_dist, &orig_lens); // XXX
1539         } else {
1540                 if (rv3d->persp==V3D_CAMOB) rv3d->persp= V3D_PERSP; /* switch out of camera mode */
1541                 smooth_view(NULL, NULL, NULL, NULL, new_quat, NULL, NULL); // XXX
1542         }
1543 }
1544