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