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