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