removed 3D view listener for changing the background image frame.
[blender-staging.git] / source / blender / editors / space_view3d / view3d_draw.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
33 #include "DNA_action_types.h"
34 #include "DNA_armature_types.h"
35 #include "DNA_camera_types.h"
36 #include "DNA_customdata_types.h"
37 #include "DNA_group_types.h"
38 #include "DNA_key_types.h"
39 #include "DNA_lamp_types.h"
40 #include "DNA_object_types.h"
41 #include "DNA_space_types.h"
42 #include "DNA_scene_types.h"
43 #include "DNA_screen_types.h"
44 #include "DNA_userdef_types.h"
45 #include "DNA_view3d_types.h"
46 #include "DNA_world_types.h"
47
48 #include "MEM_guardedalloc.h"
49
50 #include "BLI_blenlib.h"
51 #include "BLI_math.h"
52 #include "BLI_rand.h"
53
54 #include "BKE_anim.h"
55 #include "BKE_context.h"
56 #include "BKE_customdata.h"
57 #include "BKE_image.h"
58 #include "BKE_ipo.h"
59 #include "BKE_key.h"
60 #include "BKE_object.h"
61 #include "BKE_global.h"
62 #include "BKE_paint.h"
63 #include "BKE_scene.h"
64 #include "BKE_screen.h"
65 #include "BKE_utildefines.h"
66 #include "BKE_unit.h"
67
68 #include "RE_pipeline.h"        // make_stars
69
70 #include "IMB_imbuf_types.h"
71 #include "IMB_imbuf.h"
72
73 #include "BIF_gl.h"
74 #include "BIF_glutil.h"
75
76 #include "WM_api.h"
77 #include "BLF_api.h"
78
79 #include "ED_armature.h"
80 #include "ED_keyframing.h"
81 #include "ED_gpencil.h"
82 #include "ED_mesh.h"
83 #include "ED_screen.h"
84 #include "ED_space_api.h"
85 #include "ED_util.h"
86 #include "ED_transform.h"
87 #include "ED_types.h"
88
89 #include "UI_interface.h"
90 #include "UI_interface_icons.h"
91 #include "UI_resources.h"
92 #include "UI_view2d.h"
93
94 #include "GPU_draw.h"
95 #include "GPU_material.h"
96
97 #include "view3d_intern.h"      // own include
98
99
100
101 static void star_stuff_init_func(void)
102 {
103         cpack(-1);
104         glPointSize(1.0);
105         glBegin(GL_POINTS);
106 }
107 static void star_stuff_vertex_func(float* i)
108 {
109         glVertex3fv(i);
110 }
111 static void star_stuff_term_func(void)
112 {
113         glEnd();
114 }
115
116 void circf(float x, float y, float rad)
117 {
118         GLUquadricObj *qobj = gluNewQuadric(); 
119         
120         gluQuadricDrawStyle(qobj, GLU_FILL); 
121         
122         glPushMatrix(); 
123         
124         glTranslatef(x,  y, 0.); 
125         
126         gluDisk( qobj, 0.0,  rad, 32, 1); 
127         
128         glPopMatrix(); 
129         
130         gluDeleteQuadric(qobj);
131 }
132
133 void circ(float x, float y, float rad)
134 {
135         GLUquadricObj *qobj = gluNewQuadric(); 
136         
137         gluQuadricDrawStyle(qobj, GLU_SILHOUETTE); 
138         
139         glPushMatrix(); 
140         
141         glTranslatef(x,  y, 0.); 
142         
143         gluDisk( qobj, 0.0,  rad, 32, 1); 
144         
145         glPopMatrix(); 
146         
147         gluDeleteQuadric(qobj);
148 }
149
150
151 /* ********* custom clipping *********** */
152
153 static void view3d_draw_clipping(RegionView3D *rv3d)
154 {
155         BoundBox *bb= rv3d->clipbb;
156         
157         if(bb) {
158                 UI_ThemeColorShade(TH_BACK, -8);
159                 
160                 glBegin(GL_QUADS);
161                 
162                 glVertex3fv(bb->vec[0]); glVertex3fv(bb->vec[1]); glVertex3fv(bb->vec[2]); glVertex3fv(bb->vec[3]);
163                 glVertex3fv(bb->vec[0]); glVertex3fv(bb->vec[4]); glVertex3fv(bb->vec[5]); glVertex3fv(bb->vec[1]);
164                 glVertex3fv(bb->vec[4]); glVertex3fv(bb->vec[7]); glVertex3fv(bb->vec[6]); glVertex3fv(bb->vec[5]);
165                 glVertex3fv(bb->vec[7]); glVertex3fv(bb->vec[3]); glVertex3fv(bb->vec[2]); glVertex3fv(bb->vec[6]);
166                 glVertex3fv(bb->vec[1]); glVertex3fv(bb->vec[5]); glVertex3fv(bb->vec[6]); glVertex3fv(bb->vec[2]);
167                 glVertex3fv(bb->vec[7]); glVertex3fv(bb->vec[4]); glVertex3fv(bb->vec[0]); glVertex3fv(bb->vec[3]);
168                 
169                 glEnd();
170         }
171 }
172
173 void view3d_set_clipping(RegionView3D *rv3d)
174 {
175         double plane[4];
176         int a, tot=4;
177         
178         if(rv3d->viewlock) tot= 6;
179         
180         for(a=0; a<tot; a++) {
181                 QUATCOPY(plane, rv3d->clip[a]);
182                 glClipPlane(GL_CLIP_PLANE0+a, plane);
183                 glEnable(GL_CLIP_PLANE0+a);
184         }
185 }
186
187 void view3d_clr_clipping(void)
188 {
189         int a;
190         
191         for(a=0; a<6; a++) {
192                 glDisable(GL_CLIP_PLANE0+a);
193         }
194 }
195
196 static int test_clipping(float *vec, float clip[][4])
197 {
198         float view[3];
199         VECCOPY(view, vec);
200         
201         if(0.0f < clip[0][3] + INPR(view, clip[0]))
202                 if(0.0f < clip[1][3] + INPR(view, clip[1]))
203                         if(0.0f < clip[2][3] + INPR(view, clip[2]))
204                                 if(0.0f < clip[3][3] + INPR(view, clip[3]))
205                                         return 0;
206
207         return 1;
208 }
209
210 /* for 'local' ED_view3d_local_clipping must run first
211  * then all comparisons can be done in localspace */
212 int view3d_test_clipping(RegionView3D *rv3d, float *vec, int local)
213 {
214         return test_clipping(vec, local ? rv3d->clip_local : rv3d->clip);
215 }
216
217 /* ********* end custom clipping *********** */
218
219
220 static void drawgrid_draw(ARegion *ar, float wx, float wy, float x, float y, float dx)
221 {
222         float fx, fy;
223         
224         x+= (wx); 
225         y+= (wy);
226         fx= x/dx;
227         fx= x-dx*floor(fx);
228         
229         while(fx< ar->winx) {
230                 fdrawline(fx,  0.0,  fx,  (float)ar->winy); 
231                 fx+= dx; 
232         }
233
234         fy= y/dx;
235         fy= y-dx*floor(fy);
236         
237
238         while(fy< ar->winy) {
239                 fdrawline(0.0,  fy,  (float)ar->winx,  fy); 
240                 fy+= dx;
241         }
242
243 }
244
245 #define GRID_MIN_PX 6.0f
246
247 static void drawgrid(UnitSettings *unit, ARegion *ar, View3D *v3d, char **grid_unit)
248 {
249         /* extern short bgpicmode; */
250         RegionView3D *rv3d= ar->regiondata;
251         float wx, wy, x, y, fw, fx, fy, dx;
252         float vec4[4];
253         char col[3], col2[3];
254         
255         *grid_unit= NULL;
256
257         vec4[0]=vec4[1]=vec4[2]=0.0; 
258         vec4[3]= 1.0;
259         mul_m4_v4(rv3d->persmat, vec4);
260         fx= vec4[0]; 
261         fy= vec4[1]; 
262         fw= vec4[3];
263
264         wx= (ar->winx/2.0);     /* because of rounding errors, grid at wrong location */
265         wy= (ar->winy/2.0);
266
267         x= (wx)*fx/fw;
268         y= (wy)*fy/fw;
269
270         vec4[0]=vec4[1]= (unit->system) ? 1.0 : v3d->grid;
271
272         vec4[2]= 0.0;
273         vec4[3]= 1.0;
274         mul_m4_v4(rv3d->persmat, vec4);
275         fx= vec4[0]; 
276         fy= vec4[1]; 
277         fw= vec4[3];
278
279         dx= fabs(x-(wx)*fx/fw);
280         if(dx==0) dx= fabs(y-(wy)*fy/fw);
281         
282         glDepthMask(0);         // disable write in zbuffer
283
284         /* check zoom out */
285         UI_ThemeColor(TH_GRID);
286         
287         if(unit->system) {
288                 /* Use GRID_MIN_PX*2 for units because very very small grid
289                  * items are less useful when dealing with units */
290                 void *usys;
291                 int len, i;
292                 double scalar;
293                 float dx_scalar;
294                 float blend_fac;
295
296                 bUnit_GetSystem(&usys, &len, unit->system, B_UNIT_LENGTH);
297
298                 if(usys) {
299                         i= len;
300                         while(i--) {
301                                 scalar= bUnit_GetScaler(usys, i);
302
303                                 dx_scalar = dx * scalar * unit->scale_length;
304                                 if (dx_scalar < (GRID_MIN_PX*2))
305                                         continue;
306
307                                 /* Store the smallest drawn grid size units name so users know how big each grid cell is */
308                                 if(*grid_unit==NULL) {
309                                         *grid_unit= bUnit_GetNameDisplay(usys, i);
310                                         rv3d->gridview= (scalar * unit->scale_length);
311                                 }
312                                 blend_fac= 1-((GRID_MIN_PX*2)/dx_scalar);
313
314                                 /* tweak to have the fade a bit nicer */
315                                 blend_fac= (blend_fac * blend_fac) * 2.0f;
316                                 CLAMP(blend_fac, 0.3f, 1.0f);
317
318
319                                 UI_ThemeColorBlend(TH_BACK, TH_GRID, blend_fac);
320
321                                 drawgrid_draw(ar, wx, wy, x, y, dx_scalar);
322                         }
323                 }
324         }
325         else {
326                 short sublines = v3d->gridsubdiv;
327
328                 if(dx<GRID_MIN_PX) {
329                         rv3d->gridview*= sublines;
330                         dx*= sublines;
331                         
332                         if(dx<GRID_MIN_PX) {
333                                 rv3d->gridview*= sublines;
334                                 dx*= sublines;
335
336                                 if(dx<GRID_MIN_PX) {
337                                         rv3d->gridview*= sublines;
338                                         dx*=sublines;
339                                         if(dx<GRID_MIN_PX);
340                                         else {
341                                                 UI_ThemeColor(TH_GRID);
342                                                 drawgrid_draw(ar, wx, wy, x, y, dx);
343                                         }
344                                 }
345                                 else {  // start blending out
346                                         UI_ThemeColorBlend(TH_BACK, TH_GRID, dx/(GRID_MIN_PX*6));
347                                         drawgrid_draw(ar, wx, wy, x, y, dx);
348
349                                         UI_ThemeColor(TH_GRID);
350                                         drawgrid_draw(ar, wx, wy, x, y, sublines*dx);
351                                 }
352                         }
353                         else {  // start blending out (GRID_MIN_PX < dx < (GRID_MIN_PX*10))
354                                 UI_ThemeColorBlend(TH_BACK, TH_GRID, dx/(GRID_MIN_PX*6));
355                                 drawgrid_draw(ar, wx, wy, x, y, dx);
356
357                                 UI_ThemeColor(TH_GRID);
358                                 drawgrid_draw(ar, wx, wy, x, y, sublines*dx);
359                         }
360                 }
361                 else {
362                         if(dx>(GRID_MIN_PX*10)) {               // start blending in
363                                 rv3d->gridview/= sublines;
364                                 dx/= sublines;
365                                 if(dx>(GRID_MIN_PX*10)) {               // start blending in
366                                         rv3d->gridview/= sublines;
367                                         dx/= sublines;
368                                         if(dx>(GRID_MIN_PX*10)) {
369                                                 UI_ThemeColor(TH_GRID);
370                                                 drawgrid_draw(ar, wx, wy, x, y, dx);
371                                         }
372                                         else {
373                                                 UI_ThemeColorBlend(TH_BACK, TH_GRID, dx/(GRID_MIN_PX*6));
374                                                 drawgrid_draw(ar, wx, wy, x, y, dx);
375                                                 UI_ThemeColor(TH_GRID);
376                                                 drawgrid_draw(ar, wx, wy, x, y, dx*sublines);
377                                         }
378                                 }
379                                 else {
380                                         UI_ThemeColorBlend(TH_BACK, TH_GRID, dx/(GRID_MIN_PX*6));
381                                         drawgrid_draw(ar, wx, wy, x, y, dx);
382                                         UI_ThemeColor(TH_GRID);
383                                         drawgrid_draw(ar, wx, wy, x, y, dx*sublines);
384                                 }
385                         }
386                         else {
387                                 UI_ThemeColorBlend(TH_BACK, TH_GRID, dx/(GRID_MIN_PX*6));
388                                 drawgrid_draw(ar, wx, wy, x, y, dx);
389                                 UI_ThemeColor(TH_GRID);
390                                 drawgrid_draw(ar, wx, wy, x, y, dx*sublines);
391                         }
392                 }
393         }
394
395
396         x+= (wx); 
397         y+= (wy);
398         UI_GetThemeColor3ubv(TH_GRID, col);
399
400         setlinestyle(0);
401         
402         /* center cross */
403         if( ELEM(rv3d->view, RV3D_VIEW_RIGHT, RV3D_VIEW_LEFT)) 
404                 UI_make_axis_color(col, col2, 'y');
405         else UI_make_axis_color(col, col2, 'x');
406         glColor3ubv((GLubyte *)col2);
407         
408         fdrawline(0.0,  y,  (float)ar->winx,  y); 
409         
410         if( ELEM(rv3d->view, RV3D_VIEW_TOP, RV3D_VIEW_BOTTOM)) 
411                 UI_make_axis_color(col, col2, 'y');
412         else UI_make_axis_color(col, col2, 'z');
413         glColor3ubv((GLubyte *)col2);
414
415         fdrawline(x, 0.0, x, (float)ar->winy); 
416
417         glDepthMask(1);         // enable write in zbuffer
418 }
419 #undef GRID_MIN_PX
420
421 static void drawfloor(Scene *scene, View3D *v3d)
422 {
423         float vert[3], grid;
424         int a, gridlines, emphasise;
425         char col[3], col2[3];
426         short draw_line = 0;
427         
428         vert[2]= 0.0;
429         
430         if(v3d->gridlines<3) return;
431         
432         if(v3d->zbuf && scene->obedit) glDepthMask(0);  // for zbuffer-select
433         
434         gridlines= v3d->gridlines/2;
435         grid= gridlines*v3d->grid;
436         
437         UI_GetThemeColor3ubv(TH_GRID, col);
438         UI_GetThemeColor3ubv(TH_BACK, col2);
439         
440         /* emphasise division lines lighter instead of darker, if background is darker than grid */
441         if ( ((col[0]+col[1]+col[2])/3+10) > (col2[0]+col2[1]+col2[2])/3 )
442                 emphasise = 20;
443         else
444                 emphasise = -10;
445         
446         /* draw the Y axis and/or grid lines */
447         for(a= -gridlines;a<=gridlines;a++) {
448                 if(a==0) {
449                         /* check for the 'show Y axis' preference */
450                         if (v3d->gridflag & V3D_SHOW_Y) { 
451                                 UI_make_axis_color(col, col2, 'y');
452                                 glColor3ubv((GLubyte *)col2);
453                                 
454                                 draw_line = 1;
455                         } else if (v3d->gridflag & V3D_SHOW_FLOOR) {
456                                 UI_ThemeColorShade(TH_GRID, emphasise);
457                         } else {
458                                 draw_line = 0;
459                         }
460                 } else {
461                         /* check for the 'show grid floor' preference */
462                         if (v3d->gridflag & V3D_SHOW_FLOOR) {
463                                 if( (a % 10)==0) {
464                                         UI_ThemeColorShade(TH_GRID, emphasise);
465                                 }
466                                 else UI_ThemeColorShade(TH_GRID, 10);
467                                 
468                                 draw_line = 1;
469                         } else {
470                                 draw_line = 0;
471                         }
472                 }
473                 
474                 if (draw_line) {
475                         glBegin(GL_LINE_STRIP);
476                 vert[0]= a*v3d->grid;
477                 vert[1]= grid;
478                 glVertex3fv(vert);
479                 vert[1]= -grid;
480                 glVertex3fv(vert);
481                         glEnd();
482                 }
483         }
484         
485         /* draw the X axis and/or grid lines */
486         for(a= -gridlines;a<=gridlines;a++) {
487                 if(a==0) {
488                         /* check for the 'show X axis' preference */
489                         if (v3d->gridflag & V3D_SHOW_X) { 
490                                 UI_make_axis_color(col, col2, 'x');
491                                 glColor3ubv((GLubyte *)col2);
492                                 
493                                 draw_line = 1;
494                         } else if (v3d->gridflag & V3D_SHOW_FLOOR) {
495                                 UI_ThemeColorShade(TH_GRID, emphasise);
496                         } else {
497                                 draw_line = 0;
498                         }
499                 } else {
500                         /* check for the 'show grid floor' preference */
501                         if (v3d->gridflag & V3D_SHOW_FLOOR) {
502                                 if( (a % 10)==0) {
503                                         UI_ThemeColorShade(TH_GRID, emphasise);
504                                 }
505                                 else UI_ThemeColorShade(TH_GRID, 10);
506                                 
507                                 draw_line = 1;
508                         } else {
509                                 draw_line = 0;
510                         }
511                 }
512                 
513                 if (draw_line) {
514                         glBegin(GL_LINE_STRIP);
515                 vert[1]= a*v3d->grid;
516                 vert[0]= grid;
517                 glVertex3fv(vert );
518                 vert[0]= -grid;
519                 glVertex3fv(vert);
520                         glEnd();
521                 }
522         }
523         
524         /* draw the Z axis line */      
525         /* check for the 'show Z axis' preference */
526         if (v3d->gridflag & V3D_SHOW_Z) {
527                 UI_make_axis_color(col, col2, 'z');
528                 glColor3ubv((GLubyte *)col2);
529                 
530                 glBegin(GL_LINE_STRIP);
531                 vert[0]= 0;
532                 vert[1]= 0;
533                 vert[2]= grid;
534                 glVertex3fv(vert );
535                 vert[2]= -grid;
536                 glVertex3fv(vert);
537                 glEnd();
538         }
539         
540         if(v3d->zbuf && scene->obedit) glDepthMask(1);  
541         
542 }
543
544 static void drawcursor(Scene *scene, ARegion *ar, View3D *v3d)
545 {
546         short mx,my,co[2];
547         int flag;
548         
549         /* we dont want the clipping for cursor */
550         flag= v3d->flag;
551         v3d->flag= 0;
552         project_short(ar, give_cursor(scene, v3d), co);
553         v3d->flag= flag;
554         
555         mx = co[0];
556         my = co[1];
557         
558         if(mx!=IS_CLIPPED) {
559                 setlinestyle(0); 
560                 cpack(0xFF);
561                 circ((float)mx, (float)my, 10.0);
562                 setlinestyle(4); 
563                 cpack(0xFFFFFF);
564                 circ((float)mx, (float)my, 10.0);
565                 setlinestyle(0);
566                 cpack(0x0);
567                 
568                 sdrawline(mx-20, my, mx-5, my);
569                 sdrawline(mx+5, my, mx+20, my);
570                 sdrawline(mx, my-20, mx, my-5);
571                 sdrawline(mx, my+5, mx, my+20);
572         }
573 }
574
575 /* Draw a live substitute of the view icon, which is always shown */
576 static void draw_view_axis(RegionView3D *rv3d)
577 {
578         const float k = U.rvisize;   /* axis size */
579         const float toll = 0.5;      /* used to see when view is quasi-orthogonal */
580         const float start = k + 1.0; /* axis center in screen coordinates, x=y */
581         float ydisp = 0.0;          /* vertical displacement to allow obj info text */
582         
583         /* rvibright ranges approx. from original axis icon color to gizmo color */
584         float bright = U.rvibright / 15.0f;
585         
586         unsigned char col[3];
587         unsigned char gridcol[3];
588         float colf[3];
589         
590         float vec[4];
591         float dx, dy;
592         float h, s, v;
593         
594         /* thickness of lines is proportional to k */
595         /*      (log(k)-1) gives a more suitable thickness, but fps decreased by about 3 fps */
596         glLineWidth(k / 10);
597         //glLineWidth(log(k)-1); // a bit slow
598         
599         UI_GetThemeColor3ubv(TH_GRID, (char *)gridcol);
600         
601         /* X */
602         vec[0] = vec[3] = 1;
603         vec[1] = vec[2] = 0;
604         mul_qt_v3(rv3d->viewquat, vec);
605         
606         UI_make_axis_color((char *)gridcol, (char *)col, 'x');
607         rgb_to_hsv(col[0]/255.0f, col[1]/255.0f, col[2]/255.0f, &h, &s, &v);
608         s = s<0.5 ? s+0.5 : 1.0;
609         v = 0.3;
610         v = (v<1.0-(bright) ? v+bright : 1.0);
611         hsv_to_rgb(h, s, v, colf, colf+1, colf+2);
612         glColor3fv(colf);
613         
614         dx = vec[0] * k;
615         dy = vec[1] * k;
616         fdrawline(start, start + ydisp, start + dx, start + dy + ydisp);
617         if (fabs(dx) > toll || fabs(dy) > toll) {
618                 BLF_draw_default(start + dx + 2, start + dy + ydisp + 2, 0.0f, "x");
619         }
620         
621         /* Y */
622         vec[1] = vec[3] = 1;
623         vec[0] = vec[2] = 0;
624         mul_qt_v3(rv3d->viewquat, vec);
625         
626         UI_make_axis_color((char *)gridcol, (char *)col, 'y');
627         rgb_to_hsv(col[0]/255.0f, col[1]/255.0f, col[2]/255.0f, &h, &s, &v);
628         s = s<0.5 ? s+0.5 : 1.0;
629         v = 0.3;
630         v = (v<1.0-(bright) ? v+bright : 1.0);
631         hsv_to_rgb(h, s, v, colf, colf+1, colf+2);
632         glColor3fv(colf);
633         
634         dx = vec[0] * k;
635         dy = vec[1] * k;
636         fdrawline(start, start + ydisp, start + dx, start + dy + ydisp);
637         if (fabs(dx) > toll || fabs(dy) > toll) {
638                 BLF_draw_default(start + dx + 2, start + dy + ydisp + 2, 0.0f, "y");
639         }
640         
641         /* Z */
642         vec[2] = vec[3] = 1;
643         vec[1] = vec[0] = 0;
644         mul_qt_v3(rv3d->viewquat, vec);
645         
646         UI_make_axis_color((char *)gridcol, (char *)col, 'z');
647         rgb_to_hsv(col[0]/255.0f, col[1]/255.0f, col[2]/255.0f, &h, &s, &v);
648         s = s<0.5 ? s+0.5 : 1.0;
649         v = 0.5;
650         v = (v<1.0-(bright) ? v+bright : 1.0);
651         hsv_to_rgb(h, s, v, colf, colf+1, colf+2);
652         glColor3fv(colf);
653         
654         dx = vec[0] * k;
655         dy = vec[1] * k;
656         fdrawline(start, start + ydisp, start + dx, start + dy + ydisp);
657         if (fabs(dx) > toll || fabs(dy) > toll) {
658                 BLF_draw_default(start + dx + 2, start + dy + ydisp + 2, 0.0f, "z");
659         }
660         
661         /* restore line-width */
662         glLineWidth(1.0);
663 }
664
665
666 static void draw_view_icon(RegionView3D *rv3d)
667 {
668         BIFIconID icon;
669         
670         if( ELEM(rv3d->view, RV3D_VIEW_TOP, RV3D_VIEW_BOTTOM)) 
671                 icon= ICON_AXIS_TOP;
672         else if( ELEM(rv3d->view, RV3D_VIEW_FRONT, RV3D_VIEW_BACK)) 
673                 icon= ICON_AXIS_FRONT;
674         else if( ELEM(rv3d->view, RV3D_VIEW_RIGHT, RV3D_VIEW_LEFT)) 
675                 icon= ICON_AXIS_SIDE;
676         else return ;
677         
678         glEnable(GL_BLEND);
679         glBlendFunc(GL_SRC_ALPHA,  GL_ONE_MINUS_SRC_ALPHA); 
680         
681         UI_icon_draw(5.0, 5.0, icon);
682         
683         glDisable(GL_BLEND);
684 }
685
686 static char *view3d_get_name(View3D *v3d, RegionView3D *rv3d)
687 {
688         char *name = NULL;
689         
690         switch (rv3d->view) {
691                 case RV3D_VIEW_FRONT:
692                         if (rv3d->persp == RV3D_ORTHO) name = "Front Ortho";
693                         else name = "Front Persp";
694                         break;
695                 case RV3D_VIEW_BACK:
696                         if (rv3d->persp == RV3D_ORTHO) name = "Back Ortho";
697                         else name = "Back Persp";
698                         break;
699                 case RV3D_VIEW_TOP:
700                         if (rv3d->persp == RV3D_ORTHO) name = "Top Ortho";
701                         else name = "Top Persp";
702                         break;
703                 case RV3D_VIEW_BOTTOM:
704                         if (rv3d->persp == RV3D_ORTHO) name = "Bottom Ortho";
705                         else name = "Bottom Persp";
706                         break;
707                 case RV3D_VIEW_RIGHT:
708                         if (rv3d->persp == RV3D_ORTHO) name = "Right Ortho";
709                         else name = "Right Persp";
710                         break;
711                 case RV3D_VIEW_LEFT:
712                         if (rv3d->persp == RV3D_ORTHO) name = "Left Ortho";
713                         else name = "Left Persp";
714                         break;
715                         
716                 default:
717                         if (rv3d->persp==RV3D_CAMOB) {
718                                 if ((v3d->camera) && (v3d->camera->type == OB_CAMERA)) {
719                                         Camera *cam;
720                                         cam = v3d->camera->data;
721                                         name = (cam->type != CAM_ORTHO) ? "Camera Persp" : "Camera Ortho";
722                                 } else {
723                                         name = "Object as Camera";
724                                 }
725                         } else { 
726                                 name = (rv3d->persp == RV3D_ORTHO) ? "User Ortho" : "User Persp";
727                         }
728                         break;
729         }
730         
731         return name;
732 }
733
734 static void draw_viewport_name(ARegion *ar, View3D *v3d)
735 {
736         RegionView3D *rv3d= ar->regiondata;
737         char *name = view3d_get_name(v3d, rv3d);
738         char *printable = NULL;
739         
740         if (v3d->localvd) {
741                 printable = malloc(strlen(name) + strlen(" (Local)_")); /* '_' gives space for '\0' */
742                                                                                                  strcpy(printable, name);
743                                                                                                  strcat(printable, " (Local)");
744         } else {
745                 printable = name;
746         }
747
748         if (printable) {
749                 UI_ThemeColor(TH_TEXT_HI);
750                 BLF_draw_default(22,  ar->winy-17, 0.0f, printable);
751         }
752
753         if (v3d->localvd) {
754                 free(printable);
755         }
756 }
757
758
759 static char *get_cfra_marker_name(Scene *scene)
760 {
761         ListBase *markers= &scene->markers;
762         TimeMarker *m1, *m2;
763         
764         /* search through markers for match */
765         for (m1=markers->first, m2=markers->last; m1 && m2; m1=m1->next, m2=m2->prev) {
766                 if (m1->frame==CFRA)
767                         return m1->name;
768                 
769                 if (m1 == m2)
770                         break;          
771                 
772                 if (m2->frame==CFRA)
773                         return m2->name;
774         }
775         
776         return NULL;
777 }
778
779 /* draw info beside axes in bottom left-corner: 
780 *       framenum, object name, bone name (if available), marker name (if available)
781 */
782 static void draw_selected_name(Scene *scene, Object *ob, View3D *v3d)
783 {
784         char info[256], *markern;
785         short offset=30;
786         
787         /* get name of marker on current frame (if available) */
788         markern= get_cfra_marker_name(scene);
789         
790         /* check if there is an object */
791         if(ob) {
792                 /* name(s) to display depends on type of object */
793                 if(ob->type==OB_ARMATURE) {
794                         bArmature *arm= ob->data;
795                         char *name= NULL;
796                         
797                         /* show name of active bone too (if possible) */
798                         if(arm->edbo) {
799
800                                 if(arm->act_edbone)
801                                         name= ((EditBone *)arm->act_edbone)->name;
802
803                         }
804                         else if(ob->mode & OB_MODE_POSE) {
805                                 if(arm->act_bone) {
806
807                                         if(arm->act_bone->layer & arm->layer)
808                                                 name= arm->act_bone->name;
809
810                                 }
811                         }
812                         if(name && markern)
813                                 sprintf(info, "(%d) %s %s <%s>", CFRA, ob->id.name+2, name, markern);
814                         else if(name)
815                                 sprintf(info, "(%d) %s %s", CFRA, ob->id.name+2, name);
816                         else
817                                 sprintf(info, "(%d) %s", CFRA, ob->id.name+2);
818                 }
819                 else if(ELEM3(ob->type, OB_MESH, OB_LATTICE, OB_CURVE)) {
820                         Key *key= NULL;
821                         KeyBlock *kb = NULL;
822                         char shapes[75];
823                         
824                         /* try to display active shapekey too */
825                         shapes[0] = 0;
826                         key = ob_get_key(ob);
827                         if(key){
828                                 kb = BLI_findlink(&key->block, ob->shapenr-1);
829                                 if(kb){
830                                         sprintf(shapes, ": %s ", kb->name);             
831                                         if(ob->shapeflag == OB_SHAPE_LOCK){
832                                                 strcat(shapes, " (Pinned)");
833                                         }
834                                 }
835                         }
836                         
837                         if(markern)
838                                 sprintf(info, "(%d) %s %s <%s>", CFRA, ob->id.name+2, shapes, markern);
839                         else
840                                 sprintf(info, "(%d) %s %s", CFRA, ob->id.name+2, shapes);
841                 }
842                 else {
843                         /* standard object */
844                         if (markern)
845                                 sprintf(info, "(%d) %s <%s>", CFRA, ob->id.name+2, markern);
846                         else
847                                 sprintf(info, "(%d) %s", CFRA, ob->id.name+2);
848                 }
849                 
850                 /* colour depends on whether there is a keyframe */
851                 if (id_frame_has_keyframe((ID *)ob, /*frame_to_float(scene, CFRA)*/(float)(CFRA), v3d->keyflags))
852                         UI_ThemeColor(TH_VERTEX_SELECT);
853                 else
854                         UI_ThemeColor(TH_TEXT_HI);
855         }
856         else {
857                 /* no object */
858                 if (markern)
859                         sprintf(info, "(%d) <%s>", CFRA, markern);
860                 else
861                         sprintf(info, "(%d)", CFRA);
862                 
863                 /* colour is always white */
864                 UI_ThemeColor(TH_TEXT_HI);
865         }
866         
867         if (U.uiflag & USER_SHOW_ROTVIEWICON)
868                 offset = 14 + (U.rvisize * 2);
869
870         BLF_draw_default(offset,  10, 0.0f, info);
871 }
872
873 static void view3d_get_viewborder_size(Scene *scene, ARegion *ar, float size_r[2])
874 {
875         float winmax= MAX2(ar->winx, ar->winy);
876         float aspect= (float) (scene->r.xsch*scene->r.xasp)/(scene->r.ysch*scene->r.yasp);
877         
878         if(aspect>1.0) {
879                 size_r[0]= winmax;
880                 size_r[1]= winmax/aspect;
881         } else {
882                 size_r[0]= winmax*aspect;
883                 size_r[1]= winmax;
884         }
885 }
886
887 void calc_viewborder(Scene *scene, ARegion *ar, View3D *v3d, rctf *viewborder_r)
888 {
889         RegionView3D *rv3d= ar->regiondata;
890         float zoomfac, size[2];
891         float dx= 0.0f, dy= 0.0f;
892         
893         view3d_get_viewborder_size(scene, ar, size);
894         
895         /* magic zoom calculation, no idea what
896                 * it signifies, if you find out, tell me! -zr
897                 */
898         /* simple, its magic dude!
899                 * well, to be honest, this gives a natural feeling zooming
900                 * with multiple keypad presses (ton)
901                 */
902         
903         zoomfac= (M_SQRT2 + rv3d->camzoom/50.0);
904         zoomfac= (zoomfac*zoomfac)*0.25;
905         
906         size[0]= size[0]*zoomfac;
907         size[1]= size[1]*zoomfac;
908         
909         /* center in window */
910         viewborder_r->xmin= 0.5*ar->winx - 0.5*size[0];
911         viewborder_r->ymin= 0.5*ar->winy - 0.5*size[1];
912         viewborder_r->xmax= viewborder_r->xmin + size[0];
913         viewborder_r->ymax= viewborder_r->ymin + size[1];
914         
915         dx= ar->winx*rv3d->camdx*zoomfac*2.0f;
916         dy= ar->winy*rv3d->camdy*zoomfac*2.0f;
917         
918         /* apply offset */
919         viewborder_r->xmin-= dx;
920         viewborder_r->ymin-= dy;
921         viewborder_r->xmax-= dx;
922         viewborder_r->ymax-= dy;
923         
924         if(v3d->camera && v3d->camera->type==OB_CAMERA) {
925                 Camera *cam= v3d->camera->data;
926                 float w = viewborder_r->xmax - viewborder_r->xmin;
927                 float h = viewborder_r->ymax - viewborder_r->ymin;
928                 float side = MAX2(w, h);
929                 
930                 viewborder_r->xmin+= cam->shiftx*side;
931                 viewborder_r->xmax+= cam->shiftx*side;
932                 viewborder_r->ymin+= cam->shifty*side;
933                 viewborder_r->ymax+= cam->shifty*side;
934         }
935 }
936
937 void view3d_set_1_to_1_viewborder(Scene *scene, ARegion *ar)
938 {
939         RegionView3D *rv3d= ar->regiondata;
940         float size[2];
941         int im_width= (scene->r.size*scene->r.xsch)/100;
942         
943         view3d_get_viewborder_size(scene, ar, size);
944         
945         rv3d->camzoom= (sqrt(4.0*im_width/size[0]) - M_SQRT2)*50.0;
946         rv3d->camzoom= CLAMPIS(rv3d->camzoom, -30, 300);
947 }
948
949
950 static void drawviewborder_flymode(ARegion *ar) 
951 {
952         /* draws 4 edge brackets that frame the safe area where the
953         mouse can move during fly mode without spinning the view */
954         float x1, x2, y1, y2;
955         
956         x1= 0.45*(float)ar->winx;
957         y1= 0.45*(float)ar->winy;
958         x2= 0.55*(float)ar->winx;
959         y2= 0.55*(float)ar->winy;
960         cpack(0);
961         
962         
963         glBegin(GL_LINES);
964         /* bottom left */
965         glVertex2f(x1,y1); 
966         glVertex2f(x1,y1+5);
967         
968         glVertex2f(x1,y1); 
969         glVertex2f(x1+5,y1);
970         
971         /* top right */
972         glVertex2f(x2,y2); 
973         glVertex2f(x2,y2-5);
974         
975         glVertex2f(x2,y2); 
976         glVertex2f(x2-5,y2);
977         
978         /* top left */
979         glVertex2f(x1,y2); 
980         glVertex2f(x1,y2-5);
981         
982         glVertex2f(x1,y2); 
983         glVertex2f(x1+5,y2);
984         
985         /* bottom right */
986         glVertex2f(x2,y1); 
987         glVertex2f(x2,y1+5);
988         
989         glVertex2f(x2,y1); 
990         glVertex2f(x2-5,y1);
991         glEnd();        
992 }
993
994
995 static void drawviewborder(Scene *scene, ARegion *ar, View3D *v3d)
996 {
997         extern void gl_round_box(int mode, float minx, float miny, float maxx, float maxy, float rad);          // interface_panel.c
998         float fac, a;
999         float x1, x2, y1, y2;
1000         float x3, y3, x4, y4;
1001         rctf viewborder;
1002         Camera *ca= NULL;
1003         
1004         if(v3d->camera==NULL)
1005                 return;
1006         if(v3d->camera->type==OB_CAMERA)
1007                 ca = v3d->camera->data;
1008         
1009         calc_viewborder(scene, ar, v3d, &viewborder);
1010         x1= viewborder.xmin;
1011         y1= viewborder.ymin;
1012         x2= viewborder.xmax;
1013         y2= viewborder.ymax;
1014         
1015         /* passepartout, specified in camera edit buttons */
1016         if (ca && (ca->flag & CAM_SHOWPASSEPARTOUT) && ca->passepartalpha > 0.000001) {
1017                 if (ca->passepartalpha == 1.0) {
1018                         glColor3f(0, 0, 0);
1019                 } else {
1020                         glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA );
1021                         glEnable(GL_BLEND);
1022                         glColor4f(0, 0, 0, ca->passepartalpha);
1023                 }
1024                 if (x1 > 0.0)
1025                         glRectf(0.0, (float)ar->winy, x1, 0.0);
1026                 if (x2 < (float)ar->winx)
1027                         glRectf(x2, (float)ar->winy, (float)ar->winx, 0.0);
1028                 if (y2 < (float)ar->winy)
1029                         glRectf(x1, (float)ar->winy, x2, y2);
1030                 if (y2 > 0.0) 
1031                         glRectf(x1, y1, x2, 0.0);
1032                 
1033                 glDisable(GL_BLEND);
1034         }
1035         
1036         /* edge */
1037         glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); 
1038         
1039         setlinestyle(0);
1040         UI_ThemeColor(TH_BACK);
1041         glRectf(x1, y1, x2, y2);
1042         
1043         setlinestyle(3);
1044         UI_ThemeColor(TH_WIRE);
1045         glRectf(x1, y1, x2, y2);
1046         
1047         /* border */
1048         if(scene->r.mode & R_BORDER) {
1049                 
1050                 cpack(0);
1051                 x3= x1+ scene->r.border.xmin*(x2-x1);
1052                 y3= y1+ scene->r.border.ymin*(y2-y1);
1053                 x4= x1+ scene->r.border.xmax*(x2-x1);
1054                 y4= y1+ scene->r.border.ymax*(y2-y1);
1055                 
1056                 cpack(0x4040FF);
1057                 glRectf(x3,  y3,  x4,  y4); 
1058         }
1059         
1060         /* safety border */
1061         if (ca && (ca->flag & CAM_SHOWTITLESAFE)) {
1062                 fac= 0.1;
1063                 
1064                 a= fac*(x2-x1);
1065                 x1+= a; 
1066                 x2-= a;
1067                 
1068                 a= fac*(y2-y1);
1069                 y1+= a;
1070                 y2-= a;
1071                 
1072                 UI_ThemeColorBlendShade(TH_WIRE, TH_BACK, 0.25, 0);
1073                 
1074                 uiSetRoundBox(15);
1075                 gl_round_box(GL_LINE_LOOP, x1, y1, x2, y2, 12.0);
1076         }
1077         
1078         setlinestyle(0);
1079         glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
1080         
1081         /* camera name - draw in highlighted text color */
1082         if (ca && (ca->flag & CAM_SHOWNAME)) {
1083                 UI_ThemeColor(TH_TEXT_HI);
1084                 BLF_draw_default(x1, y1-15, 0.0f, v3d->camera->id.name+2);
1085                 UI_ThemeColor(TH_WIRE);
1086         }
1087 }
1088
1089 /* *********************** backdraw for selection *************** */
1090
1091 void backdrawview3d(Scene *scene, ARegion *ar, View3D *v3d)
1092 {
1093         RegionView3D *rv3d= ar->regiondata;
1094         struct Base *base = scene->basact;
1095         rcti winrct;
1096
1097         if(base && (base->object->mode & (OB_MODE_VERTEX_PAINT|OB_MODE_WEIGHT_PAINT) ||
1098                      paint_facesel_test(base->object)));
1099         else if((base && (base->object->mode & OB_MODE_TEXTURE_PAINT)) &&
1100                 scene->toolsettings && (scene->toolsettings->imapaint.flag & IMAGEPAINT_PROJECT_DISABLE));
1101         else if((base && (base->object->mode & OB_MODE_PARTICLE_EDIT)) && v3d->drawtype>OB_WIRE && (v3d->flag & V3D_ZBUF_SELECT));
1102         else if(scene->obedit && v3d->drawtype>OB_WIRE && (v3d->flag & V3D_ZBUF_SELECT));
1103         else {
1104                 v3d->flag &= ~V3D_INVALID_BACKBUF;
1105                 return;
1106         }
1107
1108         if( !(v3d->flag & V3D_INVALID_BACKBUF) ) return;
1109
1110 //      if(test) {
1111 //              if(qtest()) {
1112 //                      addafterqueue(ar->win, BACKBUFDRAW, 1);
1113 //                      return;
1114 //              }
1115 //      }
1116
1117         if(v3d->drawtype > OB_WIRE) v3d->zbuf= TRUE;
1118         
1119         glDisable(GL_DITHER);
1120
1121         region_scissor_winrct(ar, &winrct);
1122         glScissor(winrct.xmin, winrct.ymin, winrct.xmax - winrct.xmin, winrct.ymax - winrct.ymin);
1123
1124         glClearColor(0.0, 0.0, 0.0, 0.0); 
1125         if(v3d->zbuf) {
1126                 glEnable(GL_DEPTH_TEST);
1127                 glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
1128         }
1129         else {
1130                 glClear(GL_COLOR_BUFFER_BIT);
1131                 glDisable(GL_DEPTH_TEST);
1132         }
1133         
1134         if(rv3d->rflag & RV3D_CLIPPING)
1135                 view3d_set_clipping(rv3d);
1136         
1137         G.f |= G_BACKBUFSEL;
1138         
1139         if(base && (base->lay & v3d->lay)) {
1140                 draw_object_backbufsel(scene, v3d, rv3d, base->object);
1141         }
1142
1143         v3d->flag &= ~V3D_INVALID_BACKBUF;
1144
1145         G.f &= ~G_BACKBUFSEL;
1146         v3d->zbuf= FALSE; 
1147         glDisable(GL_DEPTH_TEST);
1148         glEnable(GL_DITHER);
1149
1150         if(rv3d->rflag & RV3D_CLIPPING)
1151                 view3d_clr_clipping();
1152
1153         /* it is important to end a view in a transform compatible with buttons */
1154 //      persp(PERSP_WIN);  // set ortho
1155
1156 }
1157
1158 void view3d_validate_backbuf(ViewContext *vc)
1159 {
1160         if(vc->v3d->flag & V3D_INVALID_BACKBUF)
1161                 backdrawview3d(vc->scene, vc->ar, vc->v3d);
1162 }
1163
1164 /* samples a single pixel (copied from vpaint) */
1165 unsigned int view3d_sample_backbuf(ViewContext *vc, int x, int y)
1166 {
1167         unsigned int col;
1168         
1169         if(x >= vc->ar->winx || y >= vc->ar->winy) return 0;
1170         x+= vc->ar->winrct.xmin;
1171         y+= vc->ar->winrct.ymin;
1172         
1173         view3d_validate_backbuf(vc);
1174
1175         glReadPixels(x,  y, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE,  &col);
1176         glReadBuffer(GL_BACK);  
1177         
1178         if(ENDIAN_ORDER==B_ENDIAN) SWITCH_INT(col);
1179         
1180         return WM_framebuffer_to_index(col);
1181 }
1182
1183 /* reads full rect, converts indices */
1184 ImBuf *view3d_read_backbuf(ViewContext *vc, short xmin, short ymin, short xmax, short ymax)
1185 {
1186         unsigned int *dr, *rd;
1187         struct ImBuf *ibuf, *ibuf1;
1188         int a;
1189         short xminc, yminc, xmaxc, ymaxc, xs, ys;
1190         
1191         /* clip */
1192         if(xmin<0) xminc= 0; else xminc= xmin;
1193         if(xmax >= vc->ar->winx) xmaxc= vc->ar->winx-1; else xmaxc= xmax;
1194         if(xminc > xmaxc) return NULL;
1195
1196         if(ymin<0) yminc= 0; else yminc= ymin;
1197         if(ymax >= vc->ar->winy) ymaxc= vc->ar->winy-1; else ymaxc= ymax;
1198         if(yminc > ymaxc) return NULL;
1199         
1200         ibuf= IMB_allocImBuf((xmaxc-xminc+1), (ymaxc-yminc+1), 32, IB_rect,0);
1201
1202         view3d_validate_backbuf(vc); 
1203         
1204         glReadPixels(vc->ar->winrct.xmin+xminc, vc->ar->winrct.ymin+yminc, (xmaxc-xminc+1), (ymaxc-yminc+1), GL_RGBA, GL_UNSIGNED_BYTE, ibuf->rect);
1205         glReadBuffer(GL_BACK);  
1206
1207         if(ENDIAN_ORDER==B_ENDIAN) IMB_convert_rgba_to_abgr(ibuf);
1208
1209         a= (xmaxc-xminc+1)*(ymaxc-yminc+1);
1210         dr= ibuf->rect;
1211         while(a--) {
1212                 if(*dr) *dr= WM_framebuffer_to_index(*dr);
1213                 dr++;
1214         }
1215         
1216         /* put clipped result back, if needed */
1217         if(xminc==xmin && xmaxc==xmax && yminc==ymin && ymaxc==ymax) 
1218                 return ibuf;
1219         
1220         ibuf1= IMB_allocImBuf( (xmax-xmin+1),(ymax-ymin+1),32,IB_rect,0);
1221         rd= ibuf->rect;
1222         dr= ibuf1->rect;
1223                 
1224         for(ys= ymin; ys<=ymax; ys++) {
1225                 for(xs= xmin; xs<=xmax; xs++, dr++) {
1226                         if( xs>=xminc && xs<=xmaxc && ys>=yminc && ys<=ymaxc) {
1227                                 *dr= *rd;
1228                                 rd++;
1229                         }
1230                 }
1231         }
1232         IMB_freeImBuf(ibuf);
1233         return ibuf1;
1234 }
1235
1236 /* smart function to sample a rect spiralling outside, nice for backbuf selection */
1237 unsigned int view3d_sample_backbuf_rect(ViewContext *vc, short mval[2], int size, 
1238                                                                                 unsigned int min, unsigned int max, int *dist, short strict, 
1239                                                                                 void *handle, unsigned int (*indextest)(void *handle, unsigned int index))
1240 {
1241         struct ImBuf *buf;
1242         unsigned int *bufmin, *bufmax, *tbuf;
1243         int minx, miny;
1244         int a, b, rc, nr, amount, dirvec[4][2];
1245         int distance=0;
1246         unsigned int index = 0;
1247         short indexok = 0;      
1248
1249         amount= (size-1)/2;
1250
1251         minx = mval[0]-(amount+1);
1252         miny = mval[1]-(amount+1);
1253         buf = view3d_read_backbuf(vc, minx, miny, minx+size-1, miny+size-1);
1254         if (!buf) return 0;
1255
1256         rc= 0;
1257         
1258         dirvec[0][0]= 1; dirvec[0][1]= 0;
1259         dirvec[1][0]= 0; dirvec[1][1]= -size;
1260         dirvec[2][0]= -1; dirvec[2][1]= 0;
1261         dirvec[3][0]= 0; dirvec[3][1]= size;
1262         
1263         bufmin = buf->rect;
1264         tbuf = buf->rect;
1265         bufmax = buf->rect + size*size;
1266         tbuf+= amount*size+ amount;
1267         
1268         for(nr=1; nr<=size; nr++) {
1269                 
1270                 for(a=0; a<2; a++) {
1271                         for(b=0; b<nr; b++, distance++) {
1272                                 if (*tbuf && *tbuf>=min && *tbuf<max) { //we got a hit
1273                                         if(strict){
1274                                                 indexok =  indextest(handle, *tbuf - min+1);
1275                                                 if(indexok){
1276                                                         *dist= (short) sqrt( (float)distance   );
1277                                                         index = *tbuf - min+1;
1278                                                         goto exit; 
1279                                                 }                                               
1280                                         }
1281                                         else{
1282                                                 *dist= (short) sqrt( (float)distance ); // XXX, this distance is wrong - 
1283                                                 index = *tbuf - min+1; // messy yah, but indices start at 1
1284                                                 goto exit;
1285                                         }                       
1286                                 }
1287                                 
1288                                 tbuf+= (dirvec[rc][0]+dirvec[rc][1]);
1289                                 
1290                                 if(tbuf<bufmin || tbuf>=bufmax) {
1291                                         goto exit;
1292                                 }
1293                         }
1294                         rc++;
1295                         rc &= 3;
1296                 }
1297         }
1298
1299 exit:
1300         IMB_freeImBuf(buf);
1301         return index;
1302 }
1303
1304
1305 /* ************************************************************* */
1306
1307 static void draw_bgpic(Scene *scene, ARegion *ar, View3D *v3d)
1308 {
1309         RegionView3D *rv3d= ar->regiondata;
1310         BGpic *bgpic;
1311         Image *ima;
1312         ImBuf *ibuf= NULL;
1313         float vec[4], fac, asp, zoomx, zoomy;
1314         float x1, y1, x2, y2, cx, cy;
1315         
1316         bgpic= v3d->bgpic;
1317         if(bgpic==NULL) return;
1318         
1319         ima= bgpic->ima;
1320
1321         if(ima) {
1322                 /* notifier can also call this however screen_ops.c */
1323                 BKE_image_user_calc_frame(&bgpic->iuser, CFRA, 0);
1324                 ibuf= BKE_image_get_ibuf(ima, &bgpic->iuser);
1325         }
1326         if(ibuf==NULL || (ibuf->rect==NULL && ibuf->rect_float==NULL) ) 
1327                 return;
1328         if(ibuf->channels!=4)
1329                 return;
1330         if(ibuf->rect==NULL)
1331                 IMB_rect_from_float(ibuf);
1332         
1333         if(rv3d->persp==2) {
1334                 rctf vb;
1335                 
1336                 calc_viewborder(scene, ar, v3d, &vb);
1337                 
1338                 x1= vb.xmin;
1339                 y1= vb.ymin;
1340                 x2= vb.xmax;
1341                 y2= vb.ymax;
1342         }
1343         else {
1344                 float sco[2];
1345                 
1346                 /* calc window coord */
1347                 initgrabz(rv3d, 0.0, 0.0, 0.0);
1348                 window_to_3d_delta(ar, vec, 1, 0);
1349                 fac= MAX3( fabs(vec[0]), fabs(vec[1]), fabs(vec[1]) );
1350                 fac= 1.0/fac;
1351                 
1352                 asp= ( (float)ibuf->y)/(float)ibuf->x;
1353                 
1354                 vec[0] = vec[1] = vec[2] = 0.0;
1355                 view3d_project_float(ar, vec, sco, rv3d->persmat);
1356                 cx = sco[0];
1357                 cy = sco[1];
1358                 
1359                 x1=  cx+ fac*(bgpic->xof-bgpic->size);
1360                 y1=  cy+ asp*fac*(bgpic->yof-bgpic->size);
1361                 x2=  cx+ fac*(bgpic->xof+bgpic->size);
1362                 y2=  cy+ asp*fac*(bgpic->yof+bgpic->size);
1363         }
1364         
1365         /* complete clip? */
1366         
1367         if(x2 < 0 ) return;
1368         if(y2 < 0 ) return;
1369         if(x1 > ar->winx ) return;
1370         if(y1 > ar->winy ) return;
1371         
1372         zoomx= (x2-x1)/ibuf->x;
1373         zoomy= (y2-y1)/ibuf->y;
1374         
1375         /* for some reason; zoomlevels down refuses to use GL_ALPHA_SCALE */
1376         if(zoomx < 1.0f || zoomy < 1.0f) {
1377                 float tzoom= MIN2(zoomx, zoomy);
1378                 int mip= 0;
1379                 
1380                 if(ibuf->mipmap[0]==NULL)
1381                         IMB_makemipmap(ibuf, 0, 0);
1382                 
1383                 while(tzoom < 1.0f && mip<8 && ibuf->mipmap[mip]) {
1384                         tzoom*= 2.0f;
1385                         zoomx*= 2.0f;
1386                         zoomy*= 2.0f;
1387                         mip++;
1388                 }
1389                 if(mip>0)
1390                         ibuf= ibuf->mipmap[mip-1];
1391         }
1392         
1393         if(v3d->zbuf) glDisable(GL_DEPTH_TEST);
1394         glDepthMask(0);
1395         
1396         glBlendFunc(GL_SRC_ALPHA,  GL_ONE_MINUS_SRC_ALPHA); 
1397         
1398         /* need to use wm push/pop matrix because ED_region_pixelspace
1399            uses the wm functions too, otherwise gets out of sync */
1400         wmPushMatrix();
1401         ED_region_pixelspace(ar);
1402         
1403         glEnable(GL_BLEND);
1404         
1405         glPixelZoom(zoomx, zoomy);
1406         glColor4f(1.0, 1.0, 1.0, 1.0-bgpic->blend);
1407         glaDrawPixelsTex(x1, y1, ibuf->x, ibuf->y, GL_UNSIGNED_BYTE, ibuf->rect);
1408         
1409         glPixelZoom(1.0, 1.0);
1410         glPixelTransferf(GL_ALPHA_SCALE, 1.0f);
1411         
1412         wmPopMatrix();
1413         
1414         glDisable(GL_BLEND);
1415
1416         glDepthMask(1);
1417         if(v3d->zbuf) glEnable(GL_DEPTH_TEST);
1418 }
1419
1420 /* ****************** View3d afterdraw *************** */
1421
1422 typedef struct View3DAfter {
1423         struct View3DAfter *next, *prev;
1424         struct Base *base;
1425         int type, flag;
1426 } View3DAfter;
1427
1428 /* temp storage of Objects that need to be drawn as last */
1429 void add_view3d_after(View3D *v3d, Base *base, int type, int flag)
1430 {
1431         View3DAfter *v3da= MEM_callocN(sizeof(View3DAfter), "View 3d after");
1432         
1433         BLI_addtail(&v3d->afterdraw, v3da);
1434         v3da->base= base;
1435         v3da->type= type;
1436         v3da->flag= flag;
1437 }
1438
1439 /* clears zbuffer and draws it over */
1440 static void view3d_draw_xray(Scene *scene, ARegion *ar, View3D *v3d, int clear)
1441 {
1442         View3DAfter *v3da, *next;
1443         int doit= 0;
1444         
1445         for(v3da= v3d->afterdraw.first; v3da; v3da= v3da->next)
1446                 if(v3da->type==V3D_XRAY) doit= 1;
1447         
1448         if(doit) {
1449                 if(clear && v3d->zbuf) glClear(GL_DEPTH_BUFFER_BIT);
1450                 v3d->xray= TRUE;
1451                 
1452                 for(v3da= v3d->afterdraw.first; v3da; v3da= next) {
1453                         next= v3da->next;
1454                         if(v3da->type==V3D_XRAY) {
1455                                 draw_object(scene, ar, v3d, v3da->base, v3da->flag);
1456                                 BLI_remlink(&v3d->afterdraw, v3da);
1457                                 MEM_freeN(v3da);
1458                         }
1459                 }
1460                 v3d->xray= FALSE;
1461         }
1462 }
1463
1464 /* disables write in zbuffer and draws it over */
1465 static void view3d_draw_transp(Scene *scene, ARegion *ar, View3D *v3d)
1466 {
1467         View3DAfter *v3da, *next;
1468         
1469         glDepthMask(0);
1470         v3d->transp= TRUE;
1471         
1472         for(v3da= v3d->afterdraw.first; v3da; v3da= next) {
1473                 next= v3da->next;
1474                 if(v3da->type==V3D_TRANSP) {
1475                         draw_object(scene, ar, v3d, v3da->base, v3da->flag);
1476                         BLI_remlink(&v3d->afterdraw, v3da);
1477                         MEM_freeN(v3da);
1478                 }
1479         }
1480         v3d->transp= FALSE;
1481         
1482         glDepthMask(1);
1483         
1484 }
1485
1486 /* *********************** */
1487
1488 /*
1489         In most cases call draw_dupli_objects,
1490         draw_dupli_objects_color was added because when drawing set dupli's
1491         we need to force the color
1492  */
1493 static void draw_dupli_objects_color(Scene *scene, ARegion *ar, View3D *v3d, Base *base, int color)
1494 {       
1495         RegionView3D *rv3d= ar->regiondata;
1496         ListBase *lb;
1497         DupliObject *dob;
1498         Base tbase;
1499         BoundBox bb; /* use a copy because draw_object, calls clear_mesh_caches */
1500         GLuint displist=0;
1501         short transflag, use_displist= -1;      /* -1 is initialize */
1502         char dt, dtx;
1503         
1504         if (base->object->restrictflag & OB_RESTRICT_VIEW) return;
1505         
1506         tbase.flag= OB_FROMDUPLI|base->flag;
1507         lb= object_duplilist(scene, base->object);
1508         
1509         for(dob= lb->first; dob; dob= dob->next) {
1510                 if(dob->no_draw);
1511                 else {
1512                         tbase.object= dob->ob;
1513                         
1514                         /* extra service: draw the duplicator in drawtype of parent */
1515                         /* MIN2 for the drawtype to allow bounding box objects in groups for lods */
1516                         dt= tbase.object->dt;   tbase.object->dt= MIN2(tbase.object->dt, base->object->dt);
1517                         dtx= tbase.object->dtx; tbase.object->dtx= base->object->dtx;
1518                         
1519                         /* negative scale flag has to propagate */
1520                         transflag= tbase.object->transflag;
1521                         if(base->object->transflag & OB_NEG_SCALE)
1522                                 tbase.object->transflag ^= OB_NEG_SCALE;
1523                         
1524                         UI_ThemeColorBlend(color, TH_BACK, 0.5);
1525                         
1526                         /* generate displist, test for new object */
1527                         if(use_displist==1 && dob->prev && dob->prev->ob!=dob->ob) {
1528                                 use_displist= -1;
1529                                 glDeleteLists(displist, 1);
1530                         }
1531                         /* generate displist */
1532                         if(use_displist == -1) {
1533                                 
1534                                 /* lamp drawing messes with matrices, could be handled smarter... but this works */
1535                                 if(dob->ob->type==OB_LAMP || dob->type==OB_DUPLIGROUP)
1536                                         use_displist= 0;
1537                                 else {
1538                                         /* disable boundbox check for list creation */
1539                                         object_boundbox_flag(dob->ob, OB_BB_DISABLED, 1);
1540                                         /* need this for next part of code */
1541                                         bb= *object_get_boundbox(dob->ob);
1542                                         
1543                                         unit_m4(dob->ob->obmat);        /* obmat gets restored */
1544                                         
1545                                         displist= glGenLists(1);
1546                                         glNewList(displist, GL_COMPILE);
1547                                         draw_object(scene, ar, v3d, &tbase, DRAW_CONSTCOLOR);
1548                                         glEndList();
1549                                         
1550                                         use_displist= 1;
1551                                         object_boundbox_flag(dob->ob, OB_BB_DISABLED, 0);
1552                                 }
1553                         }
1554                         if(use_displist) {
1555                                 wmMultMatrix(dob->mat);
1556                                 if(boundbox_clip(rv3d, dob->mat, &bb))
1557                                         glCallList(displist);
1558                                 wmLoadMatrix(rv3d->viewmat);
1559                         }
1560                         else {
1561                                 copy_m4_m4(dob->ob->obmat, dob->mat);
1562                                 draw_object(scene, ar, v3d, &tbase, DRAW_CONSTCOLOR);
1563                         }
1564                         
1565                         tbase.object->dt= dt;
1566                         tbase.object->dtx= dtx;
1567                         tbase.object->transflag= transflag;
1568                 }
1569         }
1570         
1571         /* Transp afterdraw disabled, afterdraw only stores base pointers, and duplis can be same obj */
1572         
1573         free_object_duplilist(lb);      /* does restore */
1574         
1575         if(use_displist)
1576                 glDeleteLists(displist, 1);
1577 }
1578
1579 static void draw_dupli_objects(Scene *scene, ARegion *ar, View3D *v3d, Base *base)
1580 {
1581         /* define the color here so draw_dupli_objects_color can be called
1582         * from the set loop */
1583         
1584         int color= (base->flag & SELECT)?TH_SELECT:TH_WIRE;
1585         /* debug */
1586         if(base->object->dup_group && base->object->dup_group->id.us<1)
1587                 color= TH_REDALERT;
1588         
1589         draw_dupli_objects_color(scene, ar, v3d, base, color);
1590 }
1591
1592
1593 void view3d_update_depths(ARegion *ar, View3D *v3d)
1594 {
1595         RegionView3D *rv3d= ar->regiondata;
1596         
1597         /* Create storage for, and, if necessary, copy depth buffer */
1598         if(!rv3d->depths) rv3d->depths= MEM_callocN(sizeof(ViewDepths),"ViewDepths");
1599         if(rv3d->depths) {
1600                 ViewDepths *d= rv3d->depths;
1601                 if(d->w != ar->winx ||
1602                    d->h != ar->winy ||
1603                    !d->depths) {
1604                         d->w= ar->winx;
1605                         d->h= ar->winy;
1606                         if(d->depths)
1607                                 MEM_freeN(d->depths);
1608                         d->depths= MEM_mallocN(sizeof(float)*d->w*d->h,"View depths");
1609                         d->damaged= 1;
1610                 }
1611                 
1612                 if(d->damaged) {
1613                         glReadPixels(ar->winrct.xmin,ar->winrct.ymin,d->w,d->h,
1614                                                  GL_DEPTH_COMPONENT,GL_FLOAT, d->depths);
1615                         
1616                         glGetDoublev(GL_DEPTH_RANGE,d->depth_range);
1617                         
1618                         d->damaged= 0;
1619                 }
1620         }
1621 }
1622
1623 void draw_depth_gpencil(Scene *scene, ARegion *ar, View3D *v3d)
1624 {
1625         short zbuf= v3d->zbuf;
1626         RegionView3D *rv3d= ar->regiondata;
1627
1628         setwinmatrixview3d(ar, v3d, NULL);      /* 0= no pick rect */
1629         setviewmatrixview3d(scene, v3d, rv3d);  /* note: calls where_is_object for camera... */
1630
1631         mul_m4_m4m4(rv3d->persmat, rv3d->viewmat, rv3d->winmat);
1632         invert_m4_m4(rv3d->persinv, rv3d->persmat);
1633         invert_m4_m4(rv3d->viewinv, rv3d->viewmat);
1634
1635         glClear(GL_DEPTH_BUFFER_BIT);
1636
1637         wmLoadMatrix(rv3d->viewmat);
1638
1639         v3d->zbuf= TRUE;
1640         glEnable(GL_DEPTH_TEST);
1641
1642         draw_gpencil_3dview_ext(scene, ar, 1);
1643         
1644         v3d->zbuf= zbuf;
1645
1646 }
1647
1648 void draw_depth(Scene *scene, ARegion *ar, View3D *v3d, int (* func)(void *))
1649 {
1650         RegionView3D *rv3d= ar->regiondata;
1651         Base *base;
1652         Scene *sce;
1653         short zbuf= v3d->zbuf;
1654         short flag= v3d->flag;
1655         float glalphaclip= U.glalphaclip;
1656         int obcenter_dia= U.obcenter_dia;
1657         /* temp set drawtype to solid */
1658         
1659         /* Setting these temporarily is not nice */
1660         v3d->flag &= ~V3D_SELECT_OUTLINE;
1661         U.glalphaclip = 0.5; /* not that nice but means we wont zoom into billboards */
1662         U.obcenter_dia= 0;
1663         
1664         setwinmatrixview3d(ar, v3d, NULL);      /* 0= no pick rect */
1665         setviewmatrixview3d(scene, v3d, rv3d);  /* note: calls where_is_object for camera... */
1666         
1667         mul_m4_m4m4(rv3d->persmat, rv3d->viewmat, rv3d->winmat);
1668         invert_m4_m4(rv3d->persinv, rv3d->persmat);
1669         invert_m4_m4(rv3d->viewinv, rv3d->viewmat);
1670         
1671         glClear(GL_DEPTH_BUFFER_BIT);
1672         
1673         wmLoadMatrix(rv3d->viewmat);
1674 //      persp(PERSP_STORE);  // store correct view for persp(PERSP_VIEW) calls
1675         
1676         if(rv3d->rflag & RV3D_CLIPPING) {
1677                 view3d_set_clipping(rv3d);
1678         }
1679         
1680         v3d->zbuf= TRUE;
1681         glEnable(GL_DEPTH_TEST);
1682         
1683         /* draw set first */
1684         if(scene->set) {
1685                 for(SETLOOPER(scene->set, base)) {
1686                         if(v3d->lay & base->lay) {
1687                                 if (func == NULL || func(base)) {
1688                                         draw_object(scene, ar, v3d, base, 0);
1689                                         if(base->object->transflag & OB_DUPLI) {
1690                                                 draw_dupli_objects_color(scene, ar, v3d, base, TH_WIRE);
1691                                         }
1692                                 }
1693                         }
1694                 }
1695         }
1696         
1697         for(base= scene->base.first; base; base= base->next) {
1698                 if(v3d->lay & base->lay) {
1699                         if (func == NULL || func(base)) {
1700                                 /* dupli drawing */
1701                                 if(base->object->transflag & OB_DUPLI) {
1702                                         draw_dupli_objects(scene, ar, v3d, base);
1703                                 }
1704                                 draw_object(scene, ar, v3d, base, 0);
1705                         }
1706                 }
1707         }
1708         
1709         /* this isnt that nice, draw xray objects as if they are normal */
1710         if (v3d->afterdraw.first) {
1711                 View3DAfter *v3da, *next;
1712                 int num = 0;
1713                 v3d->xray= TRUE;
1714                 
1715                 glDepthFunc(GL_ALWAYS); /* always write into the depth bufer, overwriting front z values */
1716                 for(v3da= v3d->afterdraw.first; v3da; v3da= next) {
1717                         next= v3da->next;
1718                         if(v3da->type==V3D_XRAY) {
1719                                 draw_object(scene, ar, v3d, v3da->base, 0);
1720                                 num++;
1721                         }
1722                         /* dont remove this time */
1723                 }
1724                 v3d->xray= FALSE;
1725                 
1726                 glDepthFunc(GL_LEQUAL); /* Now write the depth buffer normally */
1727                 for(v3da= v3d->afterdraw.first; v3da; v3da= next) {
1728                         next= v3da->next;
1729                         if(v3da->type==V3D_XRAY) {
1730                                 v3d->xray= TRUE; v3d->transp= FALSE;  
1731                         } else if (v3da->type==V3D_TRANSP) {
1732                                 v3d->xray= FALSE; v3d->transp= TRUE;
1733                         }
1734                         
1735                         draw_object(scene, ar, v3d, v3da->base, 0); /* Draw Xray or Transp objects normally */
1736                         BLI_remlink(&v3d->afterdraw, v3da);
1737                         MEM_freeN(v3da);
1738                 }
1739                 v3d->xray= FALSE;
1740                 v3d->transp= FALSE;
1741         }
1742         
1743         v3d->zbuf = zbuf;
1744         U.glalphaclip = glalphaclip;
1745         v3d->flag = flag;
1746         U.obcenter_dia= obcenter_dia;
1747 }
1748
1749 typedef struct View3DShadow {
1750         struct View3DShadow *next, *prev;
1751         GPULamp *lamp;
1752 } View3DShadow;
1753
1754 static void gpu_render_lamp_update(Scene *scene, View3D *v3d, Object *ob, Object *par, float obmat[][4], ListBase *shadows)
1755 {
1756         GPULamp *lamp;
1757         Lamp *la = (Lamp*)ob->data;
1758         View3DShadow *shadow;
1759         
1760         lamp = GPU_lamp_from_blender(scene, ob, par);
1761         
1762         if(lamp) {
1763                 GPU_lamp_update(lamp, ob->lay, obmat);
1764                 GPU_lamp_update_colors(lamp, la->r, la->g, la->b, la->energy);
1765                 
1766                 if((ob->lay & v3d->lay) && GPU_lamp_has_shadow_buffer(lamp)) {
1767                         shadow= MEM_callocN(sizeof(View3DShadow), "View3DShadow");
1768                         shadow->lamp = lamp;
1769                         BLI_addtail(shadows, shadow);
1770                 }
1771         }
1772 }
1773
1774 static void gpu_update_lamps_shadows(Scene *scene, View3D *v3d)
1775 {
1776         ListBase shadows;
1777         View3DShadow *shadow;
1778         Scene *sce;
1779         Base *base;
1780         Object *ob;
1781         
1782         shadows.first= shadows.last= NULL;
1783         
1784         /* update lamp transform and gather shadow lamps */
1785         for(SETLOOPER(scene, base)) {
1786                 ob= base->object;
1787                 
1788                 if(ob->type == OB_LAMP)
1789                         gpu_render_lamp_update(scene, v3d, ob, NULL, ob->obmat, &shadows);
1790                 
1791                 if (ob->transflag & OB_DUPLI) {
1792                         DupliObject *dob;
1793                         ListBase *lb = object_duplilist(scene, ob);
1794                         
1795                         for(dob=lb->first; dob; dob=dob->next)
1796                                 if(dob->ob->type==OB_LAMP)
1797                                         gpu_render_lamp_update(scene, v3d, dob->ob, ob, dob->mat, &shadows);
1798                         
1799                         free_object_duplilist(lb);
1800                 }
1801         }
1802         
1803         /* render shadows after updating all lamps, nested object_duplilist
1804                 * don't work correct since it's replacing object matrices */
1805         for(shadow=shadows.first; shadow; shadow=shadow->next) {
1806                 /* this needs to be done better .. */
1807                 float viewmat[4][4], winmat[4][4];
1808                 int drawtype, lay, winsize, flag2;
1809                 
1810                 drawtype= v3d->drawtype;
1811                 lay= v3d->lay;
1812                 flag2= v3d->flag2 & V3D_SOLID_TEX;
1813                 
1814                 v3d->drawtype = OB_SOLID;
1815                 v3d->lay &= GPU_lamp_shadow_layer(shadow->lamp);
1816                 v3d->flag2 &= ~V3D_SOLID_TEX;
1817                 
1818                 GPU_lamp_shadow_buffer_bind(shadow->lamp, viewmat, &winsize, winmat);
1819 // XXX          drawview3d_render(v3d, viewmat, winsize, winsize, winmat, 1);
1820                 GPU_lamp_shadow_buffer_unbind(shadow->lamp);
1821                 
1822                 v3d->drawtype= drawtype;
1823                 v3d->lay= lay;
1824                 v3d->flag2 |= flag2;
1825         }
1826         
1827         BLI_freelistN(&shadows);
1828 }
1829
1830 /* *********************** customdata **************** */
1831
1832 /* goes over all modes and view3d settings */
1833 static CustomDataMask get_viewedit_datamask(bScreen *screen, Scene *scene, Object *ob)
1834 {
1835         CustomDataMask mask = CD_MASK_BAREMESH;
1836         ScrArea *sa;
1837         
1838         /* check if we need tfaces & mcols due to face select or texture paint */
1839         if(paint_facesel_test(ob) || (ob && ob->mode & OB_MODE_TEXTURE_PAINT))
1840                 mask |= CD_MASK_MTFACE | CD_MASK_MCOL;
1841         
1842         /* check if we need tfaces & mcols due to view mode */
1843         for(sa = screen->areabase.first; sa; sa = sa->next) {
1844                 if(sa->spacetype == SPACE_VIEW3D) {
1845                         View3D *view = sa->spacedata.first;
1846                         if(view->drawtype == OB_SHADED) {
1847                                 /* this includes normals for mesh_create_shadedColors */
1848                                 mask |= CD_MASK_MTFACE | CD_MASK_MCOL | CD_MASK_NORMAL | CD_MASK_ORCO;
1849                         }
1850                         if((view->drawtype == OB_TEXTURE) || ((view->drawtype == OB_SOLID) && (view->flag2 & V3D_SOLID_TEX))) {
1851                                 mask |= CD_MASK_MTFACE | CD_MASK_MCOL;
1852                                 
1853                                 if(scene->gm.matmode == GAME_MAT_GLSL)
1854                                         mask |= CD_MASK_ORCO;
1855                         }
1856                 }
1857         }
1858         
1859         /* check if we need mcols due to vertex paint or weightpaint */
1860         if(ob) {
1861                 if(ob->mode & OB_MODE_VERTEX_PAINT)
1862                         mask |= CD_MASK_MCOL;
1863                 if(ob->mode & OB_MODE_WEIGHT_PAINT)
1864                         mask |= CD_MASK_WEIGHT_MCOL;
1865         }
1866
1867         return mask;
1868 }
1869
1870 static void view3d_main_area_setup_view(Scene *scene, View3D *v3d, ARegion *ar, float viewmat[][4], float winmat[][4])
1871 {
1872         RegionView3D *rv3d= ar->regiondata;
1873
1874         /* setup window matrices */
1875         if(winmat)
1876                 copy_m4_m4(rv3d->winmat, winmat);
1877         else
1878                 setwinmatrixview3d(ar, v3d, NULL); /* NULL= no pickrect */
1879         
1880         /* setup view matrix */
1881         if(viewmat)
1882                 copy_m4_m4(rv3d->viewmat, viewmat);
1883         else
1884                 setviewmatrixview3d(scene, v3d, rv3d);  /* note: calls where_is_object for camera... */
1885         
1886         /* update utilitity matrices */
1887         mul_m4_m4m4(rv3d->persmat, rv3d->viewmat, rv3d->winmat);
1888         invert_m4_m4(rv3d->persinv, rv3d->persmat);
1889         invert_m4_m4(rv3d->viewinv, rv3d->viewmat);
1890         
1891         /* calculate pixelsize factor once, is used for lamps and obcenters */
1892         {
1893                 float len1, len2, vec[3];
1894                 
1895                 VECCOPY(vec, rv3d->persinv[0]);
1896                 len1= normalize_v3(vec);
1897                 VECCOPY(vec, rv3d->persinv[1]);
1898                 len2= normalize_v3(vec);
1899                 
1900                 rv3d->pixsize= 2.0f*(len1>len2?len1:len2);
1901                 
1902                 /* correct for window size */
1903                 if(ar->winx > ar->winy) rv3d->pixsize/= (float)ar->winx;
1904                 else rv3d->pixsize/= (float)ar->winy;
1905         }
1906         
1907         /* set for opengl */
1908         glMatrixMode(GL_PROJECTION);
1909         wmLoadMatrix(rv3d->winmat);
1910
1911         glMatrixMode(GL_MODELVIEW);
1912         wmLoadMatrix(rv3d->viewmat);
1913 }
1914
1915 void ED_view3d_draw_offscreen(Scene *scene, View3D *v3d, ARegion *ar, int winx, int winy, float viewmat[][4], float winmat[][4])
1916 {
1917         Scene *sce;
1918         Base *base;
1919         int bwinx, bwiny;
1920
1921         glPushMatrix();
1922
1923         /* set temporary new size */
1924         bwinx= ar->winx;
1925         bwiny= ar->winy;
1926         ar->winx= winx;
1927         ar->winy= winy;
1928
1929         /* set flags */
1930         G.f |= G_RENDER_OGL;
1931         GPU_free_images();
1932
1933         /* set background color, fallback on the view background color */
1934         if(scene->world) {
1935                 glClearColor(scene->world->horr, scene->world->horg, scene->world->horb, 0.0);
1936         }
1937         else {
1938                 float col[3];
1939                 UI_GetThemeColor3fv(TH_BACK, col);
1940                 glClearColor(col[0], col[1], col[2], 0.0);      
1941         }
1942
1943         glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
1944
1945         /* setup view matrices */
1946         view3d_main_area_setup_view(scene, v3d, ar, viewmat, winmat);
1947
1948         /* set zbuffer */
1949         if(v3d->drawtype > OB_WIRE) {
1950                 v3d->zbuf= TRUE;
1951                 glEnable(GL_DEPTH_TEST);
1952         }
1953         else
1954                 v3d->zbuf= FALSE;
1955
1956         /* draw set first */
1957         if(scene->set) {
1958                 for(SETLOOPER(scene->set, base)) {
1959                         if(v3d->lay & base->lay) {
1960                                 UI_ThemeColorBlend(TH_WIRE, TH_BACK, 0.6f);
1961                                 draw_object(scene, ar, v3d, base, DRAW_CONSTCOLOR|DRAW_SCENESET);
1962                                 
1963                                 if(base->object->transflag & OB_DUPLI)
1964                                         draw_dupli_objects_color(scene, ar, v3d, base, TH_WIRE);
1965                         }
1966                 }
1967         }
1968         
1969         /* then draw not selected and the duplis, but skip editmode object */
1970         for(base= scene->base.first; base; base= base->next) {
1971                 if(v3d->lay & base->lay) {
1972                         /* dupli drawing */
1973                         if(base->object->transflag & OB_DUPLI)
1974                                 draw_dupli_objects(scene, ar, v3d, base);
1975
1976                         draw_object(scene, ar, v3d, base, 0);
1977                 }
1978         }
1979
1980         /* transp and X-ray afterdraw stuff */
1981         view3d_draw_transp(scene, ar, v3d);
1982         view3d_draw_xray(scene, ar, v3d, 1);    // clears zbuffer if it is used!
1983
1984         /* cleanup */
1985         if(v3d->zbuf) {
1986                 v3d->zbuf= FALSE;
1987                 glDisable(GL_DEPTH_TEST);
1988         }
1989
1990         /* draw grease-pencil stuff */
1991         draw_gpencil_3dview_ext(scene, ar, 1);
1992
1993         ED_region_pixelspace(ar);
1994
1995         /* draw grease-pencil stuff - needed to get paint-buffer shown too (since it's 2D) */
1996         draw_gpencil_3dview_ext(scene, ar, 0);
1997
1998         GPU_free_images();
1999
2000         /* restore size */
2001         ar->winx= bwinx;
2002         ar->winy= bwiny;
2003
2004         glPopMatrix();
2005 }
2006
2007 void view3d_main_area_draw(const bContext *C, ARegion *ar)
2008 {
2009         Scene *scene= CTX_data_scene(C);
2010         View3D *v3d = CTX_wm_view3d(C);
2011         RegionView3D *rv3d= CTX_wm_region_view3d(C);
2012         Scene *sce;
2013         Base *base;
2014         Object *ob;
2015         float col[3];
2016         int retopo= 0, sculptparticle= 0;
2017         Object *obact = OBACT;
2018         char *grid_unit= NULL;
2019         
2020         /* from now on all object derived meshes check this */
2021         v3d->customdata_mask= get_viewedit_datamask(CTX_wm_screen(C), scene, obact);
2022         
2023         /* shadow buffers, before we setup matrices */
2024         if(draw_glsl_material(scene, NULL, v3d, v3d->drawtype))
2025                 gpu_update_lamps_shadows(scene, v3d);
2026
2027         /* clear background */
2028         UI_GetThemeColor3fv(TH_BACK, col);
2029         glClearColor(col[0], col[1], col[2], 0.0); 
2030         glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
2031         
2032         /* setup view matrices */
2033         view3d_main_area_setup_view(scene, v3d, ar, NULL, NULL);
2034
2035         if(rv3d->rflag & RV3D_CLIPPING)
2036                 view3d_draw_clipping(rv3d);
2037         
2038         /* set zbuffer after we draw clipping region */
2039         if(v3d->drawtype > OB_WIRE) {
2040                 v3d->zbuf= TRUE;
2041                 glEnable(GL_DEPTH_TEST);
2042         }
2043         else
2044                 v3d->zbuf= FALSE;
2045
2046         /* enables anti-aliasing for 3D view drawing */
2047         if (!(U.gameflags & USER_DISABLE_AA))
2048                 glEnable(GL_MULTISAMPLE_ARB);
2049         
2050         // needs to be done always, gridview is adjusted in drawgrid() now
2051         rv3d->gridview= v3d->grid;
2052         
2053         if(rv3d->view==0 || rv3d->persp!=0) {
2054                 drawfloor(scene, v3d);
2055                 if(rv3d->persp==2) {
2056                         if(scene->world) {
2057                                 if(scene->world->mode & WO_STARS) {
2058                                         RE_make_stars(NULL, scene, star_stuff_init_func, star_stuff_vertex_func,
2059                                                                   star_stuff_term_func);
2060                                 }
2061                         }
2062                         if(v3d->flag & V3D_DISPBGPIC) draw_bgpic(scene, ar, v3d);
2063                 }
2064         }
2065         else {
2066                 ED_region_pixelspace(ar);
2067                 drawgrid(&scene->unit, ar, v3d, &grid_unit);
2068                 /* XXX make function? replaces persp(1) */
2069                 glMatrixMode(GL_PROJECTION);
2070                 wmLoadMatrix(rv3d->winmat);
2071                 glMatrixMode(GL_MODELVIEW);
2072                 wmLoadMatrix(rv3d->viewmat);
2073                 
2074                 if(v3d->flag & V3D_DISPBGPIC) {
2075                         draw_bgpic(scene, ar, v3d);
2076                 }
2077         }
2078         
2079         if(rv3d->rflag & RV3D_CLIPPING)
2080                 view3d_set_clipping(rv3d);
2081         
2082         /* draw set first */
2083         if(scene->set) {
2084                 for(SETLOOPER(scene->set, base)) {
2085                         
2086                         if(v3d->lay & base->lay) {
2087                                 
2088                                 UI_ThemeColorBlend(TH_WIRE, TH_BACK, 0.6f);
2089                                 draw_object(scene, ar, v3d, base, DRAW_CONSTCOLOR|DRAW_SCENESET);
2090                                 
2091                                 if(base->object->transflag & OB_DUPLI) {
2092                                         draw_dupli_objects_color(scene, ar, v3d, base, TH_WIRE);
2093                                 }
2094                         }
2095                 }
2096                 
2097                 /* Transp and X-ray afterdraw stuff for sets is done later */
2098         }
2099         
2100         /* extra service in layerbuttons, showing used layers */
2101         v3d->lay_used = 0;
2102         
2103         /* then draw not selected and the duplis, but skip editmode object */
2104         for(base= scene->base.first; base; base= base->next) {
2105                 v3d->lay_used |= base->lay;
2106                 
2107                 if(v3d->lay & base->lay) {
2108                         
2109                         /* dupli drawing */
2110                         if(base->object->transflag & OB_DUPLI) {
2111                                 draw_dupli_objects(scene, ar, v3d, base);
2112                         }
2113                         if((base->flag & SELECT)==0) {
2114                                 if(base->object!=scene->obedit) 
2115                                         draw_object(scene, ar, v3d, base, 0);
2116                         }
2117                 }
2118         }
2119
2120 //      retopo= retopo_mesh_check() || retopo_curve_check();
2121         sculptparticle= (obact && obact->mode & (OB_MODE_PARTICLE_EDIT)) && !scene->obedit;
2122         if(retopo)
2123                 view3d_update_depths(ar, v3d);
2124         
2125         /* draw selected and editmode */
2126         for(base= scene->base.first; base; base= base->next) {
2127                 if(v3d->lay & base->lay) {
2128                         if (base->object==scene->obedit || ( base->flag & SELECT) ) 
2129                                 draw_object(scene, ar, v3d, base, 0);
2130                 }
2131         }
2132         
2133         if(!retopo && sculptparticle && !(obact && (obact->dtx & OB_DRAWXRAY))) {
2134                 view3d_update_depths(ar, v3d);
2135         }
2136         
2137         ED_region_draw_cb_draw(C, ar, REGION_DRAW_POST_VIEW);
2138         
2139 //      REEB_draw();
2140         
2141 //      if(scene->radio) RAD_drawall(v3d->drawtype>=OB_SOLID);
2142         
2143         /* Transp and X-ray afterdraw stuff */
2144         view3d_draw_transp(scene, ar, v3d);
2145         view3d_draw_xray(scene, ar, v3d, 1);    // clears zbuffer if it is used!
2146         
2147         if(!retopo && sculptparticle && (obact && (OBACT->dtx & OB_DRAWXRAY))) {
2148                 view3d_update_depths(ar, v3d);
2149         }
2150         
2151         if(rv3d->rflag & RV3D_CLIPPING)
2152                 view3d_clr_clipping();
2153         
2154         BIF_draw_manipulator(C);
2155         
2156         /* Disable back anti-aliasing */
2157         if (!(U.gameflags & USER_DISABLE_AA))
2158                 glDisable(GL_MULTISAMPLE_ARB);
2159
2160         if(v3d->zbuf) {
2161                 v3d->zbuf= FALSE;
2162                 glDisable(GL_DEPTH_TEST);
2163         }
2164         
2165         /* draw grease-pencil stuff (3d-space strokes) */
2166         //if (v3d->flag2 & V3D_DISPGP)
2167                 draw_gpencil_3dview((bContext *)C, 1);
2168         
2169         BDR_drawSketch(C);
2170         
2171         ED_region_pixelspace(ar);
2172         
2173 //      retopo_paint_view_update(v3d);
2174 //      retopo_draw_paint_lines();
2175         
2176         /* Draw particle edit brush XXX (removed) */
2177         
2178         if(rv3d->persp>1) drawviewborder(scene, ar, v3d);
2179         if(rv3d->rflag & RV3D_FLYMODE) drawviewborder_flymode(ar);
2180         
2181         /* draw grease-pencil stuff - needed to get paint-buffer shown too (since it's 2D) */
2182 //      if (v3d->flag2 & V3D_DISPGP)
2183                 draw_gpencil_3dview((bContext *)C, 0);
2184
2185         drawcursor(scene, ar, v3d);
2186         
2187         if(U.uiflag & USER_SHOW_ROTVIEWICON)
2188                 draw_view_axis(rv3d);
2189         else    
2190                 draw_view_icon(rv3d);
2191         
2192         /* XXX removed viewport fps */
2193         if(U.uiflag & USER_SHOW_VIEWPORTNAME) {
2194                 draw_viewport_name(ar, v3d);
2195         }
2196         if (grid_unit) { /* draw below the viewport name */
2197                 UI_ThemeColor(TH_TEXT_HI);
2198                 BLF_draw_default(10,  ar->winy-(USER_SHOW_VIEWPORTNAME?40:20), 0.0f, grid_unit);
2199         }
2200
2201         ob= OBACT;
2202         if(U.uiflag & USER_DRAWVIEWINFO) 
2203                 draw_selected_name(scene, ob, v3d);
2204
2205         ED_region_draw_cb_draw(C, ar, REGION_DRAW_POST_PIXEL);
2206         
2207         /* XXX here was the blockhandlers for floating panels */
2208
2209         v3d->flag |= V3D_INVALID_BACKBUF;
2210 }
2211
2212