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