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