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