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