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