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