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