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