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