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