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