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