Camera tracking integration
[blender.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
1231                         float sensor_aspect = ca->sensor_x / ca->sensor_y;
1232                         float sensor_scale = (x2i-x1i) / ca->sensor_x;
1233                         float sensor_height = sensor_scale * ca->sensor_y;
1234
1235                         float ymid = y1i + (y2i-y1i)/2.f;
1236                         float sy1= ymid - sensor_height/2.f;
1237                         float sy2= ymid + sensor_height/2.f;
1238
1239                         UI_ThemeColorShade(TH_WIRE, 100);
1240
1241                         uiDrawBox(GL_LINE_LOOP, x1i, sy1, x2i, sy2, 2.0);
1242                 }
1243         }
1244
1245         setlinestyle(0);
1246         glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
1247
1248         /* camera name - draw in highlighted text color */
1249         if (ca && (ca->flag & CAM_SHOWNAME)) {
1250                 UI_ThemeColor(TH_TEXT_HI);
1251                 BLF_draw_default(x1i, y1i-15, 0.0f, v3d->camera->id.name+2, sizeof(v3d->camera->id.name)-2);
1252                 UI_ThemeColor(TH_WIRE);
1253         }
1254 }
1255
1256 /* *********************** backdraw for selection *************** */
1257
1258 static void backdrawview3d(Scene *scene, ARegion *ar, View3D *v3d)
1259 {
1260         RegionView3D *rv3d= ar->regiondata;
1261         struct Base *base = scene->basact;
1262         rcti winrct;
1263
1264         BLI_assert(ar->regiontype == RGN_TYPE_WINDOW);
1265
1266         if(base && (base->object->mode & (OB_MODE_VERTEX_PAINT|OB_MODE_WEIGHT_PAINT) ||
1267                          paint_facesel_test(base->object)));
1268         else if((base && (base->object->mode & OB_MODE_TEXTURE_PAINT)) &&
1269                 scene->toolsettings && (scene->toolsettings->imapaint.flag & IMAGEPAINT_PROJECT_DISABLE));
1270         else if((base && (base->object->mode & OB_MODE_PARTICLE_EDIT)) && v3d->drawtype>OB_WIRE && (v3d->flag & V3D_ZBUF_SELECT));
1271         else if(scene->obedit && v3d->drawtype>OB_WIRE && (v3d->flag & V3D_ZBUF_SELECT));
1272         else {
1273                 v3d->flag &= ~V3D_INVALID_BACKBUF;
1274                 return;
1275         }
1276
1277         if( !(v3d->flag & V3D_INVALID_BACKBUF) ) return;
1278
1279 //      if(test) {
1280 //              if(qtest()) {
1281 //                      addafterqueue(ar->win, BACKBUFDRAW, 1);
1282 //                      return;
1283 //              }
1284 //      }
1285
1286         if(v3d->drawtype > OB_WIRE) v3d->zbuf= TRUE;
1287         
1288         glDisable(GL_DITHER);
1289
1290         region_scissor_winrct(ar, &winrct);
1291         glScissor(winrct.xmin, winrct.ymin, winrct.xmax - winrct.xmin, winrct.ymax - winrct.ymin);
1292
1293         glClearColor(0.0, 0.0, 0.0, 0.0); 
1294         if(v3d->zbuf) {
1295                 glEnable(GL_DEPTH_TEST);
1296                 glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
1297         }
1298         else {
1299                 glClear(GL_COLOR_BUFFER_BIT);
1300                 glDisable(GL_DEPTH_TEST);
1301         }
1302         
1303         if(rv3d->rflag & RV3D_CLIPPING)
1304                 view3d_set_clipping(rv3d);
1305         
1306         G.f |= G_BACKBUFSEL;
1307         
1308         if(base && (base->lay & v3d->lay)) {
1309                 draw_object_backbufsel(scene, v3d, rv3d, base->object);
1310         }
1311
1312         v3d->flag &= ~V3D_INVALID_BACKBUF;
1313         ar->swap= 0; /* mark invalid backbuf for wm draw */
1314
1315         G.f &= ~G_BACKBUFSEL;
1316         v3d->zbuf= FALSE; 
1317         glDisable(GL_DEPTH_TEST);
1318         glEnable(GL_DITHER);
1319
1320         if(rv3d->rflag & RV3D_CLIPPING)
1321                 view3d_clr_clipping();
1322
1323         /* it is important to end a view in a transform compatible with buttons */
1324 //      persp(PERSP_WIN);  // set ortho
1325
1326 }
1327
1328 void view3d_validate_backbuf(ViewContext *vc)
1329 {
1330         if(vc->v3d->flag & V3D_INVALID_BACKBUF)
1331                 backdrawview3d(vc->scene, vc->ar, vc->v3d);
1332 }
1333
1334 /* samples a single pixel (copied from vpaint) */
1335 unsigned int view3d_sample_backbuf(ViewContext *vc, int x, int y)
1336 {
1337         unsigned int col;
1338         
1339         if(x >= vc->ar->winx || y >= vc->ar->winy) return 0;
1340         x+= vc->ar->winrct.xmin;
1341         y+= vc->ar->winrct.ymin;
1342         
1343         view3d_validate_backbuf(vc);
1344
1345         glReadPixels(x,  y, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE,  &col);
1346         glReadBuffer(GL_BACK);  
1347         
1348         if(ENDIAN_ORDER==B_ENDIAN) SWITCH_INT(col);
1349         
1350         return WM_framebuffer_to_index(col);
1351 }
1352
1353 /* reads full rect, converts indices */
1354 ImBuf *view3d_read_backbuf(ViewContext *vc, short xmin, short ymin, short xmax, short ymax)
1355 {
1356         unsigned int *dr, *rd;
1357         struct ImBuf *ibuf, *ibuf1;
1358         int a;
1359         short xminc, yminc, xmaxc, ymaxc, xs, ys;
1360         
1361         /* clip */
1362         if(xmin<0) xminc= 0; else xminc= xmin;
1363         if(xmax >= vc->ar->winx) xmaxc= vc->ar->winx-1; else xmaxc= xmax;
1364         if(xminc > xmaxc) return NULL;
1365
1366         if(ymin<0) yminc= 0; else yminc= ymin;
1367         if(ymax >= vc->ar->winy) ymaxc= vc->ar->winy-1; else ymaxc= ymax;
1368         if(yminc > ymaxc) return NULL;
1369         
1370         ibuf= IMB_allocImBuf((xmaxc-xminc+1), (ymaxc-yminc+1), 32, IB_rect);
1371
1372         view3d_validate_backbuf(vc); 
1373         
1374         glReadPixels(vc->ar->winrct.xmin+xminc, vc->ar->winrct.ymin+yminc, (xmaxc-xminc+1), (ymaxc-yminc+1), GL_RGBA, GL_UNSIGNED_BYTE, ibuf->rect);
1375         glReadBuffer(GL_BACK);  
1376
1377         if(ENDIAN_ORDER==B_ENDIAN) IMB_convert_rgba_to_abgr(ibuf);
1378
1379         a= (xmaxc-xminc+1)*(ymaxc-yminc+1);
1380         dr= ibuf->rect;
1381         while(a--) {
1382                 if(*dr) *dr= WM_framebuffer_to_index(*dr);
1383                 dr++;
1384         }
1385         
1386         /* put clipped result back, if needed */
1387         if(xminc==xmin && xmaxc==xmax && yminc==ymin && ymaxc==ymax) 
1388                 return ibuf;
1389         
1390         ibuf1= IMB_allocImBuf( (xmax-xmin+1),(ymax-ymin+1),32,IB_rect);
1391         rd= ibuf->rect;
1392         dr= ibuf1->rect;
1393                 
1394         for(ys= ymin; ys<=ymax; ys++) {
1395                 for(xs= xmin; xs<=xmax; xs++, dr++) {
1396                         if( xs>=xminc && xs<=xmaxc && ys>=yminc && ys<=ymaxc) {
1397                                 *dr= *rd;
1398                                 rd++;
1399                         }
1400                 }
1401         }
1402         IMB_freeImBuf(ibuf);
1403         return ibuf1;
1404 }
1405
1406 /* smart function to sample a rect spiralling outside, nice for backbuf selection */
1407 unsigned int view3d_sample_backbuf_rect(ViewContext *vc, const int mval[2], int size,
1408                                                                                 unsigned int min, unsigned int max, int *dist, short strict, 
1409                                                                                 void *handle, unsigned int (*indextest)(void *handle, unsigned int index))
1410 {
1411         struct ImBuf *buf;
1412         unsigned int *bufmin, *bufmax, *tbuf;
1413         int minx, miny;
1414         int a, b, rc, nr, amount, dirvec[4][2];
1415         int distance=0;
1416         unsigned int index = 0;
1417         short indexok = 0;      
1418
1419         amount= (size-1)/2;
1420
1421         minx = mval[0]-(amount+1);
1422         miny = mval[1]-(amount+1);
1423         buf = view3d_read_backbuf(vc, minx, miny, minx+size-1, miny+size-1);
1424         if (!buf) return 0;
1425
1426         rc= 0;
1427         
1428         dirvec[0][0]= 1; dirvec[0][1]= 0;
1429         dirvec[1][0]= 0; dirvec[1][1]= -size;
1430         dirvec[2][0]= -1; dirvec[2][1]= 0;
1431         dirvec[3][0]= 0; dirvec[3][1]= size;
1432         
1433         bufmin = buf->rect;
1434         tbuf = buf->rect;
1435         bufmax = buf->rect + size*size;
1436         tbuf+= amount*size+ amount;
1437         
1438         for(nr=1; nr<=size; nr++) {
1439                 
1440                 for(a=0; a<2; a++) {
1441                         for(b=0; b<nr; b++, distance++) {
1442                                 if (*tbuf && *tbuf>=min && *tbuf<max) { //we got a hit
1443                                         if(strict){
1444                                                 indexok =  indextest(handle, *tbuf - min+1);
1445                                                 if(indexok){
1446                                                         *dist= (short) sqrt( (float)distance   );
1447                                                         index = *tbuf - min+1;
1448                                                         goto exit; 
1449                                                 }                                               
1450                                         }
1451                                         else{
1452                                                 *dist= (short) sqrt( (float)distance ); // XXX, this distance is wrong - 
1453                                                 index = *tbuf - min+1; // messy yah, but indices start at 1
1454                                                 goto exit;
1455                                         }                       
1456                                 }
1457                                 
1458                                 tbuf+= (dirvec[rc][0]+dirvec[rc][1]);
1459                                 
1460                                 if(tbuf<bufmin || tbuf>=bufmax) {
1461                                         goto exit;
1462                                 }
1463                         }
1464                         rc++;
1465                         rc &= 3;
1466                 }
1467         }
1468
1469 exit:
1470         IMB_freeImBuf(buf);
1471         return index;
1472 }
1473
1474
1475 /* ************************************************************* */
1476
1477 static void draw_bgpic(Scene *scene, ARegion *ar, View3D *v3d)
1478 {
1479         RegionView3D *rv3d= ar->regiondata;
1480         BGpic *bgpic;
1481         Image *ima;
1482         MovieClip *clip;
1483         ImBuf *ibuf= NULL, *freeibuf;
1484         float vec[4], fac, asp, zoomx, zoomy;
1485         float x1, y1, x2, y2, cx, cy;
1486
1487
1488         for ( bgpic= v3d->bgpicbase.first; bgpic; bgpic= bgpic->next ) {
1489
1490                 if(     (bgpic->view == 0) || /* zero for any */
1491                         (bgpic->view & (1<<rv3d->view)) || /* check agaist flags */
1492                         (rv3d->persp==RV3D_CAMOB && bgpic->view == (1<<RV3D_VIEW_CAMERA))
1493                 ) {
1494                         freeibuf= NULL;
1495                         if(bgpic->source==V3D_BGPIC_IMAGE) {
1496                                 ima= bgpic->ima;
1497                                 if(ima==NULL)
1498                                         continue;
1499                                 BKE_image_user_calc_frame(&bgpic->iuser, CFRA, 0);
1500                                 ibuf= BKE_image_get_ibuf(ima, &bgpic->iuser);
1501                         } else {
1502                                 clip= NULL;
1503
1504                                 if(bgpic->flag&V3D_BGPIC_CAMERACLIP) {
1505                                         if(!scene->camera)
1506                                                 scene->camera= scene_find_camera(scene);
1507
1508                                         if(scene->camera)
1509                                                 clip= object_get_movieclip(scene, scene->camera, 1);
1510                                 } else clip= bgpic->clip;
1511
1512                                 if(clip==NULL)
1513                                         continue;
1514
1515                                 BKE_movieclip_user_set_frame(&bgpic->cuser, CFRA);
1516                                 ibuf= BKE_movieclip_get_ibuf(clip, &bgpic->cuser);
1517
1518                                 /* working with ibuf from image and clip has got different workflow now.
1519                                    ibuf acquired from clip is referenced by cache system and should
1520                                    be dereferenced after usage. */
1521                                 freeibuf= ibuf;
1522                         }
1523
1524                         if(ibuf==NULL)
1525                                 continue;
1526
1527                         if((ibuf->rect==NULL && ibuf->rect_float==NULL) || ibuf->channels!=4) { /* invalid image format */
1528                                 if(freeibuf)
1529                                         IMB_freeImBuf(freeibuf);
1530
1531                                 continue;
1532                         }
1533
1534                         if(ibuf->rect==NULL)
1535                                 IMB_rect_from_float(ibuf);
1536
1537                         if(rv3d->persp==RV3D_CAMOB) {
1538                                 rctf vb;
1539
1540                                 ED_view3d_calc_camera_border(scene, ar, v3d, rv3d, &vb, FALSE);
1541
1542                                 x1= vb.xmin;
1543                                 y1= vb.ymin;
1544                                 x2= vb.xmax;
1545                                 y2= vb.ymax;
1546                         }
1547                         else {
1548                                 float sco[2];
1549                                 const float mval_f[2]= {1.0f, 0.0f};
1550
1551                                 /* calc window coord */
1552                                 initgrabz(rv3d, 0.0, 0.0, 0.0);
1553                                 ED_view3d_win_to_delta(ar, mval_f, vec);
1554                                 fac= MAX3( fabs(vec[0]), fabs(vec[1]), fabs(vec[1]) );
1555                                 fac= 1.0f/fac;
1556
1557                                 asp= ( (float)ibuf->y)/(float)ibuf->x;
1558
1559                                 vec[0] = vec[1] = vec[2] = 0.0;
1560                                 ED_view3d_project_float(ar, vec, sco, rv3d->persmat);
1561                                 cx = sco[0];
1562                                 cy = sco[1];
1563
1564                                 x1=  cx+ fac*(bgpic->xof-bgpic->size);
1565                                 y1=  cy+ asp*fac*(bgpic->yof-bgpic->size);
1566                                 x2=  cx+ fac*(bgpic->xof+bgpic->size);
1567                                 y2=  cy+ asp*fac*(bgpic->yof+bgpic->size);
1568                         }
1569
1570                         /* complete clip? */
1571
1572                         if(x2 < 0 || y2 < 0 || x1 > ar->winx || y1 > ar->winy) {
1573                                 if(freeibuf)
1574                                         IMB_freeImBuf(freeibuf);
1575
1576                                 continue;
1577                         }
1578
1579                         zoomx= (x2-x1)/ibuf->x;
1580                         zoomy= (y2-y1)/ibuf->y;
1581
1582                         /* for some reason; zoomlevels down refuses to use GL_ALPHA_SCALE */
1583                         if(zoomx < 1.0f || zoomy < 1.0f) {
1584                                 float tzoom= MIN2(zoomx, zoomy);
1585                                 int mip= 0;
1586
1587                                 if((ibuf->userflags&IB_MIPMAP_INVALID) != 0) {
1588                                         IMB_remakemipmap(ibuf, 0);
1589                                         ibuf->userflags&= ~IB_MIPMAP_INVALID;
1590                                 }
1591                                 else if(ibuf->mipmap[0]==NULL)
1592                                         IMB_makemipmap(ibuf, 0);
1593
1594                                 while(tzoom < 1.0f && mip<8 && ibuf->mipmap[mip]) {
1595                                         tzoom*= 2.0f;
1596                                         zoomx*= 2.0f;
1597                                         zoomy*= 2.0f;
1598                                         mip++;
1599                                 }
1600                                 if(mip>0)
1601                                         ibuf= ibuf->mipmap[mip-1];
1602                         }
1603
1604                         if(v3d->zbuf) glDisable(GL_DEPTH_TEST);
1605                         glDepthMask(0);
1606
1607                         glEnable(GL_BLEND);
1608                         glBlendFunc(GL_SRC_ALPHA,  GL_ONE_MINUS_SRC_ALPHA);
1609
1610                         glMatrixMode(GL_PROJECTION);
1611                         glPushMatrix();
1612                         glMatrixMode(GL_MODELVIEW);
1613                         glPushMatrix();
1614                         ED_region_pixelspace(ar);
1615
1616                         glPixelZoom(zoomx, zoomy);
1617                         glColor4f(1.0f, 1.0f, 1.0f, 1.0f-bgpic->blend);
1618                         glaDrawPixelsTex(x1, y1, ibuf->x, ibuf->y, GL_UNSIGNED_BYTE, ibuf->rect);
1619
1620                         glPixelZoom(1.0, 1.0);
1621                         glPixelTransferf(GL_ALPHA_SCALE, 1.0f);
1622
1623                         glMatrixMode(GL_PROJECTION);
1624                         glPopMatrix();
1625                         glMatrixMode(GL_MODELVIEW);
1626                         glPopMatrix();
1627
1628                         glDisable(GL_BLEND);
1629
1630                         glDepthMask(1);
1631                         if(v3d->zbuf) glEnable(GL_DEPTH_TEST);
1632
1633                         if(freeibuf)
1634                                 IMB_freeImBuf(freeibuf);
1635                 }
1636         }
1637 }
1638
1639 /* ****************** View3d afterdraw *************** */
1640
1641 typedef struct View3DAfter {
1642         struct View3DAfter *next, *prev;
1643         struct Base *base;
1644         int flag;
1645 } View3DAfter;
1646
1647 /* temp storage of Objects that need to be drawn as last */
1648 void add_view3d_after(ListBase *lb, Base *base, int flag)
1649 {
1650         View3DAfter *v3da= MEM_callocN(sizeof(View3DAfter), "View 3d after");
1651         BLI_addtail(lb, v3da);
1652         v3da->base= base;
1653         v3da->flag= flag;
1654 }
1655
1656 /* disables write in zbuffer and draws it over */
1657 static void view3d_draw_transp(Scene *scene, ARegion *ar, View3D *v3d)
1658 {
1659         View3DAfter *v3da, *next;
1660         
1661         glDepthMask(0);
1662         v3d->transp= TRUE;
1663         
1664         for(v3da= v3d->afterdraw_transp.first; v3da; v3da= next) {
1665                 next= v3da->next;
1666                 draw_object(scene, ar, v3d, v3da->base, v3da->flag);
1667                 BLI_remlink(&v3d->afterdraw_transp, v3da);
1668                 MEM_freeN(v3da);
1669         }
1670         v3d->transp= FALSE;
1671         
1672         glDepthMask(1);
1673         
1674 }
1675
1676 /* clears zbuffer and draws it over */
1677 static void view3d_draw_xray(Scene *scene, ARegion *ar, View3D *v3d, int clear)
1678 {
1679         View3DAfter *v3da, *next;
1680
1681         if(clear && v3d->zbuf)
1682                 glClear(GL_DEPTH_BUFFER_BIT);
1683
1684         v3d->xray= TRUE;
1685         for(v3da= v3d->afterdraw_xray.first; v3da; v3da= next) {
1686                 next= v3da->next;
1687                 draw_object(scene, ar, v3d, v3da->base, v3da->flag);
1688                 BLI_remlink(&v3d->afterdraw_xray, v3da);
1689                 MEM_freeN(v3da);
1690         }
1691         v3d->xray= FALSE;
1692 }
1693
1694
1695 /* clears zbuffer and draws it over */
1696 static void view3d_draw_xraytransp(Scene *scene, ARegion *ar, View3D *v3d, int clear)
1697 {
1698         View3DAfter *v3da, *next;
1699
1700         if(clear && v3d->zbuf)
1701                 glClear(GL_DEPTH_BUFFER_BIT);
1702
1703         v3d->xray= TRUE;
1704         v3d->transp= TRUE;
1705         
1706         for(v3da= v3d->afterdraw_xraytransp.first; v3da; v3da= next) {
1707                 next= v3da->next;
1708                 draw_object(scene, ar, v3d, v3da->base, v3da->flag);
1709                 BLI_remlink(&v3d->afterdraw_xraytransp, v3da);
1710                 MEM_freeN(v3da);
1711         }
1712
1713         v3d->transp= FALSE;
1714         v3d->xray= FALSE;
1715
1716 }
1717
1718 /* *********************** */
1719
1720 /*
1721         In most cases call draw_dupli_objects,
1722         draw_dupli_objects_color was added because when drawing set dupli's
1723         we need to force the color
1724  */
1725
1726 #if 0
1727 int dupli_ob_sort(void *arg1, void *arg2)
1728 {
1729         void *p1= ((DupliObject *)arg1)->ob;
1730         void *p2= ((DupliObject *)arg2)->ob;
1731         int val = 0;
1732         if (p1 < p2)            val = -1;
1733         else if (p1 > p2)       val = 1;
1734         return val;
1735 }
1736 #endif
1737
1738
1739 static DupliObject *dupli_step(DupliObject *dob)
1740 {
1741         while(dob && dob->no_draw)
1742                 dob= dob->next;
1743         return dob;
1744 }
1745
1746 static void draw_dupli_objects_color(Scene *scene, ARegion *ar, View3D *v3d, Base *base, int color)
1747 {
1748         RegionView3D *rv3d= ar->regiondata;
1749         ListBase *lb;
1750         DupliObject *dob_prev= NULL, *dob, *dob_next= NULL;
1751         Base tbase;
1752         BoundBox bb, *bb_tmp; /* use a copy because draw_object, calls clear_mesh_caches */
1753         GLuint displist=0;
1754         short transflag, use_displist= -1;      /* -1 is initialize */
1755         char dt, dtx;
1756         
1757         if (base->object->restrictflag & OB_RESTRICT_VIEW) return;
1758         
1759         tbase.flag= OB_FROMDUPLI|base->flag;
1760         lb= object_duplilist(scene, base->object);
1761         // BLI_sortlist(lb, dupli_ob_sort); // might be nice to have if we have a dupli list with mixed objects.
1762
1763         dob=dupli_step(lb->first);
1764         if(dob) dob_next= dupli_step(dob->next);
1765
1766         for( ; dob ; dob_prev= dob, dob= dob_next, dob_next= dob_next ? dupli_step(dob_next->next) : NULL) {
1767                 tbase.object= dob->ob;
1768
1769                 /* extra service: draw the duplicator in drawtype of parent */
1770                 /* MIN2 for the drawtype to allow bounding box objects in groups for lods */
1771                 dt= tbase.object->dt;   tbase.object->dt= MIN2(tbase.object->dt, base->object->dt);
1772                 dtx= tbase.object->dtx; tbase.object->dtx= base->object->dtx;
1773
1774                 /* negative scale flag has to propagate */
1775                 transflag= tbase.object->transflag;
1776                 if(base->object->transflag & OB_NEG_SCALE)
1777                         tbase.object->transflag ^= OB_NEG_SCALE;
1778
1779                 UI_ThemeColorBlend(color, TH_BACK, 0.5);
1780
1781                 /* generate displist, test for new object */
1782                 if(dob_prev && dob_prev->ob != dob->ob) {
1783                         if(use_displist==1)
1784                                 glDeleteLists(displist, 1);
1785
1786                         use_displist= -1;
1787                 }
1788
1789                 /* generate displist */
1790                 if(use_displist == -1) {
1791
1792                         /* note, since this was added, its checked dob->type==OB_DUPLIGROUP
1793                          * however this is very slow, it was probably needed for the NLA
1794                          * offset feature (used in group-duplicate.blend but no longer works in 2.5)
1795                          * so for now it should be ok to - campbell */
1796
1797                         if(             (dob_next==NULL || dob_next->ob != dob->ob) || /* if this is the last no need  to make a displist */
1798                                         (dob->ob->type == OB_LAMP) || /* lamp drawing messes with matrices, could be handled smarter... but this works */
1799                                         (dob->type == OB_DUPLIGROUP && dob->animated) ||
1800                                         !(bb_tmp= object_get_boundbox(dob->ob))
1801                         ) {
1802                                 // printf("draw_dupli_objects_color: skipping displist for %s\n", dob->ob->id.name+2);
1803                                 use_displist= 0;
1804                         }
1805                         else {
1806                                 // printf("draw_dupli_objects_color: using displist for %s\n", dob->ob->id.name+2);
1807                                 bb= *bb_tmp; /* must make a copy  */
1808
1809                                 /* disable boundbox check for list creation */
1810                                 object_boundbox_flag(dob->ob, OB_BB_DISABLED, 1);
1811                                 /* need this for next part of code */
1812                                 unit_m4(dob->ob->obmat);        /* obmat gets restored */
1813
1814                                 displist= glGenLists(1);
1815                                 glNewList(displist, GL_COMPILE);
1816                                 draw_object(scene, ar, v3d, &tbase, DRAW_CONSTCOLOR);
1817                                 glEndList();
1818
1819                                 use_displist= 1;
1820                                 object_boundbox_flag(dob->ob, OB_BB_DISABLED, 0);
1821                         }
1822                 }
1823                 if(use_displist) {
1824                         glMultMatrixf(dob->mat);
1825                         if(ED_view3d_boundbox_clip(rv3d, dob->mat, &bb))
1826                                 glCallList(displist);
1827                         glLoadMatrixf(rv3d->viewmat);
1828                 }
1829                 else {
1830                         copy_m4_m4(dob->ob->obmat, dob->mat);
1831                         draw_object(scene, ar, v3d, &tbase, DRAW_CONSTCOLOR);
1832                 }
1833
1834                 tbase.object->dt= dt;
1835                 tbase.object->dtx= dtx;
1836                 tbase.object->transflag= transflag;
1837         }
1838         
1839         /* Transp afterdraw disabled, afterdraw only stores base pointers, and duplis can be same obj */
1840         
1841         free_object_duplilist(lb);      /* does restore */
1842         
1843         if(use_displist)
1844                 glDeleteLists(displist, 1);
1845 }
1846
1847 static void draw_dupli_objects(Scene *scene, ARegion *ar, View3D *v3d, Base *base)
1848 {
1849         /* define the color here so draw_dupli_objects_color can be called
1850         * from the set loop */
1851         
1852         int color= (base->flag & SELECT)?TH_SELECT:TH_WIRE;
1853         /* debug */
1854         if(base->object->dup_group && base->object->dup_group->id.us<1)
1855                 color= TH_REDALERT;
1856         
1857         draw_dupli_objects_color(scene, ar, v3d, base, color);
1858 }
1859
1860 void view3d_update_depths_rect(ARegion *ar, ViewDepths *d, rcti *rect)
1861 {
1862         int x, y, w, h; 
1863         rcti r;
1864         /* clamp rect by area */
1865
1866         r.xmin= 0;
1867         r.xmax= ar->winx-1;
1868         r.ymin= 0;
1869         r.ymax= ar->winy-1;
1870
1871         /* Constrain rect to depth bounds */
1872         BLI_isect_rcti(&r, rect, rect);
1873
1874         /* assign values to compare with the ViewDepths */
1875         x= rect->xmin;
1876         y= rect->ymin;
1877
1878         w= rect->xmax - rect->xmin;
1879         h= rect->ymax - rect->ymin;
1880
1881         if(w <= 0 || h <= 0) {
1882                 if(d->depths)
1883                         MEM_freeN(d->depths);
1884                 d->depths= NULL;
1885
1886                 d->damaged= FALSE;
1887         }
1888         else if(        d->w != w ||
1889                 d->h != h ||
1890                 d->x != x ||
1891                 d->y != y ||
1892                 d->depths==NULL
1893         ) {
1894                 d->x= x;
1895                 d->y= y;
1896                 d->w= w;
1897                 d->h= h;
1898
1899                 if(d->depths)
1900                         MEM_freeN(d->depths);
1901
1902                 d->depths= MEM_mallocN(sizeof(float)*d->w*d->h,"View depths Subset");
1903                 
1904                 d->damaged= TRUE;
1905         }
1906
1907         if(d->damaged) {
1908                 glReadPixels(ar->winrct.xmin+d->x,ar->winrct.ymin+d->y, d->w,d->h, GL_DEPTH_COMPONENT,GL_FLOAT, d->depths);
1909                 glGetDoublev(GL_DEPTH_RANGE,d->depth_range);
1910                 d->damaged= FALSE;
1911         }
1912 }
1913
1914 /* note, with nouveau drivers the glReadPixels() is very slow. [#24339] */
1915 void ED_view3d_depth_update(ARegion *ar)
1916 {
1917         RegionView3D *rv3d= ar->regiondata;
1918         
1919         /* Create storage for, and, if necessary, copy depth buffer */
1920         if(!rv3d->depths) rv3d->depths= MEM_callocN(sizeof(ViewDepths),"ViewDepths");
1921         if(rv3d->depths) {
1922                 ViewDepths *d= rv3d->depths;
1923                 if(d->w != ar->winx ||
1924                    d->h != ar->winy ||
1925                    !d->depths) {
1926                         d->w= ar->winx;
1927                         d->h= ar->winy;
1928                         if(d->depths)
1929                                 MEM_freeN(d->depths);
1930                         d->depths= MEM_mallocN(sizeof(float)*d->w*d->h,"View depths");
1931                         d->damaged= 1;
1932                 }
1933                 
1934                 if(d->damaged) {
1935                         glReadPixels(ar->winrct.xmin,ar->winrct.ymin,d->w,d->h,
1936                                                  GL_DEPTH_COMPONENT,GL_FLOAT, d->depths);
1937                         
1938                         glGetDoublev(GL_DEPTH_RANGE,d->depth_range);
1939                         
1940                         d->damaged= 0;
1941                 }
1942         }
1943 }
1944
1945 /* utility function to find the closest Z value, use for autodepth */
1946 float view3d_depth_near(ViewDepths *d)
1947 {
1948         /* convert to float for comparisons */
1949         const float near= (float)d->depth_range[0];
1950         const float far_real= (float)d->depth_range[1];
1951         float far= far_real;
1952
1953         const float *depths= d->depths;
1954         float depth= FLT_MAX;
1955         int i= (int)d->w * (int)d->h; /* cast to avoid short overflow */
1956
1957         /* far is both the starting 'far' value
1958          * and the closest value found. */      
1959         while(i--) {
1960                 depth= *depths++;
1961                 if((depth < far) && (depth > near)) {
1962                         far= depth;
1963                 }
1964         }
1965
1966         return far == far_real ? FLT_MAX : far;
1967 }
1968
1969 void draw_depth_gpencil(Scene *scene, ARegion *ar, View3D *v3d)
1970 {
1971         short zbuf= v3d->zbuf;
1972         RegionView3D *rv3d= ar->regiondata;
1973
1974         setwinmatrixview3d(ar, v3d, NULL);      /* 0= no pick rect */
1975         setviewmatrixview3d(scene, v3d, rv3d);  /* note: calls where_is_object for camera... */
1976
1977         mul_m4_m4m4(rv3d->persmat, rv3d->viewmat, rv3d->winmat);
1978         invert_m4_m4(rv3d->persinv, rv3d->persmat);
1979         invert_m4_m4(rv3d->viewinv, rv3d->viewmat);
1980
1981         glClear(GL_DEPTH_BUFFER_BIT);
1982
1983         glLoadMatrixf(rv3d->viewmat);
1984
1985         v3d->zbuf= TRUE;
1986         glEnable(GL_DEPTH_TEST);
1987
1988         draw_gpencil_view3d(scene, v3d, ar, 1);
1989         
1990         v3d->zbuf= zbuf;
1991
1992 }
1993
1994 void draw_depth(Scene *scene, ARegion *ar, View3D *v3d, int (* func)(void *))
1995 {
1996         RegionView3D *rv3d= ar->regiondata;
1997         Base *base;
1998         short zbuf= v3d->zbuf;
1999         short flag= v3d->flag;
2000         float glalphaclip= U.glalphaclip;
2001         int obcenter_dia= U.obcenter_dia;
2002         /* temp set drawtype to solid */
2003         
2004         /* Setting these temporarily is not nice */
2005         v3d->flag &= ~V3D_SELECT_OUTLINE;
2006         U.glalphaclip = 0.5; /* not that nice but means we wont zoom into billboards */
2007         U.obcenter_dia= 0;
2008         
2009         setwinmatrixview3d(ar, v3d, NULL);      /* 0= no pick rect */
2010         setviewmatrixview3d(scene, v3d, rv3d);  /* note: calls where_is_object for camera... */
2011         
2012         mul_m4_m4m4(rv3d->persmat, rv3d->viewmat, rv3d->winmat);
2013         invert_m4_m4(rv3d->persinv, rv3d->persmat);
2014         invert_m4_m4(rv3d->viewinv, rv3d->viewmat);
2015         
2016         glClear(GL_DEPTH_BUFFER_BIT);
2017         
2018         glLoadMatrixf(rv3d->viewmat);
2019 //      persp(PERSP_STORE);  // store correct view for persp(PERSP_VIEW) calls
2020         
2021         if(rv3d->rflag & RV3D_CLIPPING) {
2022                 view3d_set_clipping(rv3d);
2023         }
2024         
2025         v3d->zbuf= TRUE;
2026         glEnable(GL_DEPTH_TEST);
2027         
2028         /* draw set first */
2029         if(scene->set) {
2030                 Scene *sce_iter;
2031                 for(SETLOOPER(scene->set, sce_iter, base)) {
2032                         if(v3d->lay & base->lay) {
2033                                 if (func == NULL || func(base)) {
2034                                         draw_object(scene, ar, v3d, base, 0);
2035                                         if(base->object->transflag & OB_DUPLI) {
2036                                                 draw_dupli_objects_color(scene, ar, v3d, base, TH_WIRE);
2037                                         }
2038                                 }
2039                         }
2040                 }
2041         }
2042         
2043         for(base= scene->base.first; base; base= base->next) {
2044                 if(v3d->lay & base->lay) {
2045                         if (func == NULL || func(base)) {
2046                                 /* dupli drawing */
2047                                 if(base->object->transflag & OB_DUPLI) {
2048                                         draw_dupli_objects(scene, ar, v3d, base);
2049                                 }
2050                                 draw_object(scene, ar, v3d, base, 0);
2051                         }
2052                 }
2053         }
2054         
2055         /* this isnt that nice, draw xray objects as if they are normal */
2056         if (    v3d->afterdraw_transp.first ||
2057                         v3d->afterdraw_xray.first || 
2058                         v3d->afterdraw_xraytransp.first
2059         ) {
2060                 View3DAfter *v3da, *next;
2061                 int mask_orig;
2062
2063                 v3d->xray= TRUE;
2064                 
2065                 /* transp materials can change the depth mask, see #21388 */
2066                 glGetIntegerv(GL_DEPTH_WRITEMASK, &mask_orig);
2067
2068
2069                 if(v3d->afterdraw_xray.first || v3d->afterdraw_xraytransp.first) {
2070                         glDepthFunc(GL_ALWAYS); /* always write into the depth bufer, overwriting front z values */
2071                         for(v3da= v3d->afterdraw_xray.first; v3da; v3da= next) {
2072                                 next= v3da->next;
2073                                 draw_object(scene, ar, v3d, v3da->base, 0);
2074                         }
2075                         glDepthFunc(GL_LEQUAL); /* Now write the depth buffer normally */
2076                 }
2077
2078                 /* draw 3 passes, transp/xray/xraytransp */
2079                 v3d->xray= FALSE;
2080                 v3d->transp= TRUE;
2081                 for(v3da= v3d->afterdraw_transp.first; v3da; v3da= next) {
2082                         next= v3da->next;
2083                         draw_object(scene, ar, v3d, v3da->base, 0);
2084                         BLI_remlink(&v3d->afterdraw_transp, v3da);
2085                         MEM_freeN(v3da);
2086                 }
2087
2088                 v3d->xray= TRUE;
2089                 v3d->transp= FALSE;  
2090                 for(v3da= v3d->afterdraw_xray.first; v3da; v3da= next) {
2091                         next= v3da->next;
2092                         draw_object(scene, ar, v3d, v3da->base, 0);
2093                         BLI_remlink(&v3d->afterdraw_xray, v3da);
2094                         MEM_freeN(v3da);
2095                 }
2096
2097                 v3d->xray= TRUE;
2098                 v3d->transp= TRUE;
2099                 for(v3da= v3d->afterdraw_xraytransp.first; v3da; v3da= next) {
2100                         next= v3da->next;
2101                         draw_object(scene, ar, v3d, v3da->base, 0);
2102                         BLI_remlink(&v3d->afterdraw_xraytransp, v3da);
2103                         MEM_freeN(v3da);
2104                 }
2105
2106                 
2107                 v3d->xray= FALSE;
2108                 v3d->transp= FALSE;
2109
2110                 glDepthMask(mask_orig);
2111         }
2112         
2113         if(rv3d->rflag & RV3D_CLIPPING)
2114                 view3d_clr_clipping();
2115         
2116         v3d->zbuf = zbuf;
2117         if(!v3d->zbuf) glDisable(GL_DEPTH_TEST);
2118
2119         U.glalphaclip = glalphaclip;
2120         v3d->flag = flag;
2121         U.obcenter_dia= obcenter_dia;
2122 }
2123
2124 typedef struct View3DShadow {
2125         struct View3DShadow *next, *prev;
2126         GPULamp *lamp;
2127 } View3DShadow;
2128
2129 static void gpu_render_lamp_update(Scene *scene, View3D *v3d, Object *ob, Object *par, float obmat[][4], ListBase *shadows)
2130 {
2131         GPULamp *lamp;
2132         Lamp *la = (Lamp*)ob->data;
2133         View3DShadow *shadow;
2134         
2135         lamp = GPU_lamp_from_blender(scene, ob, par);
2136         
2137         if(lamp) {
2138                 GPU_lamp_update(lamp, ob->lay, (ob->restrictflag & OB_RESTRICT_RENDER), obmat);
2139                 GPU_lamp_update_colors(lamp, la->r, la->g, la->b, la->energy);
2140                 
2141                 if((ob->lay & v3d->lay) && GPU_lamp_has_shadow_buffer(lamp)) {
2142                         shadow= MEM_callocN(sizeof(View3DShadow), "View3DShadow");
2143                         shadow->lamp = lamp;
2144                         BLI_addtail(shadows, shadow);
2145                 }
2146         }
2147 }
2148
2149 static void gpu_update_lamps_shadows(Scene *scene, View3D *v3d)
2150 {
2151         ListBase shadows;
2152         View3DShadow *shadow;
2153         Scene *sce_iter;
2154         Base *base;
2155         Object *ob;
2156         
2157         shadows.first= shadows.last= NULL;
2158         
2159         /* update lamp transform and gather shadow lamps */
2160         for(SETLOOPER(scene, sce_iter, base)) {
2161                 ob= base->object;
2162                 
2163                 if(ob->type == OB_LAMP)
2164                         gpu_render_lamp_update(scene, v3d, ob, NULL, ob->obmat, &shadows);
2165                 
2166                 if (ob->transflag & OB_DUPLI) {
2167                         DupliObject *dob;
2168                         ListBase *lb = object_duplilist(scene, ob);
2169                         
2170                         for(dob=lb->first; dob; dob=dob->next)
2171                                 if(dob->ob->type==OB_LAMP)
2172                                         gpu_render_lamp_update(scene, v3d, dob->ob, ob, dob->mat, &shadows);
2173                         
2174                         free_object_duplilist(lb);
2175                 }
2176         }
2177         
2178         /* render shadows after updating all lamps, nested object_duplilist
2179                 * don't work correct since it's replacing object matrices */
2180         for(shadow=shadows.first; shadow; shadow=shadow->next) {
2181                 /* this needs to be done better .. */
2182                 float viewmat[4][4], winmat[4][4];
2183                 int drawtype, lay, winsize, flag2=v3d->flag2;
2184                 ARegion ar= {NULL};
2185                 RegionView3D rv3d= {{{0}}};
2186                 
2187                 drawtype= v3d->drawtype;
2188                 lay= v3d->lay;
2189                 
2190                 v3d->drawtype = OB_SOLID;
2191                 v3d->lay &= GPU_lamp_shadow_layer(shadow->lamp);
2192                 v3d->flag2 &= ~V3D_SOLID_TEX;
2193                 v3d->flag2 |= V3D_RENDER_OVERRIDE | V3D_RENDER_SHADOW;
2194                 
2195                 GPU_lamp_shadow_buffer_bind(shadow->lamp, viewmat, &winsize, winmat);
2196
2197                 ar.regiondata= &rv3d;
2198                 ar.regiontype= RGN_TYPE_WINDOW;
2199                 rv3d.persp= RV3D_CAMOB;
2200                 copy_m4_m4(rv3d.winmat, winmat);
2201                 copy_m4_m4(rv3d.viewmat, viewmat);
2202                 invert_m4_m4(rv3d.viewinv, rv3d.viewmat);
2203                 mul_m4_m4m4(rv3d.persmat, rv3d.viewmat, rv3d.winmat);
2204                 invert_m4_m4(rv3d.persinv, rv3d.viewinv);
2205
2206                 ED_view3d_draw_offscreen(scene, v3d, &ar, winsize, winsize, viewmat, winmat);
2207                 GPU_lamp_shadow_buffer_unbind(shadow->lamp);
2208                 
2209                 v3d->drawtype= drawtype;
2210                 v3d->lay= lay;
2211                 v3d->flag2 = flag2;
2212         }
2213         
2214         BLI_freelistN(&shadows);
2215 }
2216
2217 /* *********************** customdata **************** */
2218
2219 CustomDataMask ED_view3d_datamask(Scene *scene, View3D *v3d)
2220 {
2221         CustomDataMask mask= 0;
2222
2223         if((v3d->drawtype == OB_TEXTURE) || ((v3d->drawtype == OB_SOLID) && (v3d->flag2 & V3D_SOLID_TEX))) {
2224                 mask |= CD_MASK_MTFACE | CD_MASK_MCOL;
2225
2226                 if(scene->gm.matmode == GAME_MAT_GLSL)
2227                         mask |= CD_MASK_ORCO;
2228         }
2229
2230         return mask;
2231 }
2232 /* goes over all modes and view3d settings */
2233 CustomDataMask ED_viewedit_datamask(bScreen *screen)
2234 {
2235         Scene *scene= screen->scene;
2236         Object *ob= scene->basact ? scene->basact->object : NULL;
2237         CustomDataMask mask = CD_MASK_BAREMESH;
2238         ScrArea *sa;
2239         
2240         /* check if we need tfaces & mcols due to face select or texture paint */
2241         if(paint_facesel_test(ob) || (ob && ob->mode & OB_MODE_TEXTURE_PAINT))
2242                 mask |= CD_MASK_MTFACE | CD_MASK_MCOL;
2243         
2244         /* check if we need tfaces & mcols due to view mode */
2245         for(sa = screen->areabase.first; sa; sa = sa->next) {
2246                 if(sa->spacetype == SPACE_VIEW3D) {
2247                         mask |= ED_view3d_datamask(scene, (View3D *)sa->spacedata.first);
2248                 }
2249         }
2250         
2251         /* check if we need mcols due to vertex paint or weightpaint */
2252         if(ob) {
2253                 if(ob->mode & OB_MODE_VERTEX_PAINT)
2254                         mask |= CD_MASK_MCOL;
2255                 if(ob->mode & OB_MODE_WEIGHT_PAINT)
2256                         mask |= CD_MASK_WEIGHT_MCOL;
2257         }
2258
2259         return mask;
2260 }
2261
2262 static void view3d_main_area_setup_view(Scene *scene, View3D *v3d, ARegion *ar, float viewmat[][4], float winmat[][4])
2263 {
2264         RegionView3D *rv3d= ar->regiondata;
2265
2266         /* setup window matrices */
2267         if(winmat)
2268                 copy_m4_m4(rv3d->winmat, winmat);
2269         else
2270                 setwinmatrixview3d(ar, v3d, NULL); /* NULL= no pickrect */
2271         
2272         /* setup view matrix */
2273         if(viewmat)
2274                 copy_m4_m4(rv3d->viewmat, viewmat);
2275         else
2276                 setviewmatrixview3d(scene, v3d, rv3d);  /* note: calls where_is_object for camera... */
2277         
2278         /* update utilitity matrices */
2279         mul_m4_m4m4(rv3d->persmat, rv3d->viewmat, rv3d->winmat);
2280         invert_m4_m4(rv3d->persinv, rv3d->persmat);
2281         invert_m4_m4(rv3d->viewinv, rv3d->viewmat);
2282
2283         /* calculate pixelsize factor once, is used for lamps and obcenters */
2284         {
2285                 /* note:  '1.0f / len_v3(v1)'  replaced  'len_v3(rv3d->viewmat[0])'
2286                  * because of float point precision problems at large values [#23908] */
2287                 float v1[3], v2[3];
2288                 float len1, len2;
2289
2290                 v1[0]= rv3d->persmat[0][0];
2291                 v1[1]= rv3d->persmat[1][0];
2292                 v1[2]= rv3d->persmat[2][0];
2293
2294                 v2[0]= rv3d->persmat[0][1];
2295                 v2[1]= rv3d->persmat[1][1];
2296                 v2[2]= rv3d->persmat[2][1];
2297                 
2298                 len1= 1.0f / len_v3(v1);
2299                 len2= 1.0f / len_v3(v2);
2300
2301                 rv3d->pixsize = (2.0f * MAX2(len1, len2)) / (float)MAX2(ar->winx, ar->winy);
2302         }
2303
2304         /* set for opengl */
2305         glMatrixMode(GL_PROJECTION);
2306         glLoadMatrixf(rv3d->winmat);
2307         glMatrixMode(GL_MODELVIEW);
2308         glLoadMatrixf(rv3d->viewmat);
2309 }
2310
2311 void ED_view3d_draw_offscreen(Scene *scene, View3D *v3d, ARegion *ar, int winx, int winy, float viewmat[][4], float winmat[][4])
2312 {
2313         RegionView3D *rv3d= ar->regiondata;
2314         Base *base;
2315         float backcol[3];
2316         int bwinx, bwiny;
2317         rcti brect;
2318
2319         glPushMatrix();
2320
2321         /* set temporary new size */
2322         bwinx= ar->winx;
2323         bwiny= ar->winy;
2324         brect= ar->winrct;
2325         
2326         ar->winx= winx;
2327         ar->winy= winy; 
2328         ar->winrct.xmin= 0;
2329         ar->winrct.ymin= 0;
2330         ar->winrct.xmax= winx;
2331         ar->winrct.ymax= winy;
2332         
2333         
2334         /* set flags */
2335         G.f |= G_RENDER_OGL;
2336
2337         /* free images which can have changed on frame-change
2338          * warning! can be slow so only free animated images - campbell */
2339         GPU_free_images_anim();
2340         
2341         /* shadow buffers, before we setup matrices */
2342         if(draw_glsl_material(scene, NULL, v3d, v3d->drawtype))
2343                 gpu_update_lamps_shadows(scene, v3d);
2344
2345         /* set background color, fallback on the view background color */
2346         if(scene->world) {
2347                 if(scene->r.color_mgt_flag & R_COLOR_MANAGEMENT)
2348                         linearrgb_to_srgb_v3_v3(backcol, &scene->world->horr);
2349                 else
2350                         copy_v3_v3(backcol, &scene->world->horr);
2351                 glClearColor(backcol[0], backcol[1], backcol[2], 0.0);
2352         }
2353         else {
2354                 UI_ThemeClearColor(TH_BACK);    
2355         }
2356
2357         glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
2358
2359         /* setup view matrices */
2360         view3d_main_area_setup_view(scene, v3d, ar, viewmat, winmat);
2361
2362         if(rv3d->rflag & RV3D_CLIPPING)
2363                 view3d_draw_clipping(rv3d);
2364
2365         /* set zbuffer */
2366         if(v3d->drawtype > OB_WIRE) {
2367                 v3d->zbuf= TRUE;
2368                 glEnable(GL_DEPTH_TEST);
2369         }
2370         else
2371                 v3d->zbuf= FALSE;
2372
2373         if(rv3d->rflag & RV3D_CLIPPING)
2374                 view3d_set_clipping(rv3d);
2375
2376         /* draw set first */
2377         if(scene->set) {
2378                 Scene *sce_iter;
2379                 for(SETLOOPER(scene->set, sce_iter, base)) {
2380                         if(v3d->lay & base->lay) {
2381                                 UI_ThemeColorBlend(TH_WIRE, TH_BACK, 0.6f);
2382                                 draw_object(scene, ar, v3d, base, DRAW_CONSTCOLOR|DRAW_SCENESET);
2383                                 
2384                                 if(base->object->transflag & OB_DUPLI)
2385                                         draw_dupli_objects_color(scene, ar, v3d, base, TH_WIRE);
2386                         }
2387                 }
2388         }
2389         
2390         /* then draw not selected and the duplis, but skip editmode object */
2391         for(base= scene->base.first; base; base= base->next) {
2392                 if(v3d->lay & base->lay) {
2393                         /* dupli drawing */
2394                         if(base->object->transflag & OB_DUPLI)
2395                                 draw_dupli_objects(scene, ar, v3d, base);
2396
2397                         draw_object(scene, ar, v3d, base, 0);
2398                 }
2399         }
2400
2401         /* must be before xray draw which clears the depth buffer */
2402         if(v3d->zbuf) glDisable(GL_DEPTH_TEST);
2403         draw_gpencil_view3d(scene, v3d, ar, 1);
2404         if(v3d->zbuf) glEnable(GL_DEPTH_TEST);
2405
2406         /* transp and X-ray afterdraw stuff */
2407         if(v3d->afterdraw_transp.first)         view3d_draw_transp(scene, ar, v3d);
2408         if(v3d->afterdraw_xray.first)           view3d_draw_xray(scene, ar, v3d, 1);    // clears zbuffer if it is used!
2409         if(v3d->afterdraw_xraytransp.first)     view3d_draw_xraytransp(scene, ar, v3d, 1);
2410
2411         if(rv3d->rflag & RV3D_CLIPPING)
2412                 view3d_clr_clipping();
2413
2414         /* cleanup */
2415         if(v3d->zbuf) {
2416                 v3d->zbuf= FALSE;
2417                 glDisable(GL_DEPTH_TEST);
2418         }
2419
2420         /* draw grease-pencil stuff */
2421         ED_region_pixelspace(ar);
2422
2423         /* draw grease-pencil stuff - needed to get paint-buffer shown too (since it's 2D) */
2424         draw_gpencil_view3d(scene, v3d, ar, 0);
2425
2426         /* freeing the images again here could be done after the operator runs, leaving for now */
2427         GPU_free_images_anim();
2428
2429         /* restore size */
2430         ar->winx= bwinx;
2431         ar->winy= bwiny;
2432         ar->winrct = brect;
2433
2434         glPopMatrix();
2435
2436         glColor4ub(255, 255, 255, 255); // XXX, without this the sequencer flickers with opengl draw enabled, need to find out why - campbell
2437
2438         G.f &= ~G_RENDER_OGL;
2439 }
2440
2441 /* utility func for ED_view3d_draw_offscreen */
2442 ImBuf *ED_view3d_draw_offscreen_imbuf(Scene *scene, View3D *v3d, ARegion *ar, int sizex, int sizey, unsigned int flag, char err_out[256])
2443 {
2444         RegionView3D *rv3d= ar->regiondata;
2445         ImBuf *ibuf;
2446         GPUOffScreen *ofs;
2447         
2448         /* state changes make normal drawing go weird otherwise */
2449         glPushAttrib(GL_LIGHTING_BIT);
2450
2451         /* bind */
2452         ofs= GPU_offscreen_create(&sizex, &sizey, err_out);
2453         if(ofs == NULL)
2454                 return NULL;
2455
2456         GPU_offscreen_bind(ofs);
2457
2458         /* render 3d view */
2459         if(rv3d->persp==RV3D_CAMOB && v3d->camera) {
2460                 float winmat[4][4];
2461                 float _clipsta, _clipend, _lens, _yco, _dx, _dy, _sensor_x= DEFAULT_SENSOR_WIDTH, _sensor_y= DEFAULT_SENSOR_HEIGHT;
2462                 short _fov_mode= CAMERA_FOV_AUTO;
2463                 rctf _viewplane;
2464
2465                 object_camera_matrix(&scene->r, v3d->camera, sizex, sizey, 0, winmat, &_viewplane, &_clipsta, &_clipend, &_lens,
2466                         &_sensor_x, &_sensor_y, &_fov_mode, &_yco, &_dx, &_dy);
2467
2468                 ED_view3d_draw_offscreen(scene, v3d, ar, sizex, sizey, NULL, winmat);
2469         }
2470         else {
2471                 ED_view3d_draw_offscreen(scene, v3d, ar, sizex, sizey, NULL, NULL);
2472         }
2473
2474         /* read in pixels & stamp */
2475         ibuf= IMB_allocImBuf(sizex, sizey, 32, flag);
2476
2477         if(ibuf->rect_float)
2478                 glReadPixels(0, 0, sizex, sizey, GL_RGBA, GL_FLOAT, ibuf->rect_float);
2479         else if(ibuf->rect)
2480                 glReadPixels(0, 0, sizex, sizey, GL_RGBA, GL_UNSIGNED_BYTE, ibuf->rect);
2481         
2482         //if((scene->r.stamp & R_STAMP_ALL) && (scene->r.stamp & R_STAMP_DRAW))
2483         //      BKE_stamp_buf(scene, NULL, rr->rectf, rr->rectx, rr->recty, 4);
2484
2485         /* unbind */
2486         GPU_offscreen_unbind(ofs);
2487         GPU_offscreen_free(ofs);
2488
2489         glPopAttrib();
2490         
2491         if(ibuf->rect_float && ibuf->rect)
2492                 IMB_rect_from_float(ibuf);
2493         
2494         return ibuf;
2495 }
2496
2497 /* creates own 3d views, used by the sequencer */
2498 ImBuf *ED_view3d_draw_offscreen_imbuf_simple(Scene *scene, Object *camera, int width, int height, unsigned int flag, int drawtype, char err_out[256])
2499 {
2500         View3D v3d= {NULL};
2501         ARegion ar= {NULL};
2502         RegionView3D rv3d= {{{0}}};
2503
2504         /* connect data */
2505         v3d.regionbase.first= v3d.regionbase.last= &ar;
2506         ar.regiondata= &rv3d;
2507         ar.regiontype= RGN_TYPE_WINDOW;
2508
2509         v3d.camera= camera;
2510         v3d.lay= scene->lay;
2511         v3d.drawtype = drawtype;
2512         v3d.flag2 = V3D_RENDER_OVERRIDE;
2513
2514         rv3d.persp= RV3D_CAMOB;
2515
2516         copy_m4_m4(rv3d.viewinv, v3d.camera->obmat);
2517         normalize_m4(rv3d.viewinv);
2518         invert_m4_m4(rv3d.viewmat, rv3d.viewinv);
2519
2520         {
2521                 float _yco, _dx, _dy, _sensor_x= DEFAULT_SENSOR_WIDTH, _sensor_y= DEFAULT_SENSOR_HEIGHT;
2522                 short _fov_mode= CAMERA_FOV_AUTO;
2523                 rctf _viewplane;
2524                 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);
2525         }
2526
2527         mul_m4_m4m4(rv3d.persmat, rv3d.viewmat, rv3d.winmat);
2528         invert_m4_m4(rv3d.persinv, rv3d.viewinv);
2529
2530         return ED_view3d_draw_offscreen_imbuf(scene, &v3d, &ar, width, height, flag, err_out);
2531
2532         // seq_view3d_cb(scene, cfra, render_size, seqrectx, seqrecty);
2533 }
2534
2535
2536 /* NOTE: the info that this uses is updated in ED_refresh_viewport_fps(), 
2537  * which currently gets called during SCREEN_OT_animation_step.
2538  */
2539 static void draw_viewport_fps(Scene *scene, ARegion *ar)
2540 {
2541         ScreenFrameRateInfo *fpsi= scene->fps_info;
2542         float fps;
2543         char printable[16];
2544         int i, tot;
2545         
2546         if (!fpsi || !fpsi->lredrawtime || !fpsi->redrawtime)
2547                 return;
2548         
2549         printable[0] = '\0';
2550         
2551 #if 0
2552         /* this is too simple, better do an average */
2553         fps = (float)(1.0/(fpsi->lredrawtime-fpsi->redrawtime))
2554 #else
2555         fpsi->redrawtimes_fps[fpsi->redrawtime_index] = (float)(1.0/(fpsi->lredrawtime-fpsi->redrawtime));
2556         
2557         for (i=0, tot=0, fps=0.0f ; i < REDRAW_FRAME_AVERAGE ; i++) {
2558                 if (fpsi->redrawtimes_fps[i]) {
2559                         fps += fpsi->redrawtimes_fps[i];
2560                         tot++;
2561                 }
2562         }
2563         if (tot) {
2564                 fpsi->redrawtime_index = (fpsi->redrawtime_index + 1) % REDRAW_FRAME_AVERAGE;
2565                 
2566                 //fpsi->redrawtime_index++;
2567                 //if (fpsi->redrawtime >= REDRAW_FRAME_AVERAGE)
2568                 //      fpsi->redrawtime = 0;
2569                 
2570                 fps = fps / tot;
2571         }
2572 #endif
2573
2574         /* is this more then half a frame behind? */
2575         if (fps+0.5f < (float)(FPS)) {
2576                 UI_ThemeColor(TH_REDALERT);
2577                 BLI_snprintf(printable, sizeof(printable), "fps: %.2f", fps);
2578         } 
2579         else {
2580                 UI_ThemeColor(TH_TEXT_HI);
2581                 BLI_snprintf(printable, sizeof(printable), "fps: %i", (int)(fps+0.5f));
2582         }
2583         
2584         BLF_draw_default_ascii(22,  ar->winy-17, 0.0f, printable, sizeof(printable)-1);
2585 }
2586
2587 /* warning: this function has duplicate drawing in ED_view3d_draw_offscreen() */
2588 static void view3d_main_area_draw_objects(const bContext *C, ARegion *ar, const char **grid_unit)
2589 {
2590         Scene *scene= CTX_data_scene(C);
2591         View3D *v3d = CTX_wm_view3d(C);
2592         RegionView3D *rv3d= CTX_wm_region_view3d(C);
2593         Base *base;
2594         float backcol[3];
2595         unsigned int lay_used;
2596
2597         /* shadow buffers, before we setup matrices */
2598         if(draw_glsl_material(scene, NULL, v3d, v3d->drawtype))
2599                 gpu_update_lamps_shadows(scene, v3d);
2600         
2601         /* reset default OpenGL lights if needed (i.e. after preferences have been altered) */
2602         if (rv3d->rflag & RV3D_GPULIGHT_UPDATE) {
2603                 rv3d->rflag &= ~RV3D_GPULIGHT_UPDATE;
2604                 GPU_default_lights();
2605         }
2606
2607         /* clear background */
2608         if((v3d->flag2 & V3D_RENDER_OVERRIDE) && scene->world) {
2609                 if(scene->r.color_mgt_flag & R_COLOR_MANAGEMENT)
2610                         linearrgb_to_srgb_v3_v3(backcol, &scene->world->horr);
2611                 else
2612                         copy_v3_v3(backcol, &scene->world->horr);
2613                 glClearColor(backcol[0], backcol[1], backcol[2], 0.0);
2614         }
2615         else
2616                 UI_ThemeClearColor(TH_BACK);
2617
2618         glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
2619         
2620         /* setup view matrices */
2621         view3d_main_area_setup_view(scene, v3d, ar, NULL, NULL);
2622
2623         ED_region_draw_cb_draw(C, ar, REGION_DRAW_PRE_VIEW);
2624
2625         if(rv3d->rflag & RV3D_CLIPPING)
2626                 view3d_draw_clipping(rv3d);
2627         
2628         /* set zbuffer after we draw clipping region */
2629         if(v3d->drawtype > OB_WIRE) {
2630                 v3d->zbuf= TRUE;
2631                 glEnable(GL_DEPTH_TEST);
2632         }
2633         else
2634                 v3d->zbuf= FALSE;
2635
2636         /* enables anti-aliasing for 3D view drawing */
2637         /*if (!(U.gameflags & USER_DISABLE_AA))
2638                 glEnable(GL_MULTISAMPLE_ARB);*/
2639         
2640         // needs to be done always, gridview is adjusted in drawgrid() now
2641         rv3d->gridview= v3d->grid;
2642
2643         if((rv3d->view == RV3D_VIEW_USER) || (rv3d->persp != RV3D_ORTHO)) {
2644                 if ((v3d->flag2 & V3D_RENDER_OVERRIDE)==0) {
2645                         drawfloor(scene, v3d, grid_unit);
2646                 }
2647                 if(rv3d->persp==RV3D_CAMOB) {
2648                         if(scene->world) {
2649                                 if(scene->world->mode & WO_STARS) {
2650                                         RE_make_stars(NULL, scene, star_stuff_init_func, star_stuff_vertex_func,
2651                                                                   star_stuff_term_func);
2652                                 }
2653                         }
2654                         if ((v3d->flag2 & V3D_RENDER_OVERRIDE)==0) {
2655                                 if(v3d->flag & V3D_DISPBGPICS) draw_bgpic(scene, ar, v3d);
2656                         }
2657                 }
2658         }
2659         else {
2660                 if ((v3d->flag2 & V3D_RENDER_OVERRIDE)==0) {
2661                         ED_region_pixelspace(ar);
2662                         drawgrid(&scene->unit, ar, v3d, grid_unit);
2663                         /* XXX make function? replaces persp(1) */
2664                         glMatrixMode(GL_PROJECTION);
2665                         glLoadMatrixf(rv3d->winmat);
2666                         glMatrixMode(GL_MODELVIEW);
2667                         glLoadMatrixf(rv3d->viewmat);
2668
2669                         if(v3d->flag & V3D_DISPBGPICS) {
2670                                 draw_bgpic(scene, ar, v3d);
2671                         }
2672                 }
2673         }
2674         
2675         if(rv3d->rflag & RV3D_CLIPPING)
2676                 view3d_set_clipping(rv3d);
2677
2678         /* draw set first */
2679         if(scene->set) {
2680                 Scene *sce_iter;
2681                 for(SETLOOPER(scene->set, sce_iter, base)) {
2682                         
2683                         if(v3d->lay & base->lay) {
2684                                 
2685                                 UI_ThemeColorBlend(TH_WIRE, TH_BACK, 0.6f);
2686                                 draw_object(scene, ar, v3d, base, DRAW_CONSTCOLOR|DRAW_SCENESET);
2687                                 
2688                                 if(base->object->transflag & OB_DUPLI) {
2689                                         draw_dupli_objects_color(scene, ar, v3d, base, TH_WIRE);
2690                                 }
2691                         }
2692                 }
2693                 
2694                 /* Transp and X-ray afterdraw stuff for sets is done later */
2695         }
2696
2697         lay_used= 0;
2698
2699         /* then draw not selected and the duplis, but skip editmode object */
2700         for(base= scene->base.first; base; base= base->next) {
2701                 lay_used |= base->lay & ((1<<20)-1);
2702
2703                 if(v3d->lay & base->lay) {
2704                         
2705                         /* dupli drawing */
2706                         if(base->object->transflag & OB_DUPLI) {
2707                                 draw_dupli_objects(scene, ar, v3d, base);
2708                         }
2709                         if((base->flag & SELECT)==0) {
2710                                 if(base->object!=scene->obedit) 
2711                                         draw_object(scene, ar, v3d, base, 0);
2712                         }
2713                 }
2714         }
2715
2716         if(v3d->lay_used != lay_used) { /* happens when loading old files or loading with UI load */
2717                 /* find header and force tag redraw */
2718                 ScrArea *sa= CTX_wm_area(C);
2719                 ARegion *ar_header= BKE_area_find_region_type(sa, RGN_TYPE_HEADER);
2720                 ED_region_tag_redraw(ar_header); /* can be NULL */
2721                 v3d->lay_used= lay_used;
2722         }
2723
2724         /* draw selected and editmode */
2725         for(base= scene->base.first; base; base= base->next) {
2726                 if(v3d->lay & base->lay) {
2727                         if (base->object==scene->obedit || ( base->flag & SELECT) ) 
2728                                 draw_object(scene, ar, v3d, base, 0);
2729                 }
2730         }
2731
2732 //      REEB_draw();
2733
2734         if ((v3d->flag2 & V3D_RENDER_OVERRIDE)==0) {
2735                 /* must be before xray draw which clears the depth buffer */
2736                 if(v3d->zbuf) glDisable(GL_DEPTH_TEST);
2737                 draw_gpencil_view3d(scene, v3d, ar, 1);
2738                 if(v3d->zbuf) glEnable(GL_DEPTH_TEST);
2739         }
2740
2741         /* Transp and X-ray afterdraw stuff */
2742         if(v3d->afterdraw_transp.first)         view3d_draw_transp(scene, ar, v3d);
2743         if(v3d->afterdraw_xray.first)           view3d_draw_xray(scene, ar, v3d, 1);    // clears zbuffer if it is used!
2744         if(v3d->afterdraw_xraytransp.first)     view3d_draw_xraytransp(scene, ar, v3d, 1);
2745         
2746         ED_region_draw_cb_draw(C, ar, REGION_DRAW_POST_VIEW);
2747
2748         if(rv3d->rflag & RV3D_CLIPPING)
2749                 view3d_clr_clipping();
2750         
2751         BIF_draw_manipulator(C);
2752         
2753         /* Disable back anti-aliasing */
2754         /*if (!(U.gameflags & USER_DISABLE_AA))
2755                 glDisable(GL_MULTISAMPLE_ARB);*/
2756
2757         if(v3d->zbuf) {
2758                 v3d->zbuf= FALSE;
2759                 glDisable(GL_DEPTH_TEST);
2760         }
2761
2762         if ((v3d->flag2 & V3D_RENDER_OVERRIDE)==0) {
2763                 BDR_drawSketch(C);
2764         }
2765
2766         if ((U.ndof_flag & NDOF_SHOW_GUIDE) && (rv3d->viewlock != RV3D_LOCKED) && (rv3d->persp != RV3D_CAMOB))
2767                 // TODO: draw something else (but not this) during fly mode
2768                 draw_rotation_guide(rv3d);
2769
2770 }
2771
2772 static void view3d_main_area_draw_info(const bContext *C, ARegion *ar, const char *grid_unit)
2773 {
2774         Scene *scene= CTX_data_scene(C);
2775         View3D *v3d = CTX_wm_view3d(C);
2776         RegionView3D *rv3d= CTX_wm_region_view3d(C);
2777         bScreen *screen= CTX_wm_screen(C);
2778
2779         Object *ob;
2780
2781         if(rv3d->persp==RV3D_CAMOB)
2782                 drawviewborder(scene, ar, v3d);
2783
2784         if ((v3d->flag2 & V3D_RENDER_OVERRIDE)==0) {
2785                 /* draw grease-pencil stuff - needed to get paint-buffer shown too (since it's 2D) */
2786         //      if (v3d->flag2 & V3D_DISPGP)
2787                         draw_gpencil_view3d(scene, v3d, ar, 0);
2788
2789                 drawcursor(scene, ar, v3d);
2790         }
2791         
2792         if(U.uiflag & USER_SHOW_ROTVIEWICON)
2793                 draw_view_axis(rv3d);
2794         else    
2795                 draw_view_icon(rv3d);
2796         
2797         if((U.uiflag & USER_SHOW_FPS) && screen->animtimer) {
2798                 draw_viewport_fps(scene, ar);
2799         }
2800         else if(U.uiflag & USER_SHOW_VIEWPORTNAME) {
2801                 draw_viewport_name(ar, v3d);
2802         }
2803         if (grid_unit) { /* draw below the viewport name */
2804                 char tstr[32]= "";
2805
2806                 UI_ThemeColor(TH_TEXT_HI);
2807                 if(v3d->grid != 1.0f) {
2808                         BLI_snprintf(tstr, sizeof(tstr), "%s x %.4g", grid_unit, v3d->grid);
2809                 }
2810
2811                 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 */
2812         }
2813
2814         ob= OBACT;
2815         if(U.uiflag & USER_DRAWVIEWINFO) 
2816                 draw_selected_name(scene, ob);
2817 }
2818
2819 void view3d_main_area_draw(const bContext *C, ARegion *ar)
2820 {
2821         View3D *v3d = CTX_wm_view3d(C);
2822         const char *grid_unit= NULL;
2823
2824         view3d_main_area_draw_objects(C, ar, &grid_unit);
2825
2826         ED_region_pixelspace(ar);
2827         
2828         view3d_main_area_draw_info(C, ar, grid_unit);
2829
2830         v3d->flag |= V3D_INVALID_BACKBUF;
2831 }
2832