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