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