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