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