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