Fix for using non camera objects as a camera having zero area view-frame
[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         /* increase size for unicode languages (Chinese in utf-8...) */
809 #ifdef WITH_INTERNATIONAL
810         char tmpstr[96];
811 #else
812         char tmpstr[32];
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         /* fallback for non camera objects */
954         params.clipsta = v3d->near;
955         params.clipend = v3d->far;
956         BKE_camera_params_from_object(&params, v3d->camera);
957         if (no_shift) {
958                 params.shiftx = 0.0f;
959                 params.shifty = 0.0f;
960         }
961         BKE_camera_params_compute_viewplane(&params, scene->r.xsch, scene->r.ysch, scene->r.xasp, scene->r.yasp);
962         rect_camera = params.viewplane;
963
964         /* get camera border within viewport */
965         r_viewborder->xmin = ((rect_camera.xmin - rect_view.xmin) / BLI_rctf_size_x(&rect_view)) * ar->winx;
966         r_viewborder->xmax = ((rect_camera.xmax - rect_view.xmin) / BLI_rctf_size_x(&rect_view)) * ar->winx;
967         r_viewborder->ymin = ((rect_camera.ymin - rect_view.ymin) / BLI_rctf_size_y(&rect_view)) * ar->winy;
968         r_viewborder->ymax = ((rect_camera.ymax - rect_view.ymin) / BLI_rctf_size_y(&rect_view)) * ar->winy;
969 }
970
971 void ED_view3d_calc_camera_border_size(Scene *scene, ARegion *ar, View3D *v3d, RegionView3D *rv3d, float r_size[2])
972 {
973         rctf viewborder;
974
975         view3d_camera_border(scene, ar, v3d, rv3d, &viewborder, true, true);
976         r_size[0] = BLI_rctf_size_x(&viewborder);
977         r_size[1] = BLI_rctf_size_y(&viewborder);
978 }
979
980 void ED_view3d_calc_camera_border(Scene *scene, ARegion *ar, View3D *v3d, RegionView3D *rv3d,
981                                   rctf *r_viewborder, const bool no_shift)
982 {
983         view3d_camera_border(scene, ar, v3d, rv3d, r_viewborder, no_shift, false);
984 }
985
986 static void drawviewborder_grid3(float x1, float x2, float y1, float y2, float fac)
987 {
988         float x3, y3, x4, y4;
989
990         x3 = x1 + fac * (x2 - x1);
991         y3 = y1 + fac * (y2 - y1);
992         x4 = x1 + (1.0f - fac) * (x2 - x1);
993         y4 = y1 + (1.0f - fac) * (y2 - y1);
994
995         glBegin(GL_LINES);
996         glVertex2f(x1, y3);
997         glVertex2f(x2, y3);
998
999         glVertex2f(x1, y4);
1000         glVertex2f(x2, y4);
1001
1002         glVertex2f(x3, y1);
1003         glVertex2f(x3, y2);
1004
1005         glVertex2f(x4, y1);
1006         glVertex2f(x4, y2);
1007         glEnd();
1008 }
1009
1010 /* harmonious triangle */
1011 static void drawviewborder_triangle(float x1, float x2, float y1, float y2, const char golden, const char dir)
1012 {
1013         float ofs;
1014         float w = x2 - x1;
1015         float h = y2 - y1;
1016
1017         glBegin(GL_LINES);
1018         if (w > h) {
1019                 if (golden) {
1020                         ofs = w * (1.0f - (1.0f / 1.61803399f));
1021                 }
1022                 else {
1023                         ofs = h * (h / w);
1024                 }
1025                 if (dir == 'B') SWAP(float, y1, y2);
1026
1027                 glVertex2f(x1, y1);
1028                 glVertex2f(x2, y2);
1029
1030                 glVertex2f(x2, y1);
1031                 glVertex2f(x1 + (w - ofs), y2);
1032
1033                 glVertex2f(x1, y2);
1034                 glVertex2f(x1 + ofs, y1);
1035         }
1036         else {
1037                 if (golden) {
1038                         ofs = h * (1.0f - (1.0f / 1.61803399f));
1039                 }
1040                 else {
1041                         ofs = w * (w / h);
1042                 }
1043                 if (dir == 'B') SWAP(float, x1, x2);
1044
1045                 glVertex2f(x1, y1);
1046                 glVertex2f(x2, y2);
1047
1048                 glVertex2f(x2, y1);
1049                 glVertex2f(x1, y1 + ofs);
1050
1051                 glVertex2f(x1, y2);
1052                 glVertex2f(x2, y1 + (h - ofs));
1053         }
1054         glEnd();
1055 }
1056
1057 static void drawviewborder(Scene *scene, ARegion *ar, View3D *v3d)
1058 {
1059         float hmargin, vmargin;
1060         float x1, x2, y1, y2;
1061         float x1i, x2i, y1i, y2i;
1062         float x3, y3, x4, y4;
1063         rctf viewborder;
1064         Camera *ca = NULL;
1065         RegionView3D *rv3d = (RegionView3D *)ar->regiondata;
1066         
1067         if (v3d->camera == NULL)
1068                 return;
1069         if (v3d->camera->type == OB_CAMERA)
1070                 ca = v3d->camera->data;
1071         
1072         ED_view3d_calc_camera_border(scene, ar, v3d, rv3d, &viewborder, false);
1073         /* the offsets */
1074         x1 = viewborder.xmin;
1075         y1 = viewborder.ymin;
1076         x2 = viewborder.xmax;
1077         y2 = viewborder.ymax;
1078         
1079         /* apply offsets so the real 3D camera shows through */
1080
1081         /* note: quite un-scientific but without this bit extra
1082          * 0.0001 on the lower left the 2D border sometimes
1083          * obscures the 3D camera border */
1084         /* note: with VIEW3D_CAMERA_BORDER_HACK defined this error isn't noticeable
1085          * but keep it here in case we need to remove the workaround */
1086         x1i = (int)(x1 - 1.0001f);
1087         y1i = (int)(y1 - 1.0001f);
1088         x2i = (int)(x2 + (1.0f - 0.0001f));
1089         y2i = (int)(y2 + (1.0f - 0.0001f));
1090         
1091         /* passepartout, specified in camera edit buttons */
1092         if (ca && (ca->flag & CAM_SHOWPASSEPARTOUT) && ca->passepartalpha > 0.000001f) {
1093                 if (ca->passepartalpha == 1.0f) {
1094                         glColor3f(0, 0, 0);
1095                 }
1096                 else {
1097                         glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
1098                         glEnable(GL_BLEND);
1099                         glColor4f(0, 0, 0, ca->passepartalpha);
1100                 }
1101                 if (x1i > 0.0f)
1102                         glRectf(0.0, (float)ar->winy, x1i, 0.0);
1103                 if (x2i < (float)ar->winx)
1104                         glRectf(x2i, (float)ar->winy, (float)ar->winx, 0.0);
1105                 if (y2i < (float)ar->winy)
1106                         glRectf(x1i, (float)ar->winy, x2i, y2i);
1107                 if (y2i > 0.0f)
1108                         glRectf(x1i, y1i, x2i, 0.0);
1109                 
1110                 glDisable(GL_BLEND);
1111         }
1112
1113         /* edge */
1114         glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
1115
1116         setlinestyle(0);
1117
1118         UI_ThemeColor(TH_BACK);
1119                 
1120         glRectf(x1i, y1i, x2i, y2i);
1121
1122 #ifdef VIEW3D_CAMERA_BORDER_HACK
1123         if (view3d_camera_border_hack_test == true) {
1124                 glColor3ubv(view3d_camera_border_hack_col);
1125                 glRectf(x1i + 1, y1i + 1, x2i - 1, y2i - 1);
1126                 view3d_camera_border_hack_test = false;
1127         }
1128 #endif
1129
1130         setlinestyle(3);
1131
1132         /* outer line not to confuse with object selecton */
1133         if (v3d->flag2 & V3D_LOCK_CAMERA) {
1134                 UI_ThemeColor(TH_REDALERT);
1135                 glRectf(x1i - 1, y1i - 1, x2i + 1, y2i + 1);
1136         }
1137
1138         UI_ThemeColor(TH_WIRE);
1139         glRectf(x1i, y1i, x2i, y2i);
1140
1141         /* border */
1142         if (scene->r.mode & R_BORDER) {
1143                 cpack(0);
1144                 x3 = x1 + scene->r.border.xmin * (x2 - x1);
1145                 y3 = y1 + scene->r.border.ymin * (y2 - y1);
1146                 x4 = x1 + scene->r.border.xmax * (x2 - x1);
1147                 y4 = y1 + scene->r.border.ymax * (y2 - y1);
1148                 
1149                 cpack(0x4040FF);
1150                 glRecti(x3,  y3,  x4,  y4);
1151         }
1152
1153         /* safety border */
1154         if (ca) {
1155                 if (ca->dtx & CAM_DTX_CENTER) {
1156                         UI_ThemeColorBlendShade(TH_WIRE, TH_BACK, 0.25, 0);
1157
1158                         x3 = x1 + 0.5f * (x2 - x1);
1159                         y3 = y1 + 0.5f * (y2 - y1);
1160
1161                         glBegin(GL_LINES);
1162                         glVertex2f(x1, y3);
1163                         glVertex2f(x2, y3);
1164
1165                         glVertex2f(x3, y1);
1166                         glVertex2f(x3, y2);
1167                         glEnd();
1168                 }
1169
1170                 if (ca->dtx & CAM_DTX_CENTER_DIAG) {
1171                         UI_ThemeColorBlendShade(TH_WIRE, TH_BACK, 0.25, 0);
1172
1173                         glBegin(GL_LINES);
1174                         glVertex2f(x1, y1);
1175                         glVertex2f(x2, y2);
1176
1177                         glVertex2f(x1, y2);
1178                         glVertex2f(x2, y1);
1179                         glEnd();
1180                 }
1181
1182                 if (ca->dtx & CAM_DTX_THIRDS) {
1183                         UI_ThemeColorBlendShade(TH_WIRE, TH_BACK, 0.25, 0);
1184                         drawviewborder_grid3(x1, x2, y1, y2, 1.0f / 3.0f);
1185                 }
1186
1187                 if (ca->dtx & CAM_DTX_GOLDEN) {
1188                         UI_ThemeColorBlendShade(TH_WIRE, TH_BACK, 0.25, 0);
1189                         drawviewborder_grid3(x1, x2, y1, y2, 1.0f - (1.0f / 1.61803399f));
1190                 }
1191
1192                 if (ca->dtx & CAM_DTX_GOLDEN_TRI_A) {
1193                         UI_ThemeColorBlendShade(TH_WIRE, TH_BACK, 0.25, 0);
1194                         drawviewborder_triangle(x1, x2, y1, y2, 0, 'A');
1195                 }
1196
1197                 if (ca->dtx & CAM_DTX_GOLDEN_TRI_B) {
1198                         UI_ThemeColorBlendShade(TH_WIRE, TH_BACK, 0.25, 0);
1199                         drawviewborder_triangle(x1, x2, y1, y2, 0, 'B');
1200                 }
1201
1202                 if (ca->dtx & CAM_DTX_HARMONY_TRI_A) {
1203                         UI_ThemeColorBlendShade(TH_WIRE, TH_BACK, 0.25, 0);
1204                         drawviewborder_triangle(x1, x2, y1, y2, 1, 'A');
1205                 }
1206
1207                 if (ca->dtx & CAM_DTX_HARMONY_TRI_B) {
1208                         UI_ThemeColorBlendShade(TH_WIRE, TH_BACK, 0.25, 0);
1209                         drawviewborder_triangle(x1, x2, y1, y2, 1, 'B');
1210                 }
1211
1212                 if (ca->flag & CAM_SHOWTITLESAFE) {
1213                         UI_ThemeColorBlendShade(TH_WIRE, TH_BACK, 0.25, 0);
1214
1215                         hmargin = 0.1f  * (x2 - x1);
1216                         vmargin = 0.05f * (y2 - y1);
1217                         uiDrawBox(GL_LINE_LOOP, x1 + hmargin, y1 + vmargin, x2 - hmargin, y2 - vmargin, 2.0f);
1218
1219                         hmargin = 0.035f * (x2 - x1);
1220                         vmargin = 0.035f * (y2 - y1);
1221                         uiDrawBox(GL_LINE_LOOP, x1 + hmargin, y1 + vmargin, x2 - hmargin, y2 - vmargin, 2.0f);
1222                 }
1223                 if (ca->flag & CAM_SHOWSENSOR) {
1224                         /* determine sensor fit, and get sensor x/y, for auto fit we
1225                          * assume and square sensor and only use sensor_x */
1226                         float sizex = scene->r.xsch * scene->r.xasp;
1227                         float sizey = scene->r.ysch * scene->r.yasp;
1228                         int sensor_fit = BKE_camera_sensor_fit(ca->sensor_fit, sizex, sizey);
1229                         float sensor_x = ca->sensor_x;
1230                         float sensor_y = (ca->sensor_fit == CAMERA_SENSOR_FIT_AUTO) ? ca->sensor_x : ca->sensor_y;
1231
1232                         /* determine sensor plane */
1233                         rctf rect;
1234
1235                         if (sensor_fit == CAMERA_SENSOR_FIT_HOR) {
1236                                 float sensor_scale = (x2i - x1i) / sensor_x;
1237                                 float sensor_height = sensor_scale * sensor_y;
1238
1239                                 rect.xmin = x1i;
1240                                 rect.xmax = x2i;
1241                                 rect.ymin = (y1i + y2i) * 0.5f - sensor_height * 0.5f;
1242                                 rect.ymax = rect.ymin + sensor_height;
1243                         }
1244                         else {
1245                                 float sensor_scale = (y2i - y1i) / sensor_y;
1246                                 float sensor_width = sensor_scale * sensor_x;
1247
1248                                 rect.xmin = (x1i + x2i) * 0.5f - sensor_width * 0.5f;
1249                                 rect.xmax = rect.xmin + sensor_width;
1250                                 rect.ymin = y1i;
1251                                 rect.ymax = y2i;
1252                         }
1253
1254                         /* draw */
1255                         UI_ThemeColorShade(TH_WIRE, 100);
1256                         uiDrawBox(GL_LINE_LOOP, rect.xmin, rect.ymin, rect.xmax, rect.ymax, 2.0f);
1257                 }
1258         }
1259
1260         setlinestyle(0);
1261         glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
1262
1263         /* camera name - draw in highlighted text color */
1264         if (ca && (ca->flag & CAM_SHOWNAME)) {
1265                 UI_ThemeColor(TH_TEXT_HI);
1266                 BLF_draw_default(x1i, y1i - 15, 0.0f, v3d->camera->id.name + 2, sizeof(v3d->camera->id.name) - 2);
1267                 UI_ThemeColor(TH_WIRE);
1268         }
1269 }
1270
1271 /* *********************** backdraw for selection *************** */
1272
1273 static void backdrawview3d(Scene *scene, ARegion *ar, View3D *v3d)
1274 {
1275         RegionView3D *rv3d = ar->regiondata;
1276         struct Base *base = scene->basact;
1277         int multisample_enabled;
1278
1279         BLI_assert(ar->regiontype == RGN_TYPE_WINDOW);
1280
1281         if (base && (base->object->mode & (OB_MODE_VERTEX_PAINT | OB_MODE_WEIGHT_PAINT) ||
1282                      BKE_paint_select_face_test(base->object)))
1283         {
1284                 /* do nothing */
1285         }
1286         else if ((base && (base->object->mode & OB_MODE_PARTICLE_EDIT)) &&
1287                  v3d->drawtype > OB_WIRE && (v3d->flag & V3D_ZBUF_SELECT))
1288         {
1289                 /* do nothing */
1290         }
1291         else if (scene->obedit && v3d->drawtype > OB_WIRE &&
1292                  (v3d->flag & V3D_ZBUF_SELECT))
1293         {
1294                 /* do nothing */
1295         }
1296         else {
1297                 v3d->flag &= ~V3D_INVALID_BACKBUF;
1298                 return;
1299         }
1300
1301         if (!(v3d->flag & V3D_INVALID_BACKBUF))
1302                 return;
1303
1304 #if 0
1305         if (test) {
1306                 if (qtest()) {
1307                         addafterqueue(ar->win, BACKBUFDRAW, 1);
1308                         return;
1309                 }
1310         }
1311 #endif
1312
1313         if (v3d->drawtype > OB_WIRE) v3d->zbuf = TRUE;
1314         
1315         /* dithering and AA break color coding, so disable */
1316         glDisable(GL_DITHER);
1317
1318         multisample_enabled = glIsEnabled(GL_MULTISAMPLE_ARB);
1319         if (multisample_enabled)
1320                 glDisable(GL_MULTISAMPLE_ARB);
1321
1322         if (U.ogl_multisamples != USER_MULTISAMPLE_NONE) {
1323                 /* for multisample we use an offscreen FBO. multisample drawing can fail
1324                  * with color coded selection drawing, and reading back depths from such
1325                  * a buffer can also cause a few seconds freeze on OS X / NVidia. */
1326                 int w = BLI_rcti_size_x(&ar->winrct);
1327                 int h = BLI_rcti_size_y(&ar->winrct);
1328                 char error[256];
1329
1330                 if (rv3d->gpuoffscreen) {
1331                         if (GPU_offscreen_width(rv3d->gpuoffscreen)  != w ||
1332                             GPU_offscreen_height(rv3d->gpuoffscreen) != h)
1333                         {
1334                                 GPU_offscreen_free(rv3d->gpuoffscreen);
1335                                 rv3d->gpuoffscreen = NULL;
1336                         }
1337                 }
1338
1339                 if (!rv3d->gpuoffscreen) {
1340                         rv3d->gpuoffscreen = GPU_offscreen_create(w, h, error);
1341
1342                         if (!rv3d->gpuoffscreen)
1343                                 fprintf(stderr, "Failed to create offscreen selection buffer for multisample: %s\n", error);
1344                 }
1345         }
1346
1347         if (rv3d->gpuoffscreen)
1348                 GPU_offscreen_bind(rv3d->gpuoffscreen);
1349         else
1350                 glScissor(ar->winrct.xmin, ar->winrct.ymin, BLI_rcti_size_x(&ar->winrct), BLI_rcti_size_y(&ar->winrct));
1351
1352         glClearColor(0.0, 0.0, 0.0, 0.0); 
1353         if (v3d->zbuf) {
1354                 glEnable(GL_DEPTH_TEST);
1355                 glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
1356         }
1357         else {
1358                 glClear(GL_COLOR_BUFFER_BIT);
1359                 glDisable(GL_DEPTH_TEST);
1360         }
1361         
1362         if (rv3d->rflag & RV3D_CLIPPING)
1363                 ED_view3d_clipping_set(rv3d);
1364         
1365         G.f |= G_BACKBUFSEL;
1366         
1367         if (base && (base->lay & v3d->lay))
1368                 draw_object_backbufsel(scene, v3d, rv3d, base->object);
1369         
1370         if (rv3d->gpuoffscreen)
1371                 GPU_offscreen_unbind(rv3d->gpuoffscreen);
1372         else
1373                 ar->swap = 0; /* mark invalid backbuf for wm draw */
1374
1375         v3d->flag &= ~V3D_INVALID_BACKBUF;
1376
1377         G.f &= ~G_BACKBUFSEL;
1378         v3d->zbuf = FALSE;
1379         glDisable(GL_DEPTH_TEST);
1380         glEnable(GL_DITHER);
1381         if (multisample_enabled)
1382                 glEnable(GL_MULTISAMPLE_ARB);
1383
1384         if (rv3d->rflag & RV3D_CLIPPING)
1385                 ED_view3d_clipping_disable();
1386
1387         /* it is important to end a view in a transform compatible with buttons */
1388 //      persp(PERSP_WIN);  /* set ortho */
1389
1390 }
1391
1392 void view3d_opengl_read_pixels(ARegion *ar, int x, int y, int w, int h, int format, int type, void *data)
1393 {
1394         RegionView3D *rv3d = ar->regiondata;
1395
1396         if (rv3d->gpuoffscreen) {
1397                 GPU_offscreen_bind(rv3d->gpuoffscreen);
1398                 glReadBuffer(GL_COLOR_ATTACHMENT0_EXT);
1399                 glReadPixels(x, y, w, h, format, type, data);
1400                 GPU_offscreen_unbind(rv3d->gpuoffscreen);
1401         }
1402         else {
1403                 glReadPixels(ar->winrct.xmin + x, ar->winrct.ymin + y, w, h, format, type, data);
1404         }
1405 }
1406
1407 /* XXX depth reading exception, for code not using gpu offscreen */
1408 static void view3d_opengl_read_Z_pixels(ARegion *ar, int x, int y, int w, int h, int format, int type, void *data)
1409 {
1410
1411         glReadPixels(ar->winrct.xmin + x, ar->winrct.ymin + y, w, h, format, type, data);
1412 }
1413
1414 void view3d_validate_backbuf(ViewContext *vc)
1415 {
1416         if (vc->v3d->flag & V3D_INVALID_BACKBUF)
1417                 backdrawview3d(vc->scene, vc->ar, vc->v3d);
1418 }
1419
1420 /* samples a single pixel (copied from vpaint) */
1421 unsigned int view3d_sample_backbuf(ViewContext *vc, int x, int y)
1422 {
1423         unsigned int col;
1424         
1425         if (x >= vc->ar->winx || y >= vc->ar->winy) {
1426                 return 0;
1427         }
1428
1429         view3d_validate_backbuf(vc);
1430
1431         view3d_opengl_read_pixels(vc->ar, x, y, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, &col);
1432         glReadBuffer(GL_BACK);
1433         
1434         if (ENDIAN_ORDER == B_ENDIAN) {
1435                 BLI_endian_switch_uint32(&col);
1436         }
1437         
1438         return WM_framebuffer_to_index(col);
1439 }
1440
1441 /* reads full rect, converts indices */
1442 ImBuf *view3d_read_backbuf(ViewContext *vc, short xmin, short ymin, short xmax, short ymax)
1443 {
1444         unsigned int *dr, *rd;
1445         struct ImBuf *ibuf, *ibuf1;
1446         int a;
1447         short xminc, yminc, xmaxc, ymaxc, xs, ys;
1448         
1449         /* clip */
1450         if (xmin < 0) xminc = 0; else xminc = xmin;
1451         if (xmax >= vc->ar->winx) xmaxc = vc->ar->winx - 1; else xmaxc = xmax;
1452         if (xminc > xmaxc) return NULL;
1453
1454         if (ymin < 0) yminc = 0; else yminc = ymin;
1455         if (ymax >= vc->ar->winy) ymaxc = vc->ar->winy - 1; else ymaxc = ymax;
1456         if (yminc > ymaxc) return NULL;
1457         
1458         ibuf = IMB_allocImBuf((xmaxc - xminc + 1), (ymaxc - yminc + 1), 32, IB_rect);
1459
1460         view3d_validate_backbuf(vc);
1461
1462         view3d_opengl_read_pixels(vc->ar,
1463                      xminc, yminc,
1464                      (xmaxc - xminc + 1),
1465                      (ymaxc - yminc + 1),
1466                      GL_RGBA, GL_UNSIGNED_BYTE, ibuf->rect);
1467
1468         glReadBuffer(GL_BACK);
1469
1470         if (ENDIAN_ORDER == B_ENDIAN) IMB_convert_rgba_to_abgr(ibuf);
1471
1472         a = (xmaxc - xminc + 1) * (ymaxc - yminc + 1);
1473         dr = ibuf->rect;
1474         while (a--) {
1475                 if (*dr) *dr = WM_framebuffer_to_index(*dr);
1476                 dr++;
1477         }
1478         
1479         /* put clipped result back, if needed */
1480         if (xminc == xmin && xmaxc == xmax && yminc == ymin && ymaxc == ymax)
1481                 return ibuf;
1482         
1483         ibuf1 = IMB_allocImBuf( (xmax - xmin + 1), (ymax - ymin + 1), 32, IB_rect);
1484         rd = ibuf->rect;
1485         dr = ibuf1->rect;
1486
1487         for (ys = ymin; ys <= ymax; ys++) {
1488                 for (xs = xmin; xs <= xmax; xs++, dr++) {
1489                         if (xs >= xminc && xs <= xmaxc && ys >= yminc && ys <= ymaxc) {
1490                                 *dr = *rd;
1491                                 rd++;
1492                         }
1493                 }
1494         }
1495         IMB_freeImBuf(ibuf);
1496         return ibuf1;
1497 }
1498
1499 /* smart function to sample a rect spiralling outside, nice for backbuf selection */
1500 unsigned int view3d_sample_backbuf_rect(ViewContext *vc, const int mval[2], int size,
1501                                         unsigned int min, unsigned int max, float *r_dist, short strict,
1502                                         void *handle, bool (*indextest)(void *handle, unsigned int index))
1503 {
1504         struct ImBuf *buf;
1505         unsigned int *bufmin, *bufmax, *tbuf;
1506         int minx, miny;
1507         int a, b, rc, nr, amount, dirvec[4][2];
1508         int distance = 0;
1509         unsigned int index = 0;
1510         bool indexok = false;
1511
1512         amount = (size - 1) / 2;
1513
1514         minx = mval[0] - (amount + 1);
1515         miny = mval[1] - (amount + 1);
1516         buf = view3d_read_backbuf(vc, minx, miny, minx + size - 1, miny + size - 1);
1517         if (!buf) return 0;
1518
1519         rc = 0;
1520         
1521         dirvec[0][0] = 1; dirvec[0][1] = 0;
1522         dirvec[1][0] = 0; dirvec[1][1] = -size;
1523         dirvec[2][0] = -1; dirvec[2][1] = 0;
1524         dirvec[3][0] = 0; dirvec[3][1] = size;
1525         
1526         bufmin = buf->rect;
1527         tbuf = buf->rect;
1528         bufmax = buf->rect + size * size;
1529         tbuf += amount * size + amount;
1530         
1531         for (nr = 1; nr <= size; nr++) {
1532                 
1533                 for (a = 0; a < 2; a++) {
1534                         for (b = 0; b < nr; b++, distance++) {
1535                                 if (*tbuf && *tbuf >= min && *tbuf < max) {  /* we got a hit */
1536                                         if (strict) {
1537                                                 indexok =  indextest(handle, *tbuf - min + 1);
1538                                                 if (indexok) {
1539                                                         *r_dist = sqrtf((float)distance);
1540                                                         index = *tbuf - min + 1;
1541                                                         goto exit; 
1542                                                 }
1543                                         }
1544                                         else {
1545                                                 *r_dist = sqrtf((float)distance);  /* XXX, this distance is wrong - */
1546                                                 index = *tbuf - min + 1;  /* messy yah, but indices start at 1 */
1547                                                 goto exit;
1548                                         }
1549                                 }
1550                                 
1551                                 tbuf += (dirvec[rc][0] + dirvec[rc][1]);
1552                                 
1553                                 if (tbuf < bufmin || tbuf >= bufmax) {
1554                                         goto exit;
1555                                 }
1556                         }
1557                         rc++;
1558                         rc &= 3;
1559                 }
1560         }
1561
1562 exit:
1563         IMB_freeImBuf(buf);
1564         return index;
1565 }
1566
1567
1568 /* ************************************************************* */
1569
1570 static void view3d_draw_bgpic(Scene *scene, ARegion *ar, View3D *v3d,
1571                               const bool do_foreground, const bool do_camera_frame)
1572 {
1573         RegionView3D *rv3d = ar->regiondata;
1574         BGpic *bgpic;
1575         int fg_flag = do_foreground ? V3D_BGPIC_FOREGROUND : 0;
1576
1577         for (bgpic = v3d->bgpicbase.first; bgpic; bgpic = bgpic->next) {
1578
1579                 if ((bgpic->flag & V3D_BGPIC_FOREGROUND) != fg_flag)
1580                         continue;
1581
1582                 if ((bgpic->view == 0) || /* zero for any */
1583                     (bgpic->view & (1 << rv3d->view)) || /* check agaist flags */
1584                     (rv3d->persp == RV3D_CAMOB && bgpic->view == (1 << RV3D_VIEW_CAMERA)))
1585                 {
1586                         float image_aspect[2];
1587                         float fac, asp, zoomx, zoomy;
1588                         float x1, y1, x2, y2;
1589
1590                         ImBuf *ibuf = NULL, *freeibuf, *releaseibuf;
1591
1592                         Image *ima;
1593                         MovieClip *clip;
1594
1595                         /* disable individual images */
1596                         if ((bgpic->flag & V3D_BGPIC_DISABLED))
1597                                 continue;
1598
1599                         freeibuf = NULL;
1600                         releaseibuf = NULL;
1601                         if (bgpic->source == V3D_BGPIC_IMAGE) {
1602                                 ima = bgpic->ima;
1603                                 if (ima == NULL)
1604                                         continue;
1605                                 BKE_image_user_frame_calc(&bgpic->iuser, CFRA, 0);
1606                                 if (ima->source == IMA_SRC_SEQUENCE && !(bgpic->iuser.flag & IMA_USER_FRAME_IN_RANGE)) {
1607                                         ibuf = NULL; /* frame is out of range, dont show */
1608                                 }
1609                                 else {
1610                                         ibuf = BKE_image_acquire_ibuf(ima, &bgpic->iuser, NULL);
1611                                         releaseibuf = ibuf;
1612                                 }
1613
1614                                 image_aspect[0] = ima->aspx;
1615                                 image_aspect[1] = ima->aspx;
1616                         }
1617                         else if (bgpic->source == V3D_BGPIC_MOVIE) {
1618                                 clip = NULL;
1619
1620                                 /* TODO: skip drawing when out of frame range (as image sequences do above) */
1621
1622                                 if (bgpic->flag & V3D_BGPIC_CAMERACLIP) {
1623                                         if (scene->camera)
1624                                                 clip = BKE_object_movieclip_get(scene, scene->camera, true);
1625                                 }
1626                                 else {
1627                                         clip = bgpic->clip;
1628                                 }
1629
1630                                 if (clip == NULL)
1631                                         continue;
1632
1633                                 BKE_movieclip_user_set_frame(&bgpic->cuser, CFRA);
1634                                 ibuf = BKE_movieclip_get_ibuf(clip, &bgpic->cuser);
1635
1636                                 image_aspect[0] = clip->aspx;
1637                                 image_aspect[1] = clip->aspy;
1638
1639                                 /* working with ibuf from image and clip has got different workflow now.
1640                                  * ibuf acquired from clip is referenced by cache system and should
1641                                  * be dereferenced after usage. */
1642                                 freeibuf = ibuf;
1643                         }
1644                         else {
1645                                 /* perhaps when loading future files... */
1646                                 BLI_assert(0);
1647                                 copy_v2_fl(image_aspect, 1.0f);
1648                         }
1649
1650                         if (ibuf == NULL)
1651                                 continue;
1652
1653                         if ((ibuf->rect == NULL && ibuf->rect_float == NULL) || ibuf->channels != 4) { /* invalid image format */
1654                                 if (freeibuf)
1655                                         IMB_freeImBuf(freeibuf);
1656                                 if (releaseibuf)
1657                                         BKE_image_release_ibuf(ima, releaseibuf, NULL);
1658
1659                                 continue;
1660                         }
1661
1662                         if (ibuf->rect == NULL)
1663                                 IMB_rect_from_float(ibuf);
1664
1665                         if (rv3d->persp == RV3D_CAMOB) {
1666
1667                                 if (do_camera_frame) {
1668                                         rctf vb;
1669                                         ED_view3d_calc_camera_border(scene, ar, v3d, rv3d, &vb, false);
1670                                         x1 = vb.xmin;
1671                                         y1 = vb.ymin;
1672                                         x2 = vb.xmax;
1673                                         y2 = vb.ymax;
1674                                 }
1675                                 else {
1676                                         x1 = ar->winrct.xmin;
1677                                         y1 = ar->winrct.ymin;
1678                                         x2 = ar->winrct.xmax;
1679                                         y2 = ar->winrct.ymax;
1680                                 }
1681
1682                                 /* apply offset last - camera offset is different to offset in blender units */
1683                                 /* so this has some sane way of working - this matches camera's shift _exactly_ */
1684                                 {
1685                                         const float max_dim = max_ff(x2 - x1, y2 - y1);
1686                                         const float xof_scale = bgpic->xof * max_dim;
1687                                         const float yof_scale = bgpic->yof * max_dim;
1688
1689                                         x1 += xof_scale;
1690                                         y1 += yof_scale;
1691                                         x2 += xof_scale;
1692                                         y2 += yof_scale;
1693                                 }
1694
1695                                 /* aspect correction */
1696                                 if (bgpic->flag & V3D_BGPIC_CAMERA_ASPECT) {
1697                                         /* apply aspect from clip */
1698                                         const float w_src = ibuf->x * image_aspect[0];
1699                                         const float h_src = ibuf->y * image_aspect[1];
1700
1701                                         /* destination aspect is already applied from the camera frame */
1702                                         const float w_dst = x1 - x2;
1703                                         const float h_dst = y1 - y2;
1704
1705                                         const float asp_src = w_src / h_src;
1706                                         const float asp_dst = w_dst / h_dst;
1707
1708                                         if (fabsf(asp_src - asp_dst) >= FLT_EPSILON) {
1709                                                 if ((asp_src > asp_dst) == ((bgpic->flag & V3D_BGPIC_CAMERA_CROP) != 0)) {
1710                                                         /* fit X */
1711                                                         const float div = asp_src / asp_dst;
1712                                                         const float cent = (x1 + x2) / 2.0f;
1713                                                         x1 = ((x1 - cent) * div) + cent;
1714                                                         x2 = ((x2 - cent) * div) + cent;
1715                                                 }
1716                                                 else {
1717                                                         /* fit Y */
1718                                                         const float div = asp_dst / asp_src;
1719                                                         const float cent = (y1 + y2) / 2.0f;
1720                                                         y1 = ((y1 - cent) * div) + cent;
1721                                                         y2 = ((y2 - cent) * div) + cent;
1722                                                 }
1723                                         }
1724                                 }
1725                         }
1726                         else {
1727                                 float tvec[3];
1728                                 float sco[2];
1729                                 const float mval_f[2] = {1.0f, 0.0f};
1730                                 const float co_zero[3] = {0};
1731                                 float zfac;
1732
1733                                 /* calc window coord */
1734                                 zfac = ED_view3d_calc_zfac(rv3d, co_zero, NULL);
1735                                 ED_view3d_win_to_delta(ar, mval_f, tvec, zfac);
1736                                 fac = max_ff(fabsf(tvec[0]), max_ff(fabsf(tvec[1]), fabsf(tvec[2]))); /* largest abs axis */
1737                                 fac = 1.0f / fac;
1738
1739                                 asp = (float)ibuf->y / (float)ibuf->x;
1740
1741                                 zero_v3(tvec);
1742                                 ED_view3d_project_float_v2_m4(ar, tvec, sco, rv3d->persmat);
1743
1744                                 x1 =  sco[0] + fac * (bgpic->xof - bgpic->size);
1745                                 y1 =  sco[1] + asp * fac * (bgpic->yof - bgpic->size);
1746                                 x2 =  sco[0] + fac * (bgpic->xof + bgpic->size);
1747                                 y2 =  sco[1] + asp * fac * (bgpic->yof + bgpic->size);
1748                         }
1749
1750                         /* complete clip? */
1751
1752                         if (x2 < 0 || y2 < 0 || x1 > ar->winx || y1 > ar->winy) {
1753                                 if (freeibuf)
1754                                         IMB_freeImBuf(freeibuf);
1755                                 if (releaseibuf)
1756                                         BKE_image_release_ibuf(ima, releaseibuf, NULL);
1757
1758                                 continue;
1759                         }
1760
1761                         zoomx = (x2 - x1) / ibuf->x;
1762                         zoomy = (y2 - y1) / ibuf->y;
1763
1764                         /* for some reason; zoomlevels down refuses to use GL_ALPHA_SCALE */
1765                         if (zoomx < 1.0f || zoomy < 1.0f) {
1766                                 float tzoom = min_ff(zoomx, zoomy);
1767                                 int mip = 0;
1768
1769                                 if ((ibuf->userflags & IB_MIPMAP_INVALID) != 0) {
1770                                         IMB_remakemipmap(ibuf, 0);
1771                                         ibuf->userflags &= ~IB_MIPMAP_INVALID;
1772                                 }
1773                                 else if (ibuf->mipmap[0] == NULL)
1774                                         IMB_makemipmap(ibuf, 0);
1775
1776                                 while (tzoom < 1.0f && mip < 8 && ibuf->mipmap[mip]) {
1777                                         tzoom *= 2.0f;
1778                                         zoomx *= 2.0f;
1779                                         zoomy *= 2.0f;
1780                                         mip++;
1781                                 }
1782                                 if (mip > 0)
1783                                         ibuf = ibuf->mipmap[mip - 1];
1784                         }
1785
1786                         if (v3d->zbuf) glDisable(GL_DEPTH_TEST);
1787                         glDepthMask(0);
1788
1789                         glEnable(GL_BLEND);
1790                         glBlendFunc(GL_SRC_ALPHA,  GL_ONE_MINUS_SRC_ALPHA);
1791
1792                         glMatrixMode(GL_PROJECTION);
1793                         glPushMatrix();
1794                         glMatrixMode(GL_MODELVIEW);
1795                         glPushMatrix();
1796                         ED_region_pixelspace(ar);
1797
1798                         glPixelZoom(zoomx, zoomy);
1799                         glColor4f(1.0f, 1.0f, 1.0f, 1.0f - bgpic->blend);
1800
1801                         /* could not use glaDrawPixelsAuto because it could fallback to
1802                          * glaDrawPixelsSafe in some cases, which will end up in misssing
1803                          * alpha transparency for the background image (sergey)
1804                          */
1805                         glaDrawPixelsTex(x1, y1, ibuf->x, ibuf->y, GL_RGBA, GL_UNSIGNED_BYTE, GL_LINEAR, ibuf->rect);
1806
1807                         glPixelZoom(1.0, 1.0);
1808                         glPixelTransferf(GL_ALPHA_SCALE, 1.0f);
1809
1810                         glMatrixMode(GL_PROJECTION);
1811                         glPopMatrix();
1812                         glMatrixMode(GL_MODELVIEW);
1813                         glPopMatrix();
1814
1815                         glDisable(GL_BLEND);
1816
1817                         glDepthMask(1);
1818                         if (v3d->zbuf) glEnable(GL_DEPTH_TEST);
1819
1820                         if (freeibuf)
1821                                 IMB_freeImBuf(freeibuf);
1822                         if (releaseibuf)
1823                                 BKE_image_release_ibuf(ima, releaseibuf, NULL);
1824                 }
1825         }
1826 }
1827
1828 static void view3d_draw_bgpic_test(Scene *scene, ARegion *ar, View3D *v3d,
1829                                    const bool do_foreground, const bool do_camera_frame)
1830 {
1831         RegionView3D *rv3d = ar->regiondata;
1832
1833         if ((v3d->flag & V3D_DISPBGPICS) == 0)
1834                 return;
1835
1836         /* disabled - mango request, since footage /w only render is quite useful
1837          * and this option is easy to disable all background images at once */
1838 #if 0
1839         if (v3d->flag2 & V3D_RENDER_OVERRIDE)
1840                 return;
1841 #endif
1842
1843         if ((rv3d->view == RV3D_VIEW_USER) || (rv3d->persp != RV3D_ORTHO)) {
1844                 if (rv3d->persp == RV3D_CAMOB) {
1845                         view3d_draw_bgpic(scene, ar, v3d, do_foreground, do_camera_frame);
1846                 }
1847         }
1848         else {
1849                 view3d_draw_bgpic(scene, ar, v3d, do_foreground, do_camera_frame);
1850         }
1851 }
1852
1853 /* ****************** View3d afterdraw *************** */
1854
1855 typedef struct View3DAfter {
1856         struct View3DAfter *next, *prev;
1857         struct Base *base;
1858         short dflag;
1859 } View3DAfter;
1860
1861 /* temp storage of Objects that need to be drawn as last */
1862 void ED_view3d_after_add(ListBase *lb, Base *base, const short dflag)
1863 {
1864         View3DAfter *v3da = MEM_callocN(sizeof(View3DAfter), "View 3d after");
1865         BLI_assert((base->flag & OB_FROMDUPLI) == 0);
1866         BLI_addtail(lb, v3da);
1867         v3da->base = base;
1868         v3da->dflag = dflag;
1869 }
1870
1871 /* disables write in zbuffer and draws it over */
1872 static void view3d_draw_transp(Scene *scene, ARegion *ar, View3D *v3d)
1873 {
1874         View3DAfter *v3da, *next;
1875         
1876         glDepthMask(0);
1877         v3d->transp = TRUE;
1878         
1879         for (v3da = v3d->afterdraw_transp.first; v3da; v3da = next) {
1880                 next = v3da->next;
1881                 draw_object(scene, ar, v3d, v3da->base, v3da->dflag);
1882                 BLI_remlink(&v3d->afterdraw_transp, v3da);
1883                 MEM_freeN(v3da);
1884         }
1885         v3d->transp = FALSE;
1886         
1887         glDepthMask(1);
1888         
1889 }
1890
1891 /* clears zbuffer and draws it over */
1892 static void view3d_draw_xray(Scene *scene, ARegion *ar, View3D *v3d, int clear)
1893 {
1894         View3DAfter *v3da, *next;
1895
1896         if (clear && v3d->zbuf)
1897                 glClear(GL_DEPTH_BUFFER_BIT);
1898
1899         v3d->xray = TRUE;
1900         for (v3da = v3d->afterdraw_xray.first; v3da; v3da = next) {
1901                 next = v3da->next;
1902                 draw_object(scene, ar, v3d, v3da->base, v3da->dflag);
1903                 BLI_remlink(&v3d->afterdraw_xray, v3da);
1904                 MEM_freeN(v3da);
1905         }
1906         v3d->xray = FALSE;
1907 }
1908
1909
1910 /* clears zbuffer and draws it over */
1911 static void view3d_draw_xraytransp(Scene *scene, ARegion *ar, View3D *v3d, int clear)
1912 {
1913         View3DAfter *v3da, *next;
1914
1915         if (clear && v3d->zbuf)
1916                 glClear(GL_DEPTH_BUFFER_BIT);
1917
1918         v3d->xray = TRUE;
1919         v3d->transp = TRUE;
1920         
1921         for (v3da = v3d->afterdraw_xraytransp.first; v3da; v3da = next) {
1922                 next = v3da->next;
1923                 draw_object(scene, ar, v3d, v3da->base, v3da->dflag);
1924                 BLI_remlink(&v3d->afterdraw_xraytransp, v3da);
1925                 MEM_freeN(v3da);
1926         }
1927
1928         v3d->transp = FALSE;
1929         v3d->xray = FALSE;
1930
1931 }
1932
1933 /* *********************** */
1934
1935 /*
1936  * In most cases call draw_dupli_objects,
1937  * draw_dupli_objects_color was added because when drawing set dupli's
1938  * we need to force the color
1939  */
1940
1941 #if 0
1942 int dupli_ob_sort(void *arg1, void *arg2)
1943 {
1944         void *p1 = ((DupliObject *)arg1)->ob;
1945         void *p2 = ((DupliObject *)arg2)->ob;
1946         int val = 0;
1947         if (p1 < p2) val = -1;
1948         else if (p1 > p2) val = 1;
1949         return val;
1950 }
1951 #endif
1952
1953
1954 static DupliObject *dupli_step(DupliObject *dob)
1955 {
1956         while (dob && dob->no_draw)
1957                 dob = dob->next;
1958         return dob;
1959 }
1960
1961 static void draw_dupli_objects_color(Scene *scene, ARegion *ar, View3D *v3d, Base *base, int color)
1962 {
1963         RegionView3D *rv3d = ar->regiondata;
1964         ListBase *lb;
1965         LodLevel *savedlod;
1966         float savedobmat[4][4];
1967         DupliObject *dob_prev = NULL, *dob, *dob_next = NULL;
1968         Base tbase = {NULL};
1969         BoundBox bb, *bb_tmp; /* use a copy because draw_object, calls clear_mesh_caches */
1970         GLuint displist = 0;
1971         short transflag, use_displist = -1;  /* -1 is initialize */
1972         char dt;
1973         short dtx;
1974         
1975         if (base->object->restrictflag & OB_RESTRICT_VIEW) return;
1976         
1977         tbase.flag = OB_FROMDUPLI | base->flag;
1978         lb = object_duplilist(G.main->eval_ctx, scene, base->object);
1979         // BLI_sortlist(lb, dupli_ob_sort); /* might be nice to have if we have a dupli list with mixed objects. */
1980
1981         dob = dupli_step(lb->first);
1982         if (dob) dob_next = dupli_step(dob->next);
1983
1984         for (; dob; dob_prev = dob, dob = dob_next, dob_next = dob_next ? dupli_step(dob_next->next) : NULL) {
1985                 tbase.object = dob->ob;
1986
1987                 /* Make sure lod is updated from dupli's position */
1988
1989                 copy_m4_m4(savedobmat, dob->ob->obmat);
1990                 copy_m4_m4(dob->ob->obmat, dob->mat);
1991                 savedlod = dob->ob->currentlod;
1992                 BKE_object_lod_update(dob->ob, rv3d->viewinv[3]);
1993                 
1994
1995                 /* extra service: draw the duplicator in drawtype of parent, minimum taken
1996                  * to allow e.g. boundbox box objects in groups for LOD */
1997                 dt = tbase.object->dt;
1998                 tbase.object->dt = MIN2(tbase.object->dt, base->object->dt);
1999
2000                 /* inherit draw extra, but not if a boundbox under the assumption that this
2001                  * is intended to speed up drawing, and drawing extra (especially wire) can
2002                  * slow it down too much */
2003                 dtx = tbase.object->dtx;
2004                 if (tbase.object->dt != OB_BOUNDBOX)
2005                         tbase.object->dtx = base->object->dtx;
2006
2007                 /* negative scale flag has to propagate */
2008                 transflag = tbase.object->transflag;
2009
2010                 if (is_negative_m4(dob->mat))
2011                         tbase.object->transflag |= OB_NEG_SCALE;
2012                 else
2013                         tbase.object->transflag &= ~OB_NEG_SCALE;
2014
2015                 UI_ThemeColorBlend(color, TH_BACK, 0.5);
2016
2017                 /* generate displist, test for new object */
2018                 if (dob_prev && dob_prev->ob != dob->ob) {
2019                         if (use_displist == true)
2020                                 glDeleteLists(displist, 1);
2021
2022                         use_displist = -1;
2023                 }
2024
2025                 /* generate displist */
2026                 if (use_displist == -1) {
2027
2028                         /* note, since this was added, its checked (dob->type == OB_DUPLIGROUP)
2029                          * however this is very slow, it was probably needed for the NLA
2030                          * offset feature (used in group-duplicate.blend but no longer works in 2.5)
2031                          * so for now it should be ok to - campbell */
2032
2033                         if ( /* if this is the last no need  to make a displist */
2034                             (dob_next == NULL || dob_next->ob != dob->ob) ||
2035                             /* lamp drawing messes with matrices, could be handled smarter... but this works */
2036                             (dob->ob->type == OB_LAMP) ||
2037                             (dob->type == OB_DUPLIGROUP && dob->animated) ||
2038                             !(bb_tmp = BKE_object_boundbox_get(dob->ob)) ||
2039                             draw_glsl_material(scene, dob->ob, v3d, dt) ||
2040                             check_object_draw_texture(scene, v3d, dt) ||
2041                             (base->object == OBACT && v3d->flag2 & V3D_SOLID_MATCAP))
2042                         {
2043                                 // printf("draw_dupli_objects_color: skipping displist for %s\n", dob->ob->id.name + 2);
2044                                 use_displist = false;
2045                         }
2046                         else {
2047                                 // printf("draw_dupli_objects_color: using displist for %s\n", dob->ob->id.name + 2);
2048                                 bb = *bb_tmp; /* must make a copy  */
2049
2050                                 /* disable boundbox check for list creation */
2051                                 BKE_object_boundbox_flag(dob->ob, BOUNDBOX_DISABLED, 1);
2052                                 /* need this for next part of code */
2053                                 unit_m4(dob->ob->obmat);    /* obmat gets restored */
2054
2055                                 displist = glGenLists(1);
2056                                 glNewList(displist, GL_COMPILE);
2057                                 draw_object(scene, ar, v3d, &tbase, DRAW_CONSTCOLOR);
2058                                 glEndList();
2059
2060                                 use_displist = true;
2061                                 BKE_object_boundbox_flag(dob->ob, BOUNDBOX_DISABLED, 0);
2062                         }
2063                 }
2064                 if (use_displist) {
2065                         glMultMatrixf(dob->mat);
2066                         if (ED_view3d_boundbox_clip(rv3d, dob->mat, &bb))
2067                                 glCallList(displist);
2068                         glLoadMatrixf(rv3d->viewmat);
2069                 }
2070                 else {
2071                         draw_object(scene, ar, v3d, &tbase, DRAW_CONSTCOLOR);
2072                 }
2073
2074                 tbase.object->dt = dt;
2075                 tbase.object->dtx = dtx;
2076                 tbase.object->transflag = transflag;
2077                 tbase.object->currentlod = savedlod;
2078                 copy_m4_m4(tbase.object->obmat, savedobmat);
2079         }
2080         
2081         /* Transp afterdraw disabled, afterdraw only stores base pointers, and duplis can be same obj */
2082         
2083         free_object_duplilist(lb);
2084         
2085         if (use_displist)
2086                 glDeleteLists(displist, 1);
2087 }
2088
2089 static void draw_dupli_objects(Scene *scene, ARegion *ar, View3D *v3d, Base *base)
2090 {
2091         /* define the color here so draw_dupli_objects_color can be called
2092          * from the set loop */
2093         
2094         int color = (base->flag & SELECT) ? TH_SELECT : TH_WIRE;
2095         /* debug */
2096         if (base->object->dup_group && base->object->dup_group->id.us < 1)
2097                 color = TH_REDALERT;
2098         
2099         draw_dupli_objects_color(scene, ar, v3d, base, color);
2100 }
2101
2102 /* XXX warning, not using gpu offscreen here */
2103 void view3d_update_depths_rect(ARegion *ar, ViewDepths *d, rcti *rect)
2104 {
2105         int x, y, w, h;
2106         rcti r;
2107         /* clamp rect by area */
2108
2109         r.xmin = 0;
2110         r.xmax = ar->winx - 1;
2111         r.ymin = 0;
2112         r.ymax = ar->winy - 1;
2113
2114         /* Constrain rect to depth bounds */
2115         BLI_rcti_isect(&r, rect, rect);
2116
2117         /* assign values to compare with the ViewDepths */
2118         x = rect->xmin;
2119         y = rect->ymin;
2120
2121         w = BLI_rcti_size_x(rect);
2122         h = BLI_rcti_size_y(rect);
2123
2124         if (w <= 0 || h <= 0) {
2125                 if (d->depths)
2126                         MEM_freeN(d->depths);
2127                 d->depths = NULL;
2128
2129                 d->damaged = false;
2130         }
2131         else if (d->w != w ||
2132                  d->h != h ||
2133                  d->x != x ||
2134                  d->y != y ||
2135                  d->depths == NULL
2136                  )
2137         {
2138                 d->x = x;
2139                 d->y = y;
2140                 d->w = w;
2141                 d->h = h;
2142
2143                 if (d->depths)
2144                         MEM_freeN(d->depths);
2145
2146                 d->depths = MEM_mallocN(sizeof(float) * d->w * d->h, "View depths Subset");
2147                 
2148                 d->damaged = true;
2149         }
2150
2151         if (d->damaged) {
2152                 /* XXX using special function here, it doesn't use the gpu offscreen system */
2153                 view3d_opengl_read_Z_pixels(ar, d->x, d->y, d->w, d->h, GL_DEPTH_COMPONENT, GL_FLOAT, d->depths);
2154                 glGetDoublev(GL_DEPTH_RANGE, d->depth_range);
2155                 d->damaged = false;
2156         }
2157 }
2158
2159 /* note, with nouveau drivers the glReadPixels() is very slow. [#24339] */
2160 void ED_view3d_depth_update(ARegion *ar)
2161 {
2162         RegionView3D *rv3d = ar->regiondata;
2163         
2164         /* Create storage for, and, if necessary, copy depth buffer */
2165         if (!rv3d->depths) rv3d->depths = MEM_callocN(sizeof(ViewDepths), "ViewDepths");
2166         if (rv3d->depths) {
2167                 ViewDepths *d = rv3d->depths;
2168                 if (d->w != ar->winx ||
2169                     d->h != ar->winy ||
2170                     !d->depths)
2171                 {
2172                         d->w = ar->winx;
2173                         d->h = ar->winy;
2174                         if (d->depths)
2175                                 MEM_freeN(d->depths);
2176                         d->depths = MEM_mallocN(sizeof(float) * d->w * d->h, "View depths");
2177                         d->damaged = true;
2178                 }
2179                 
2180                 if (d->damaged) {
2181                         view3d_opengl_read_pixels(ar, 0, 0, d->w, d->h, GL_DEPTH_COMPONENT, GL_FLOAT, d->depths);
2182                         glGetDoublev(GL_DEPTH_RANGE, d->depth_range);
2183                         
2184                         d->damaged = false;
2185                 }
2186         }
2187 }
2188
2189 /* utility function to find the closest Z value, use for autodepth */
2190 float view3d_depth_near(ViewDepths *d)
2191 {
2192         /* convert to float for comparisons */
2193         const float near = (float)d->depth_range[0];
2194         const float far_real = (float)d->depth_range[1];
2195         float far = far_real;
2196
2197         const float *depths = d->depths;
2198         float depth = FLT_MAX;
2199         int i = (int)d->w * (int)d->h; /* cast to avoid short overflow */
2200
2201         /* far is both the starting 'far' value
2202          * and the closest value found. */
2203         while (i--) {
2204                 depth = *depths++;
2205                 if ((depth < far) && (depth > near)) {
2206                         far = depth;
2207                 }
2208         }
2209
2210         return far == far_real ? FLT_MAX : far;
2211 }
2212
2213 void draw_depth_gpencil(Scene *scene, ARegion *ar, View3D *v3d)
2214 {
2215         short zbuf = v3d->zbuf;
2216         RegionView3D *rv3d = ar->regiondata;
2217
2218         setwinmatrixview3d(ar, v3d, NULL);
2219         setviewmatrixview3d(scene, v3d, rv3d);  /* note: calls BKE_object_where_is_calc for camera... */
2220
2221         mul_m4_m4m4(rv3d->persmat, rv3d->winmat, rv3d->viewmat);
2222         invert_m4_m4(rv3d->persinv, rv3d->persmat);
2223         invert_m4_m4(rv3d->viewinv, rv3d->viewmat);
2224
2225         glClear(GL_DEPTH_BUFFER_BIT);
2226
2227         glLoadMatrixf(rv3d->viewmat);
2228
2229         v3d->zbuf = TRUE;
2230         glEnable(GL_DEPTH_TEST);
2231
2232         if (v3d->flag2 & V3D_SHOW_GPENCIL) {
2233                 draw_gpencil_view3d(scene, v3d, ar, true);
2234         }
2235         
2236         v3d->zbuf = zbuf;
2237
2238 }
2239
2240 void draw_depth(Scene *scene, ARegion *ar, View3D *v3d, int (*func)(void *), bool alphaoverride)
2241 {
2242         RegionView3D *rv3d = ar->regiondata;
2243         Base *base;
2244         short zbuf = v3d->zbuf;
2245         short flag = v3d->flag;
2246         float glalphaclip = U.glalphaclip;
2247         int obcenter_dia = U.obcenter_dia;
2248         /* temp set drawtype to solid */
2249         
2250         /* Setting these temporarily is not nice */
2251         v3d->flag &= ~V3D_SELECT_OUTLINE;
2252         U.glalphaclip = alphaoverride ? 0.5f : glalphaclip; /* not that nice but means we wont zoom into billboards */
2253         U.obcenter_dia = 0;
2254         
2255         setwinmatrixview3d(ar, v3d, NULL);
2256         setviewmatrixview3d(scene, v3d, rv3d);  /* note: calls BKE_object_where_is_calc for camera... */
2257         
2258         mul_m4_m4m4(rv3d->persmat, rv3d->winmat, rv3d->viewmat);
2259         invert_m4_m4(rv3d->persinv, rv3d->persmat);
2260         invert_m4_m4(rv3d->viewinv, rv3d->viewmat);
2261         
2262         glClear(GL_DEPTH_BUFFER_BIT);
2263         
2264         glLoadMatrixf(rv3d->viewmat);
2265 //      persp(PERSP_STORE);  /* store correct view for persp(PERSP_VIEW) calls */
2266         
2267         if (rv3d->rflag & RV3D_CLIPPING) {
2268                 ED_view3d_clipping_set(rv3d);
2269         }
2270         
2271         v3d->zbuf = TRUE;
2272         glEnable(GL_DEPTH_TEST);
2273         
2274         /* draw set first */
2275         if (scene->set) {
2276                 Scene *sce_iter;
2277                 for (SETLOOPER(scene->set, sce_iter, base)) {
2278                         if (v3d->lay & base->lay) {
2279                                 if (func == NULL || func(base)) {
2280                                         draw_object(scene, ar, v3d, base, 0);
2281                                         if (base->object->transflag & OB_DUPLI) {
2282                                                 draw_dupli_objects_color(scene, ar, v3d, base, TH_WIRE);
2283                                         }
2284                                 }
2285                         }
2286                 }
2287         }
2288         
2289         for (base = scene->base.first; base; base = base->next) {
2290                 if (v3d->lay & base->lay) {
2291                         if (func == NULL || func(base)) {
2292                                 /* dupli drawing */
2293                                 if (base->object->transflag & OB_DUPLI) {
2294                                         draw_dupli_objects(scene, ar, v3d, base);
2295                                 }
2296                                 draw_object(scene, ar, v3d, base, 0);
2297                         }
2298                 }
2299         }
2300         
2301         /* this isn't that nice, draw xray objects as if they are normal */
2302         if (v3d->afterdraw_transp.first ||
2303             v3d->afterdraw_xray.first ||
2304             v3d->afterdraw_xraytransp.first)
2305         {
2306                 View3DAfter *v3da, *next;
2307                 int mask_orig;
2308
2309                 v3d->xray = TRUE;
2310                 
2311                 /* transp materials can change the depth mask, see #21388 */
2312                 glGetIntegerv(GL_DEPTH_WRITEMASK, &mask_orig);
2313
2314
2315                 if (v3d->afterdraw_xray.first || v3d->afterdraw_xraytransp.first) {
2316                         glDepthFunc(GL_ALWAYS); /* always write into the depth bufer, overwriting front z values */
2317                         for (v3da = v3d->afterdraw_xray.first; v3da; v3da = next) {
2318                                 next = v3da->next;
2319                                 draw_object(scene, ar, v3d, v3da->base, 0);
2320                         }
2321                         glDepthFunc(GL_LEQUAL); /* Now write the depth buffer normally */
2322                 }
2323
2324                 /* draw 3 passes, transp/xray/xraytransp */
2325                 v3d->xray = FALSE;
2326                 v3d->transp = TRUE;
2327                 for (v3da = v3d->afterdraw_transp.first; v3da; v3da = next) {
2328                         next = v3da->next;
2329                         draw_object(scene, ar, v3d, v3da->base, 0);
2330                         BLI_remlink(&v3d->afterdraw_transp, v3da);
2331                         MEM_freeN(v3da);
2332                 }
2333
2334                 v3d->xray = TRUE;
2335                 v3d->transp = FALSE;
2336                 for (v3da = v3d->afterdraw_xray.first; v3da; v3da = next) {
2337                         next = v3da->next;
2338                         draw_object(scene, ar, v3d, v3da->base, 0);
2339                         BLI_remlink(&v3d->afterdraw_xray, v3da);
2340                         MEM_freeN(v3da);
2341                 }
2342
2343                 v3d->xray = TRUE;
2344                 v3d->transp = TRUE;
2345                 for (v3da = v3d->afterdraw_xraytransp.first; v3da; v3da = next) {
2346                         next = v3da->next;
2347                         draw_object(scene, ar, v3d, v3da->base, 0);
2348                         BLI_remlink(&v3d->afterdraw_xraytransp, v3da);
2349                         MEM_freeN(v3da);
2350                 }
2351
2352                 
2353                 v3d->xray = FALSE;
2354                 v3d->transp = FALSE;
2355
2356                 glDepthMask(mask_orig);
2357         }
2358         
2359         if (rv3d->rflag & RV3D_CLIPPING)
2360                 ED_view3d_clipping_disable();
2361         
2362         v3d->zbuf = zbuf;
2363         if (!v3d->zbuf) glDisable(GL_DEPTH_TEST);
2364
2365         U.glalphaclip = glalphaclip;
2366         v3d->flag = flag;
2367         U.obcenter_dia = obcenter_dia;
2368 }
2369
2370 typedef struct View3DShadow {
2371         struct View3DShadow *next, *prev;
2372         GPULamp *lamp;
2373 } View3DShadow;
2374
2375 static void gpu_render_lamp_update(Scene *scene, View3D *v3d, Object *ob, Object *par,
2376                                    float obmat[4][4], ListBase *shadows)
2377 {
2378         GPULamp *lamp;
2379         Lamp *la = (Lamp *)ob->data;
2380         View3DShadow *shadow;
2381         
2382         lamp = GPU_lamp_from_blender(scene, ob, par);
2383         
2384         if (lamp) {
2385                 GPU_lamp_update(lamp, ob->lay, (ob->restrictflag & OB_RESTRICT_RENDER), obmat);
2386                 GPU_lamp_update_colors(lamp, la->r, la->g, la->b, la->energy);
2387                 
2388                 if ((ob->lay & v3d->lay) && GPU_lamp_has_shadow_buffer(lamp)) {
2389                         shadow = MEM_callocN(sizeof(View3DShadow), "View3DShadow");
2390                         shadow->lamp = lamp;
2391                         BLI_addtail(shadows, shadow);
2392                 }
2393         }
2394 }
2395
2396 static void gpu_update_lamps_shadows(Scene *scene, View3D *v3d)
2397 {
2398         ListBase shadows;
2399         View3DShadow *shadow;
2400         Scene *sce_iter;
2401         Base *base;
2402         Object *ob;
2403         
2404         BLI_listbase_clear(&shadows);
2405         
2406         /* update lamp transform and gather shadow lamps */
2407         for (SETLOOPER(scene, sce_iter, base)) {
2408                 ob = base->object;
2409                 
2410                 if (ob->type == OB_LAMP)
2411                         gpu_render_lamp_update(scene, v3d, ob, NULL, ob->obmat, &shadows);
2412                 
2413                 if (ob->transflag & OB_DUPLI) {
2414                         DupliObject *dob;
2415                         ListBase *lb = object_duplilist(G.main->eval_ctx, scene, ob);
2416                         
2417                         for (dob = lb->first; dob; dob = dob->next)
2418                                 if (dob->ob->type == OB_LAMP)
2419                                         gpu_render_lamp_update(scene, v3d, dob->ob, ob, dob->mat, &shadows);
2420                         
2421                         free_object_duplilist(lb);
2422                 }
2423         }
2424         
2425         /* render shadows after updating all lamps, nested object_duplilist
2426          * don't work correct since it's replacing object matrices */
2427         for (shadow = shadows.first; shadow; shadow = shadow->next) {
2428                 /* this needs to be done better .. */
2429                 float viewmat[4][4], winmat[4][4];
2430                 int drawtype, lay, winsize, flag2 = v3d->flag2;
2431                 ARegion ar = {NULL};
2432                 RegionView3D rv3d = {{{0}}};
2433                 
2434                 drawtype = v3d->drawtype;
2435                 lay = v3d->lay;
2436                 
2437                 v3d->drawtype = OB_SOLID;
2438                 v3d->lay &= GPU_lamp_shadow_layer(shadow->lamp);
2439                 v3d->flag2 &= ~V3D_SOLID_TEX;
2440                 v3d->flag2 |= V3D_RENDER_OVERRIDE | V3D_RENDER_SHADOW;
2441                 
2442                 GPU_lamp_shadow_buffer_bind(shadow->lamp, viewmat, &winsize, winmat);
2443
2444                 ar.regiondata = &rv3d;
2445                 ar.regiontype = RGN_TYPE_WINDOW;
2446                 rv3d.persp = RV3D_CAMOB;
2447                 copy_m4_m4(rv3d.winmat, winmat);
2448                 copy_m4_m4(rv3d.viewmat, viewmat);
2449                 invert_m4_m4(rv3d.viewinv, rv3d.viewmat);
2450                 mul_m4_m4m4(rv3d.persmat, rv3d.winmat, rv3d.viewmat);
2451                 invert_m4_m4(rv3d.persinv, rv3d.viewinv);
2452
2453                 /* no need to call ED_view3d_draw_offscreen_init since shadow buffers were already updated */
2454                 ED_view3d_draw_offscreen(scene, v3d, &ar, winsize, winsize, viewmat, winmat, false, false);
2455                 GPU_lamp_shadow_buffer_unbind(shadow->lamp);
2456                 
2457                 v3d->drawtype = drawtype;
2458                 v3d->lay = lay;
2459                 v3d->flag2 = flag2;
2460         }
2461         
2462         BLI_freelistN(&shadows);
2463 }
2464
2465 /* *********************** customdata **************** */
2466
2467 CustomDataMask ED_view3d_datamask(Scene *scene, View3D *v3d)
2468 {
2469         CustomDataMask mask = 0;
2470
2471         if (ELEM(v3d->drawtype, OB_TEXTURE, OB_MATERIAL) ||
2472             ((v3d->drawtype == OB_SOLID) && (v3d->flag2 & V3D_SOLID_TEX)))
2473         {
2474                 mask |= CD_MASK_MTFACE | CD_MASK_MCOL;
2475
2476                 if (BKE_scene_use_new_shading_nodes(scene)) {
2477                         if (v3d->drawtype == OB_MATERIAL)
2478                                 mask |= CD_MASK_ORCO;
2479                 }
2480                 else {
2481                         if (scene->gm.matmode == GAME_MAT_GLSL)
2482                                 mask |= CD_MASK_ORCO;
2483                 }
2484         }
2485
2486         return mask;
2487 }
2488
2489 /* goes over all modes and view3d settings */
2490 CustomDataMask ED_view3d_screen_datamask(bScreen *screen)
2491 {
2492         Scene *scene = screen->scene;
2493         CustomDataMask mask = CD_MASK_BAREMESH;
2494         ScrArea *sa;
2495         
2496         /* check if we need tfaces & mcols due to view mode */
2497         for (sa = screen->areabase.first; sa; sa = sa->next) {
2498                 if (sa->spacetype == SPACE_VIEW3D) {
2499                         mask |= ED_view3d_datamask(scene, (View3D *)sa->spacedata.first);
2500                 }
2501         }
2502
2503         return mask;
2504 }
2505
2506 void ED_view3d_update_viewmat(Scene *scene, View3D *v3d, ARegion *ar, float viewmat[4][4], float winmat[4][4])
2507 {
2508         RegionView3D *rv3d = ar->regiondata;
2509
2510         /* setup window matrices */
2511         if (winmat)
2512                 copy_m4_m4(rv3d->winmat, winmat);
2513         else
2514                 setwinmatrixview3d(ar, v3d, NULL);
2515
2516         /* setup view matrix */
2517         if (viewmat)
2518                 copy_m4_m4(rv3d->viewmat, viewmat);
2519         else
2520                 setviewmatrixview3d(scene, v3d, rv3d);  /* note: calls BKE_object_where_is_calc for camera... */
2521
2522         /* update utilitity matrices */
2523         mul_m4_m4m4(rv3d->persmat, rv3d->winmat, rv3d->viewmat);
2524         invert_m4_m4(rv3d->persinv, rv3d->persmat);
2525         invert_m4_m4(rv3d->viewinv, rv3d->viewmat);
2526
2527         /* calculate pixelsize factor once, is used for lamps and obcenters */
2528         {
2529                 /* note:  '1.0f / len_v3(v1)'  replaced  'len_v3(rv3d->viewmat[0])'
2530                  * because of float point precision problems at large values [#23908] */
2531                 float v1[3], v2[3];
2532                 float len_px, len_sc;
2533
2534                 v1[0] = rv3d->persmat[0][0];
2535                 v1[1] = rv3d->persmat[1][0];
2536                 v1[2] = rv3d->persmat[2][0];
2537
2538                 v2[0] = rv3d->persmat[0][1];
2539                 v2[1] = rv3d->persmat[1][1];
2540                 v2[2] = rv3d->persmat[2][1];
2541
2542                 len_px = 2.0f / sqrtf(min_ff(len_squared_v3(v1), len_squared_v3(v2)));
2543                 len_sc = (float)MAX2(ar->winx, ar->winy);
2544
2545                 rv3d->pixsize = len_px / len_sc;
2546         }
2547 }
2548
2549 static void view3d_main_area_setup_view(Scene *scene, View3D *v3d, ARegion *ar, float viewmat[4][4], float winmat[4][4])
2550 {
2551         RegionView3D *rv3d = ar->regiondata;
2552
2553         ED_view3d_update_viewmat(scene, v3d, ar, viewmat, winmat);
2554
2555         /* set for opengl */
2556         glMatrixMode(GL_PROJECTION);
2557         glLoadMatrixf(rv3d->winmat);
2558         glMatrixMode(GL_MODELVIEW);
2559         glLoadMatrixf(rv3d->viewmat);
2560 }
2561
2562 void ED_view3d_draw_offscreen_init(Scene *scene, View3D *v3d)
2563 {
2564         /* shadow buffers, before we setup matrices */
2565         if (draw_glsl_material(scene, NULL, v3d, v3d->drawtype))
2566                 gpu_update_lamps_shadows(scene, v3d);
2567 }
2568
2569 /* ED_view3d_draw_offscreen_init should be called before this to initialize
2570  * stuff like shadow buffers
2571  */
2572 void ED_view3d_draw_offscreen(Scene *scene, View3D *v3d, ARegion *ar, int winx, int winy,
2573                               float viewmat[4][4], float winmat[4][4], bool do_bgpic, bool do_sky)
2574 {
2575         RegionView3D *rv3d = ar->regiondata;
2576         Base *base;
2577         int bwinx, bwiny;
2578         rcti brect;
2579
2580         glPushMatrix();
2581
2582         /* set temporary new size */
2583         bwinx = ar->winx;
2584         bwiny = ar->winy;
2585         brect = ar->winrct;
2586         
2587         ar->winx = winx;
2588         ar->winy = winy;
2589         ar->winrct.xmin = 0;
2590         ar->winrct.ymin = 0;
2591         ar->winrct.xmax = winx;
2592         ar->winrct.ymax = winy;
2593
2594         /* set theme */
2595         UI_SetTheme(SPACE_VIEW3D, RGN_TYPE_WINDOW);
2596         
2597         /* set flags */
2598         G.f |= G_RENDER_OGL;
2599
2600         /* free images which can have changed on frame-change
2601          * warning! can be slow so only free animated images - campbell */
2602         GPU_free_images_anim();
2603
2604         /* clear opengl buffers */
2605         if (do_sky) {
2606                 float sky_color[3];
2607
2608                 ED_view3d_offscreen_sky_color_get(scene, sky_color);
2609                 glClearColor(sky_color[0], sky_color[1], sky_color[2], 1.0f);
2610         }
2611         else {
2612                 glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
2613         }
2614
2615         glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
2616
2617         /* setup view matrices */
2618         view3d_main_area_setup_view(scene, v3d, ar, viewmat, winmat);
2619
2620         if (rv3d->rflag & RV3D_CLIPPING)
2621                 view3d_draw_clipping(rv3d);
2622
2623         /* set zbuffer */
2624         if (v3d->drawtype > OB_WIRE) {
2625                 v3d->zbuf = TRUE;
2626                 glEnable(GL_DEPTH_TEST);
2627         }
2628         else
2629                 v3d->zbuf = FALSE;
2630
2631         /* important to do before clipping */
2632         if (do_bgpic) {
2633                 view3d_draw_bgpic_test(scene, ar, v3d, false, false);
2634         }
2635
2636         if (rv3d->rflag & RV3D_CLIPPING)
2637                 ED_view3d_clipping_set(rv3d);
2638
2639         /* draw set first */
2640         if (scene->set) {
2641                 Scene *sce_iter;
2642                 for (SETLOOPER(scene->set, sce_iter, base)) {
2643                         if (v3d->lay & base->lay) {
2644                                 UI_ThemeColorBlend(TH_WIRE, TH_BACK, 0.6f);
2645                                 draw_object(scene, ar, v3d, base, DRAW_CONSTCOLOR | DRAW_SCENESET);
2646                                 
2647                                 if (base->object->transflag & OB_DUPLI)
2648                                         draw_dupli_objects_color(scene, ar, v3d, base, TH_WIRE);
2649                         }
2650                 }
2651         }
2652         
2653         /* then draw not selected and the duplis, but skip editmode object */
2654         for (base = scene->base.first; base; base = base->next) {
2655                 if (v3d->lay & base->lay) {
2656                         /* dupli drawing */
2657                         if (base->object->transflag & OB_DUPLI)
2658                                 draw_dupli_objects(scene, ar, v3d, base);
2659
2660                         draw_object(scene, ar, v3d, base, 0);
2661                 }
2662         }
2663
2664         /* must be before xray draw which clears the depth buffer */
2665         if (v3d->flag2 & V3D_SHOW_GPENCIL) {
2666                 if (v3d->zbuf) glDisable(GL_DEPTH_TEST);
2667                 draw_gpencil_view3d(scene, v3d, ar, true);
2668                 if (v3d->zbuf) glEnable(GL_DEPTH_TEST);
2669         }
2670
2671         /* transp and X-ray afterdraw stuff */
2672         if (v3d->afterdraw_transp.first)     view3d_draw_transp(scene, ar, v3d);
2673         if (v3d->afterdraw_xray.first)       view3d_draw_xray(scene, ar, v3d, 1);       /* clears zbuffer if it is used! */
2674         if (v3d->afterdraw_xraytransp.first) view3d_draw_xraytransp(scene, ar, v3d, 1);
2675
2676         if (rv3d->rflag & RV3D_CLIPPING)
2677                 ED_view3d_clipping_disable();
2678
2679         /* important to do after clipping */
2680         if (do_bgpic) {
2681                 view3d_draw_bgpic_test(scene, ar, v3d, true, false);
2682         }
2683
2684         /* cleanup */
2685         if (v3d->zbuf) {
2686                 v3d->zbuf = FALSE;
2687                 glDisable(GL_DEPTH_TEST);
2688         }
2689
2690         /* draw grease-pencil stuff */
2691         ED_region_pixelspace(ar);
2692
2693
2694         if (v3d->flag2 & V3D_SHOW_GPENCIL) {
2695                 /* draw grease-pencil stuff - needed to get paint-buffer shown too (since it's 2D) */
2696                 draw_gpencil_view3d(scene, v3d, ar, false);
2697         }
2698
2699         /* freeing the images again here could be done after the operator runs, leaving for now */
2700         GPU_free_images_anim();
2701
2702         /* restore size */
2703         ar->winx = bwinx;
2704         ar->winy = bwiny;
2705         ar->winrct = brect;
2706
2707         glPopMatrix();
2708
2709         /* XXX, without this the sequencer flickers with opengl draw enabled, need to find out why - campbell */
2710         glColor4ub(255, 255, 255, 255);
2711
2712         G.f &= ~G_RENDER_OGL;
2713 }
2714
2715 /* get a color used for offscreen sky, returns color in sRGB space */
2716 void ED_view3d_offscreen_sky_color_get(Scene *scene, float sky_color[3])
2717 {
2718         if (scene->world)
2719                 linearrgb_to_srgb_v3_v3(sky_color, &scene->world->horr);
2720         else
2721                 UI_GetThemeColor3fv(TH_BACK, sky_color);
2722 }
2723
2724 /* utility func for ED_view3d_draw_offscreen */
2725 ImBuf *ED_view3d_draw_offscreen_imbuf(Scene *scene, View3D *v3d, ARegion *ar, int sizex, int sizey, unsigned int flag,
2726                                       bool draw_background, int alpha_mode, char err_out[256])
2727 {
2728         RegionView3D *rv3d = ar->regiondata;
2729         ImBuf *ibuf;
2730         GPUOffScreen *ofs;
2731         bool draw_sky = (alpha_mode == R_ADDSKY);
2732         
2733         /* state changes make normal drawing go weird otherwise */
2734         glPushAttrib(GL_LIGHTING_BIT);
2735
2736         /* bind */
2737         ofs = GPU_offscreen_create(sizex, sizey, err_out);
2738         if (ofs == NULL) {
2739                 glPopAttrib();
2740                 return NULL;
2741         }
2742
2743         ED_view3d_draw_offscreen_init(scene, v3d);
2744
2745         GPU_offscreen_bind(ofs);
2746
2747         /* render 3d view */
2748         if (rv3d->persp == RV3D_CAMOB && v3d->camera) {
2749                 CameraParams params;
2750
2751                 BKE_camera_params_init(&params);
2752                 /* fallback for non camera objects */
2753                 params.clipsta = v3d->near;
2754                 params.clipend = v3d->far;
2755                 BKE_camera_params_from_object(&params, v3d->camera);
2756                 BKE_camera_params_compute_viewplane(&params, sizex, sizey, scene->r.xasp, scene->r.yasp);
2757                 BKE_camera_params_compute_matrix(&params);
2758
2759                 ED_view3d_draw_offscreen(scene, v3d, ar, sizex, sizey, NULL, params.winmat, draw_background, draw_sky);
2760         }
2761         else {
2762                 ED_view3d_draw_offscreen(scene, v3d, ar, sizex, sizey, NULL, NULL, draw_background, draw_sky);
2763         }
2764
2765         /* read in pixels & stamp */
2766         ibuf = IMB_allocImBuf(sizex, sizey, 32, flag);
2767
2768         if (ibuf->rect_float)
2769                 GPU_offscreen_read_pixels(ofs, GL_FLOAT, ibuf->rect_float);
2770         else if (ibuf->rect)
2771                 GPU_offscreen_read_pixels(ofs, GL_UNSIGNED_BYTE, ibuf->rect);
2772
2773         /* unbind */
2774         GPU_offscreen_unbind(ofs);
2775         GPU_offscreen_free(ofs);
2776
2777         glPopAttrib();
2778         
2779         if (ibuf->rect_float && ibuf->rect)
2780                 IMB_rect_from_float(ibuf);
2781         
2782         return ibuf;
2783 }
2784
2785 /* creates own 3d views, used by the sequencer */
2786 ImBuf *ED_view3d_draw_offscreen_imbuf_simple(Scene *scene, Object *camera, int width, int height, unsigned int flag, int drawtype,
2787                                              bool use_solid_tex, bool draw_background, int alpha_mode, char err_out[256])
2788 {
2789         View3D v3d = {NULL};
2790         ARegion ar = {NULL};
2791         RegionView3D rv3d = {{{0}}};
2792
2793         /* connect data */
2794         v3d.regionbase.first = v3d.regionbase.last = &ar;
2795         ar.regiondata = &rv3d;
2796         ar.regiontype = RGN_TYPE_WINDOW;
2797
2798         v3d.camera = camera;
2799         v3d.lay = scene->lay;
2800         v3d.drawtype = drawtype;
2801         v3d.flag2 = V3D_RENDER_OVERRIDE;
2802
2803         if (use_solid_tex)
2804                 v3d.flag2 |= V3D_SOLID_TEX;
2805
2806         rv3d.persp = RV3D_CAMOB;
2807
2808         copy_m4_m4(rv3d.viewinv, v3d.camera->obmat);
2809         normalize_m4(rv3d.viewinv);
2810         invert_m4_m4(rv3d.viewmat, rv3d.viewinv);
2811
2812         {
2813                 CameraParams params;
2814
2815                 BKE_camera_params_init(&params);
2816                 BKE_camera_params_from_object(&params, v3d.camera);
2817                 BKE_camera_params_compute_viewplane(&params, width, height, scene->r.xasp, scene->r.yasp);
2818                 BKE_camera_params_compute_matrix(&params);
2819
2820                 copy_m4_m4(rv3d.winmat, params.winmat);
2821                 v3d.near = params.clipsta;
2822                 v3d.far = params.clipend;
2823                 v3d.lens = params.lens;
2824         }
2825
2826         mul_m4_m4m4(rv3d.persmat, rv3d.winmat, rv3d.viewmat);
2827         invert_m4_m4(rv3d.persinv, rv3d.viewinv);
2828
2829         return ED_view3d_draw_offscreen_imbuf(scene, &v3d, &ar, width, height, flag,
2830                                               draw_background, alpha_mode, err_out);
2831
2832         // seq_view3d_cb(scene, cfra, render_size, seqrectx, seqrecty);
2833 }
2834
2835
2836 /* NOTE: the info that this uses is updated in ED_refresh_viewport_fps(), 
2837  * which currently gets called during SCREEN_OT_animation_step.
2838  */
2839 void ED_scene_draw_fps(Scene *scene, rcti *rect)
2840 {
2841         ScreenFrameRateInfo *fpsi = scene->fps_info;
2842         float fps;
2843         char printable[16];
2844         int i, tot;
2845         
2846         if (!fpsi || !fpsi->lredrawtime || !fpsi->redrawtime)
2847                 return;
2848         
2849         printable[0] = '\0';
2850         
2851 #if 0
2852         /* this is too simple, better do an average */
2853         fps = (float)(1.0 / (fpsi->lredrawtime - fpsi->redrawtime))
2854 #else
2855         fpsi->redrawtimes_fps[fpsi->redrawtime_index] = (float)(1.0 / (fpsi->lredrawtime - fpsi->redrawtime));
2856         
2857         for (i = 0, tot = 0, fps = 0.0f; i < REDRAW_FRAME_AVERAGE; i++) {
2858                 if (fpsi->redrawtimes_fps[i]) {
2859                         fps += fpsi->redrawtimes_fps[i];
2860                         tot++;
2861                 }
2862         }
2863         if (tot) {
2864                 fpsi->redrawtime_index = (fpsi->redrawtime_index + 1) % REDRAW_FRAME_AVERAGE;
2865                 
2866                 //fpsi->redrawtime_index++;
2867                 //if (fpsi->redrawtime >= REDRAW_FRAME_AVERAGE)
2868                 //      fpsi->redrawtime = 0;
2869                 
2870                 fps = fps / tot;
2871         }
2872 #endif
2873
2874         /* is this more than half a frame behind? */
2875         if (fps + 0.5f < (float)(FPS)) {
2876                 UI_ThemeColor(TH_REDALERT);
2877                 BLI_snprintf(printable, sizeof(printable), IFACE_("fps: %.2f"), fps);
2878         }
2879         else {
2880                 UI_ThemeColor(TH_TEXT_HI);
2881                 BLI_snprintf(printable, sizeof(printable), IFACE_("fps: %i"), (int)(fps + 0.5f));
2882         }
2883
2884 #ifdef WITH_INTERNATIONAL
2885         BLF_draw_default(rect->xmin + U.widget_unit,  rect->ymax - U.widget_unit, 0.0f, printable, sizeof(printable));
2886 #else
2887         BLF_draw_default_ascii(rect->xmin + U.widget_unit,  rect->ymax - U.widget_unit, 0.0f, printable, sizeof(printable));
2888 #endif
2889 }
2890
2891 static void view3d_main_area_draw_objects(const bContext *C, ARegion *ar, const char **grid_unit);
2892
2893 static bool view3d_main_area_do_render_draw(Scene *scene)
2894 {
2895         RenderEngineType *type = RE_engines_find(scene->r.engine);
2896
2897         return (type && type->view_update && type->view_draw);
2898 }
2899
2900 bool ED_view3d_calc_render_border(Scene *scene, View3D *v3d, ARegion *ar, rcti *rect)
2901 {
2902         RegionView3D *rv3d = ar->regiondata;
2903         rctf viewborder;
2904         bool use_border;
2905
2906         /* test if there is a 3d view rendering */
2907         if (v3d->drawtype != OB_RENDER || !view3d_main_area_do_render_draw(scene))
2908                 return false;
2909
2910         /* test if there is a border render */
2911         if (rv3d->persp == RV3D_CAMOB)
2912                 use_border = (scene->r.mode & R_BORDER) != 0;
2913         else
2914                 use_border = (v3d->flag2 & V3D_RENDER_BORDER) != 0;
2915         
2916         if (!use_border)
2917                 return false;
2918
2919         /* compute border */
2920         if (rv3d->persp == RV3D_CAMOB) {
2921                 ED_view3d_calc_camera_border(scene, ar, v3d, rv3d, &viewborder, false);
2922
2923                 rect->xmin = viewborder.xmin + scene->r.border.xmin * BLI_rctf_size_x(&viewborder);
2924                 rect->ymin = viewborder.ymin + scene->r.border.ymin * BLI_rctf_size_y(&viewborder);
2925                 rect->xmax = viewborder.xmin + scene->r.border.xmax * BLI_rctf_size_x(&viewborder);
2926                 rect->ymax = viewborder.ymin + scene->r.border.ymax * BLI_rctf_size_y(&viewborder);
2927         }
2928         else {
2929                 rect->xmin = v3d->render_border.xmin * ar->winx;
2930                 rect->xmax = v3d->render_border.xmax * ar->winx;
2931                 rect->ymin = v3d->render_border.ymin * ar->winy;
2932                 rect->ymax = v3d->render_border.ymax * ar->winy;
2933         }
2934
2935         BLI_rcti_translate(rect, ar->winrct.xmin, ar->winrct.ymin);
2936         BLI_rcti_isect(&ar->winrct, rect, rect);
2937
2938         return true;
2939 }
2940
2941 static bool view3d_main_area_draw_engine(const bContext *C, ARegion *ar, bool clip_border, rcti *border_rect)
2942 {
2943         Scene *scene = CTX_data_scene(C);
2944         View3D *v3d = CTX_wm_view3d(C);
2945         RegionView3D *rv3d = CTX_wm_region_view3d(C);
2946         RenderEngineType *type;
2947         GLint scissor[4];
2948
2949         /* create render engine */
2950         if (!rv3d->render_engine) {
2951                 RenderEngine *engine;
2952
2953                 type = RE_engines_find(scene->r.engine);
2954
2955                 if (!(type->view_update && type->view_draw))
2956                         return false;
2957
2958                 engine = RE_engine_create_ex(type, true);
2959
2960                 engine->tile_x = scene->r.tilex;
2961                 engine->tile_y = scene->r.tiley;
2962
2963                 type->view_update(engine, C);
2964
2965                 rv3d->render_engine = engine;
2966         }
2967
2968         /* setup view matrices */
2969         view3d_main_area_setup_view(scene, v3d, ar, NULL, NULL);
2970
2971         /* background draw */
2972         ED_region_pixelspace(ar);
2973
2974         if (clip_border) {
2975                 /* for border draw, we only need to clear a subset of the 3d view */
2976                 if (border_rect->xmax > border_rect->xmin && border_rect->ymax > border_rect->ymin) {
2977                         glGetIntegerv(GL_SCISSOR_BOX, scissor);
2978                         glScissor(border_rect->xmin, border_rect->ymin,
2979                                   BLI_rcti_size_x(border_rect), BLI_rcti_size_y(border_rect));
2980                 }
2981                 else {
2982                         return false;
2983                 }
2984         }
2985
2986         glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
2987         glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
2988
2989         if (v3d->flag & V3D_DISPBGPICS)
2990                 view3d_draw_bgpic(scene, ar, v3d, false, true);
2991         else
2992                 fdrawcheckerboard(0, 0, ar->winx, ar->winy);
2993
2994         /* render result draw */
2995         type = rv3d->render_engine->type;
2996         type->view_draw(rv3d->render_engine, C);
2997
2998         if (v3d->flag & V3D_DISPBGPICS)
2999                 view3d_draw_bgpic(scene, ar, v3d, true, true);
3000
3001         if (clip_border) {
3002                 /* restore scissor as it was before */
3003                 glScissor(scissor[0], scissor[1], scissor[2], scissor[3]);
3004         }
3005
3006         return true;
3007 }
3008
3009 static void view3d_main_area_draw_engine_info(View3D *v3d, RegionView3D *rv3d, ARegion *ar, bool render_border)
3010 {
3011         float fill_color[4] = {0.0f, 0.0f, 0.0f, 0.25f};
3012
3013         if (!rv3d->render_engine || !rv3d->render_engine->text[0])
3014                 return;
3015         
3016         if (render_border) {
3017                 /* draw darkened background color. no alpha because border render does
3018                  * partial redraw and will not redraw the area behind this info bar */
3019                 float alpha = 1.0f - fill_color[3];
3020                 Camera *camera = ED_view3d_camera_data_get(v3d, rv3d);
3021
3022                 if (camera) {
3023                         if (camera->flag & CAM_SHOWPASSEPARTOUT) {
3024                                 alpha *= (1.0f - camera->passepartalpha);
3025                         }
3026                 }
3027
3028                 UI_GetThemeColor3fv(TH_HIGH_GRAD, fill_color);
3029                 mul_v3_fl(fill_color, alpha);
3030                 fill_color[3] = 1.0f;
3031         }
3032
3033         ED_region_info_draw(ar, rv3d->render_engine->text, 1, fill_color);
3034 }
3035
3036 /*
3037  * Function to clear the view
3038  */
3039 static void view3d_main_area_clear(Scene *scene, View3D *v3d, ARegion *ar)
3040 {
3041         /* clear background */
3042         if (scene->world && (v3d->flag2 & V3D_RENDER_OVERRIDE)) {  /* clear with solid color */
3043                 if (scene->world->skytype & WO_SKYBLEND) {  /* blend sky */
3044                         int x, y;
3045                         float col_hor[3];
3046                         float col_zen[3];
3047
3048 #define VIEWGRAD_RES_X 16
3049 #define VIEWGRAD_RES_Y 16
3050
3051                         GLubyte grid_col[VIEWGRAD_RES_X][VIEWGRAD_RES_Y][4];
3052                         static float   grid_pos[VIEWGRAD_RES_X][VIEWGRAD_RES_Y][3];
3053                         static GLushort indices[VIEWGRAD_RES_X - 1][VIEWGRAD_RES_X - 1][4];
3054                         static bool buf_calculated = false;
3055
3056                         IMB_colormanagement_pixel_to_display_space_v3(col_hor, &scene->world->horr, &scene->view_settings,
3057                                                                       &scene->display_settings);
3058                         IMB_colormanagement_pixel_to_display_space_v3(col_zen, &scene->world->zenr, &scene->view_settings,
3059                                                                       &scene->display_settings);
3060
3061                         glMatrixMode(GL_PROJECTION);
3062                         glPushMatrix();
3063                         glLoadIdentity();
3064                         glMatrixMode(GL_MODELVIEW);
3065                         glPushMatrix();
3066                         glLoadIdentity();
3067
3068                         glShadeModel(GL_SMOOTH);
3069
3070                         /* calculate buffers the first time only */
3071                         if (!buf_calculated) {
3072                                 for (x = 0; x < VIEWGRAD_RES_X; x++) {
3073                                         for (y = 0; y < VIEWGRAD_RES_Y; y++) {
3074                                                 const float xf = (float)x / (float)(VIEWGRAD_RES_X - 1);
3075                                                 const float yf = (float)y / (float)(VIEWGRAD_RES_Y - 1);
3076
3077                                                 /* -1..1 range */
3078                                                 grid_pos[x][y][0] = (xf - 0.5f) * 2.0f;
3079                                                 grid_pos[x][y][1] = (yf - 0.5f) * 2.0f;
3080                                                 grid_pos[x][y][2] = 1.0;