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