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