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