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