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