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