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