svn merge ^/trunk/blender -r50091:50107
[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) / BLI_RCT_SIZE_X(&rect_view)) * ar->winx;
975         viewborder_r->xmax = ((rect_camera.xmax - rect_view.xmin) / BLI_RCT_SIZE_X(&rect_view)) * ar->winx;
976         viewborder_r->ymin = ((rect_camera.ymin - rect_view.ymin) / BLI_RCT_SIZE_Y(&rect_view)) * ar->winy;
977         viewborder_r->ymax = ((rect_camera.ymax - rect_view.ymin) / BLI_RCT_SIZE_Y(&rect_view)) * 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] = BLI_RCT_SIZE_X(&viewborder);
986         size_r[1] = BLI_RCT_SIZE_Y(&viewborder);
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, BLI_RCT_SIZE_X(&winrct), BLI_RCT_SIZE_Y(&winrct));
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_foreground, 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_foreground ? 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->aspy;
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 = minf(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_foreground, const short do_camera_frame)
1776 {
1777         RegionView3D *rv3d = ar->regiondata;
1778
1779         if ((v3d->flag & V3D_DISPBGPICS) == 0)
1780                 return;
1781
1782         /* disabled - mango request, since footage /w only render is quite useful
1783          * and this option is easy to disable all background images at once */
1784 #if 0
1785         if (v3d->flag2 & V3D_RENDER_OVERRIDE)
1786                 return;
1787 #endif
1788
1789         if ((rv3d->view == RV3D_VIEW_USER) || (rv3d->persp != RV3D_ORTHO)) {
1790                 if (rv3d->persp == RV3D_CAMOB) {
1791                         view3d_draw_bgpic(scene, ar, v3d, do_foreground, do_camera_frame);
1792                 }
1793         }
1794         else {
1795                 view3d_draw_bgpic(scene, ar, v3d, do_foreground, do_camera_frame);
1796         }
1797 }
1798
1799 /* ****************** View3d afterdraw *************** */
1800
1801 typedef struct View3DAfter {
1802         struct View3DAfter *next, *prev;
1803         struct Base *base;
1804         short dflag;
1805 } View3DAfter;
1806
1807 /* temp storage of Objects that need to be drawn as last */
1808 void ED_view3d_after_add(ListBase *lb, Base *base, const short dflag)
1809 {
1810         View3DAfter *v3da = MEM_callocN(sizeof(View3DAfter), "View 3d after");
1811         BLI_assert((base->flag & OB_FROMDUPLI) == 0);
1812         BLI_addtail(lb, v3da);
1813         v3da->base = base;
1814         v3da->dflag = dflag;
1815 }
1816
1817 /* disables write in zbuffer and draws it over */
1818 static void view3d_draw_transp(Scene *scene, ARegion *ar, View3D *v3d)
1819 {
1820         View3DAfter *v3da, *next;
1821         
1822         glDepthMask(0);
1823         v3d->transp = TRUE;
1824         
1825         for (v3da = v3d->afterdraw_transp.first; v3da; v3da = next) {
1826                 next = v3da->next;
1827                 draw_object(scene, ar, v3d, v3da->base, v3da->dflag);
1828                 BLI_remlink(&v3d->afterdraw_transp, v3da);
1829                 MEM_freeN(v3da);
1830         }
1831         v3d->transp = FALSE;
1832         
1833         glDepthMask(1);
1834         
1835 }
1836
1837 /* clears zbuffer and draws it over */
1838 static void view3d_draw_xray(Scene *scene, ARegion *ar, View3D *v3d, int clear)
1839 {
1840         View3DAfter *v3da, *next;
1841
1842         if (clear && v3d->zbuf)
1843                 glClear(GL_DEPTH_BUFFER_BIT);
1844
1845         v3d->xray = TRUE;
1846         for (v3da = v3d->afterdraw_xray.first; v3da; v3da = next) {
1847                 next = v3da->next;
1848                 draw_object(scene, ar, v3d, v3da->base, v3da->dflag);
1849                 BLI_remlink(&v3d->afterdraw_xray, v3da);
1850                 MEM_freeN(v3da);
1851         }
1852         v3d->xray = FALSE;
1853 }
1854
1855
1856 /* clears zbuffer and draws it over */
1857 static void view3d_draw_xraytransp(Scene *scene, ARegion *ar, View3D *v3d, int clear)
1858 {
1859         View3DAfter *v3da, *next;
1860
1861         if (clear && v3d->zbuf)
1862                 glClear(GL_DEPTH_BUFFER_BIT);
1863
1864         v3d->xray = TRUE;
1865         v3d->transp = TRUE;
1866         
1867         for (v3da = v3d->afterdraw_xraytransp.first; v3da; v3da = next) {
1868                 next = v3da->next;
1869                 draw_object(scene, ar, v3d, v3da->base, v3da->dflag);
1870                 BLI_remlink(&v3d->afterdraw_xraytransp, v3da);
1871                 MEM_freeN(v3da);
1872         }
1873
1874         v3d->transp = FALSE;
1875         v3d->xray = FALSE;
1876
1877 }
1878
1879 /* *********************** */
1880
1881 /*
1882  * In most cases call draw_dupli_objects,
1883  * draw_dupli_objects_color was added because when drawing set dupli's
1884  * we need to force the color
1885  */
1886
1887 #if 0
1888 int dupli_ob_sort(void *arg1, void *arg2)
1889 {
1890         void *p1 = ((DupliObject *)arg1)->ob;
1891         void *p2 = ((DupliObject *)arg2)->ob;
1892         int val = 0;
1893         if (p1 < p2) val = -1;
1894         else if (p1 > p2) val = 1;
1895         return val;
1896 }
1897 #endif
1898
1899
1900 static DupliObject *dupli_step(DupliObject *dob)
1901 {
1902         while (dob && dob->no_draw)
1903                 dob = dob->next;
1904         return dob;
1905 }
1906
1907 static void draw_dupli_objects_color(Scene *scene, ARegion *ar, View3D *v3d, Base *base, int color)
1908 {
1909         RegionView3D *rv3d = ar->regiondata;
1910         ListBase *lb;
1911         DupliObject *dob_prev = NULL, *dob, *dob_next = NULL;
1912         Base tbase = {NULL};
1913         BoundBox bb, *bb_tmp; /* use a copy because draw_object, calls clear_mesh_caches */
1914         GLuint displist = 0;
1915         short transflag, use_displist = -1;  /* -1 is initialize */
1916         char dt, dtx;
1917         
1918         if (base->object->restrictflag & OB_RESTRICT_VIEW) return;
1919         
1920         tbase.flag = OB_FROMDUPLI | base->flag;
1921         lb = object_duplilist(scene, base->object);
1922         // BLI_sortlist(lb, dupli_ob_sort); /* might be nice to have if we have a dupli list with mixed objects. */
1923
1924         dob = dupli_step(lb->first);
1925         if (dob) dob_next = dupli_step(dob->next);
1926
1927         for (; dob; dob_prev = dob, dob = dob_next, dob_next = dob_next ? dupli_step(dob_next->next) : NULL) {
1928                 tbase.object = dob->ob;
1929
1930                 /* extra service: draw the duplicator in drawtype of parent */
1931                 /* MIN2 for the drawtype to allow bounding box objects in groups for lods */
1932                 dt = tbase.object->dt;   tbase.object->dt = MIN2(tbase.object->dt, base->object->dt);
1933                 dtx = tbase.object->dtx; tbase.object->dtx = base->object->dtx;
1934
1935                 /* negative scale flag has to propagate */
1936                 transflag = tbase.object->transflag;
1937                 if (base->object->transflag & OB_NEG_SCALE)
1938                         tbase.object->transflag ^= OB_NEG_SCALE;
1939
1940                 UI_ThemeColorBlend(color, TH_BACK, 0.5);
1941
1942                 /* generate displist, test for new object */
1943                 if (dob_prev && dob_prev->ob != dob->ob) {
1944                         if (use_displist == TRUE)
1945                                 glDeleteLists(displist, 1);
1946
1947                         use_displist = -1;
1948                 }
1949
1950                 /* generate displist */
1951                 if (use_displist == -1) {
1952
1953                         /* note, since this was added, its checked (dob->type == OB_DUPLIGROUP)
1954                          * however this is very slow, it was probably needed for the NLA
1955                          * offset feature (used in group-duplicate.blend but no longer works in 2.5)
1956                          * so for now it should be ok to - campbell */
1957
1958                         if ( /* if this is the last no need  to make a displist */
1959                             (dob_next == NULL || dob_next->ob != dob->ob) ||
1960                             /* lamp drawing messes with matrices, could be handled smarter... but this works */
1961                             (dob->ob->type == OB_LAMP) ||
1962                             (dob->type == OB_DUPLIGROUP && dob->animated) ||
1963                             !(bb_tmp = BKE_object_boundbox_get(dob->ob)))
1964                         {
1965                                 // printf("draw_dupli_objects_color: skipping displist for %s\n", dob->ob->id.name+2);
1966                                 use_displist = FALSE;
1967                         }
1968                         else {
1969                                 // printf("draw_dupli_objects_color: using displist for %s\n", dob->ob->id.name+2);
1970                                 bb = *bb_tmp; /* must make a copy  */
1971
1972                                 /* disable boundbox check for list creation */
1973                                 BKE_object_boundbox_flag(dob->ob, OB_BB_DISABLED, 1);
1974                                 /* need this for next part of code */
1975                                 unit_m4(dob->ob->obmat);    /* obmat gets restored */
1976
1977                                 displist = glGenLists(1);
1978                                 glNewList(displist, GL_COMPILE);
1979                                 draw_object(scene, ar, v3d, &tbase, DRAW_CONSTCOLOR);
1980                                 glEndList();
1981
1982                                 use_displist = TRUE;
1983                                 BKE_object_boundbox_flag(dob->ob, OB_BB_DISABLED, 0);
1984                         }
1985                 }
1986                 if (use_displist) {
1987                         glMultMatrixf(dob->mat);
1988                         if (ED_view3d_boundbox_clip(rv3d, dob->mat, &bb))
1989                                 glCallList(displist);
1990                         glLoadMatrixf(rv3d->viewmat);
1991                 }
1992                 else {
1993                         copy_m4_m4(dob->ob->obmat, dob->mat);
1994                         draw_object(scene, ar, v3d, &tbase, DRAW_CONSTCOLOR);
1995                 }
1996
1997                 tbase.object->dt = dt;
1998                 tbase.object->dtx = dtx;
1999                 tbase.object->transflag = transflag;
2000         }
2001         
2002         /* Transp afterdraw disabled, afterdraw only stores base pointers, and duplis can be same obj */
2003         
2004         free_object_duplilist(lb);  /* does restore */
2005         
2006         if (use_displist)
2007                 glDeleteLists(displist, 1);
2008 }
2009
2010 static void draw_dupli_objects(Scene *scene, ARegion *ar, View3D *v3d, Base *base)
2011 {
2012         /* define the color here so draw_dupli_objects_color can be called
2013          * from the set loop */
2014         
2015         int color = (base->flag & SELECT) ? TH_SELECT : TH_WIRE;
2016         /* debug */
2017         if (base->object->dup_group && base->object->dup_group->id.us < 1)
2018                 color = TH_REDALERT;
2019         
2020         draw_dupli_objects_color(scene, ar, v3d, base, color);
2021 }
2022
2023 void view3d_update_depths_rect(ARegion *ar, ViewDepths *d, rcti *rect)
2024 {
2025         int x, y, w, h; 
2026         rcti r;
2027         /* clamp rect by area */
2028
2029         r.xmin = 0;
2030         r.xmax = ar->winx - 1;
2031         r.ymin = 0;
2032         r.ymax = ar->winy - 1;
2033
2034         /* Constrain rect to depth bounds */
2035         BLI_rcti_isect(&r, rect, rect);
2036
2037         /* assign values to compare with the ViewDepths */
2038         x = rect->xmin;
2039         y = rect->ymin;
2040
2041         w = BLI_RCT_SIZE_X(rect);
2042         h = BLI_RCT_SIZE_Y(rect);
2043
2044         if (w <= 0 || h <= 0) {
2045                 if (d->depths)
2046                         MEM_freeN(d->depths);
2047                 d->depths = NULL;
2048
2049                 d->damaged = FALSE;
2050         }
2051         else if (d->w != w ||
2052                  d->h != h ||
2053                  d->x != x ||
2054                  d->y != y ||
2055                  d->depths == NULL
2056                  )
2057         {
2058                 d->x = x;
2059                 d->y = y;
2060                 d->w = w;
2061                 d->h = h;
2062
2063                 if (d->depths)
2064                         MEM_freeN(d->depths);
2065
2066                 d->depths = MEM_mallocN(sizeof(float) * d->w * d->h, "View depths Subset");
2067                 
2068                 d->damaged = TRUE;
2069         }
2070
2071         if (d->damaged) {
2072                 glReadPixels(ar->winrct.xmin + d->x, ar->winrct.ymin + d->y, d->w, d->h, GL_DEPTH_COMPONENT, GL_FLOAT, d->depths);
2073                 glGetDoublev(GL_DEPTH_RANGE, d->depth_range);
2074                 d->damaged = FALSE;
2075         }
2076 }
2077
2078 /* note, with nouveau drivers the glReadPixels() is very slow. [#24339] */
2079 void ED_view3d_depth_update(ARegion *ar)
2080 {
2081         RegionView3D *rv3d = ar->regiondata;
2082         
2083         /* Create storage for, and, if necessary, copy depth buffer */
2084         if (!rv3d->depths) rv3d->depths = MEM_callocN(sizeof(ViewDepths), "ViewDepths");
2085         if (rv3d->depths) {
2086                 ViewDepths *d = rv3d->depths;
2087                 if (d->w != ar->winx ||
2088                     d->h != ar->winy ||
2089                     !d->depths)
2090                 {
2091                         d->w = ar->winx;
2092                         d->h = ar->winy;
2093                         if (d->depths)
2094                                 MEM_freeN(d->depths);
2095                         d->depths = MEM_mallocN(sizeof(float) * d->w * d->h, "View depths");
2096                         d->damaged = 1;
2097                 }
2098                 
2099                 if (d->damaged) {
2100                         glReadPixels(ar->winrct.xmin, ar->winrct.ymin, d->w, d->h,
2101                                      GL_DEPTH_COMPONENT, GL_FLOAT, d->depths);
2102                         
2103                         glGetDoublev(GL_DEPTH_RANGE, d->depth_range);
2104                         
2105                         d->damaged = 0;
2106                 }
2107         }
2108 }
2109
2110 /* utility function to find the closest Z value, use for autodepth */
2111 float view3d_depth_near(ViewDepths *d)
2112 {
2113         /* convert to float for comparisons */
2114         const float near = (float)d->depth_range[0];
2115         const float far_real = (float)d->depth_range[1];
2116         float far = far_real;
2117
2118         const float *depths = d->depths;
2119         float depth = FLT_MAX;
2120         int i = (int)d->w * (int)d->h; /* cast to avoid short overflow */
2121
2122         /* far is both the starting 'far' value
2123          * and the closest value found. */      
2124         while (i--) {
2125                 depth = *depths++;
2126                 if ((depth < far) && (depth > near)) {
2127                         far = depth;
2128                 }
2129         }
2130
2131         return far == far_real ? FLT_MAX : far;
2132 }
2133
2134 void draw_depth_gpencil(Scene *scene, ARegion *ar, View3D *v3d)
2135 {
2136         short zbuf = v3d->zbuf;
2137         RegionView3D *rv3d = ar->regiondata;
2138
2139         setwinmatrixview3d(ar, v3d, NULL);  /* 0= no pick rect */
2140         setviewmatrixview3d(scene, v3d, rv3d);  /* note: calls BKE_object_where_is_calc for camera... */
2141
2142         mult_m4_m4m4(rv3d->persmat, rv3d->winmat, rv3d->viewmat);
2143         invert_m4_m4(rv3d->persinv, rv3d->persmat);
2144         invert_m4_m4(rv3d->viewinv, rv3d->viewmat);
2145
2146         glClear(GL_DEPTH_BUFFER_BIT);
2147
2148         glLoadMatrixf(rv3d->viewmat);
2149
2150         v3d->zbuf = TRUE;
2151         glEnable(GL_DEPTH_TEST);
2152
2153         draw_gpencil_view3d(scene, v3d, ar, 1);
2154         
2155         v3d->zbuf = zbuf;
2156
2157 }
2158
2159 void draw_depth(Scene *scene, ARegion *ar, View3D *v3d, int (*func)(void *))
2160 {
2161         RegionView3D *rv3d = ar->regiondata;
2162         Base *base;
2163         short zbuf = v3d->zbuf;
2164         short flag = v3d->flag;
2165         float glalphaclip = U.glalphaclip;
2166         int obcenter_dia = U.obcenter_dia;
2167         /* temp set drawtype to solid */
2168         
2169         /* Setting these temporarily is not nice */
2170         v3d->flag &= ~V3D_SELECT_OUTLINE;
2171         U.glalphaclip = 0.5; /* not that nice but means we wont zoom into billboards */
2172         U.obcenter_dia = 0;
2173         
2174         setwinmatrixview3d(ar, v3d, NULL);  /* 0= no pick rect */
2175         setviewmatrixview3d(scene, v3d, rv3d);  /* note: calls BKE_object_where_is_calc for camera... */
2176         
2177         mult_m4_m4m4(rv3d->persmat, rv3d->winmat, rv3d->viewmat);
2178         invert_m4_m4(rv3d->persinv, rv3d->persmat);
2179         invert_m4_m4(rv3d->viewinv, rv3d->viewmat);
2180         
2181         glClear(GL_DEPTH_BUFFER_BIT);
2182         
2183         glLoadMatrixf(rv3d->viewmat);
2184 //      persp(PERSP_STORE);  /* store correct view for persp(PERSP_VIEW) calls */
2185         
2186         if (rv3d->rflag & RV3D_CLIPPING) {
2187                 ED_view3d_clipping_set(rv3d);
2188         }
2189         
2190         v3d->zbuf = TRUE;
2191         glEnable(GL_DEPTH_TEST);
2192         
2193         /* draw set first */
2194         if (scene->set) {
2195                 Scene *sce_iter;
2196                 for (SETLOOPER(scene->set, sce_iter, base)) {
2197                         if (v3d->lay & base->lay) {
2198                                 if (func == NULL || func(base)) {
2199                                         draw_object(scene, ar, v3d, base, 0);
2200                                         if (base->object->transflag & OB_DUPLI) {
2201                                                 draw_dupli_objects_color(scene, ar, v3d, base, TH_WIRE);
2202                                         }
2203                                 }
2204                         }
2205                 }
2206         }
2207         
2208         for (base = scene->base.first; base; base = base->next) {
2209                 if (v3d->lay & base->lay) {
2210                         if (func == NULL || func(base)) {
2211                                 /* dupli drawing */
2212                                 if (base->object->transflag & OB_DUPLI) {
2213                                         draw_dupli_objects(scene, ar, v3d, base);
2214                                 }
2215                                 draw_object(scene, ar, v3d, base, 0);
2216                         }
2217                 }
2218         }
2219         
2220         /* this isn't that nice, draw xray objects as if they are normal */
2221         if (v3d->afterdraw_transp.first ||
2222             v3d->afterdraw_xray.first ||
2223             v3d->afterdraw_xraytransp.first)
2224         {
2225                 View3DAfter *v3da, *next;
2226                 int mask_orig;
2227
2228                 v3d->xray = TRUE;
2229                 
2230                 /* transp materials can change the depth mask, see #21388 */
2231                 glGetIntegerv(GL_DEPTH_WRITEMASK, &mask_orig);
2232
2233
2234                 if (v3d->afterdraw_xray.first || v3d->afterdraw_xraytransp.first) {
2235                         glDepthFunc(GL_ALWAYS); /* always write into the depth bufer, overwriting front z values */
2236                         for (v3da = v3d->afterdraw_xray.first; v3da; v3da = next) {
2237                                 next = v3da->next;
2238                                 draw_object(scene, ar, v3d, v3da->base, 0);
2239                         }
2240                         glDepthFunc(GL_LEQUAL); /* Now write the depth buffer normally */
2241                 }
2242
2243                 /* draw 3 passes, transp/xray/xraytransp */
2244                 v3d->xray = FALSE;
2245                 v3d->transp = TRUE;
2246                 for (v3da = v3d->afterdraw_transp.first; v3da; v3da = next) {
2247                         next = v3da->next;
2248                         draw_object(scene, ar, v3d, v3da->base, 0);
2249                         BLI_remlink(&v3d->afterdraw_transp, v3da);
2250                         MEM_freeN(v3da);
2251                 }
2252
2253                 v3d->xray = TRUE;
2254                 v3d->transp = FALSE;
2255                 for (v3da = v3d->afterdraw_xray.first; v3da; v3da = next) {
2256                         next = v3da->next;
2257                         draw_object(scene, ar, v3d, v3da->base, 0);
2258                         BLI_remlink(&v3d->afterdraw_xray, v3da);
2259                         MEM_freeN(v3da);
2260                 }
2261
2262                 v3d->xray = TRUE;
2263                 v3d->transp = TRUE;
2264                 for (v3da = v3d->afterdraw_xraytransp.first; v3da; v3da = next) {
2265                         next = v3da->next;
2266                         draw_object(scene, ar, v3d, v3da->base, 0);
2267                         BLI_remlink(&v3d->afterdraw_xraytransp, v3da);
2268                         MEM_freeN(v3da);
2269                 }
2270
2271                 
2272                 v3d->xray = FALSE;
2273                 v3d->transp = FALSE;
2274
2275                 glDepthMask(mask_orig);
2276         }
2277         
2278         if (rv3d->rflag & RV3D_CLIPPING)
2279                 ED_view3d_clipping_disable();
2280         
2281         v3d->zbuf = zbuf;
2282         if (!v3d->zbuf) glDisable(GL_DEPTH_TEST);
2283
2284         U.glalphaclip = glalphaclip;
2285         v3d->flag = flag;
2286         U.obcenter_dia = obcenter_dia;
2287 }
2288
2289 typedef struct View3DShadow {
2290         struct View3DShadow *next, *prev;
2291         GPULamp *lamp;
2292 } View3DShadow;
2293
2294 static void gpu_render_lamp_update(Scene *scene, View3D *v3d, Object *ob, Object *par,
2295                                    float obmat[][4], ListBase *shadows)
2296 {
2297         GPULamp *lamp;
2298         Lamp *la = (Lamp *)ob->data;
2299         View3DShadow *shadow;
2300         
2301         lamp = GPU_lamp_from_blender(scene, ob, par);
2302         
2303         if (lamp) {
2304                 GPU_lamp_update(lamp, ob->lay, (ob->restrictflag & OB_RESTRICT_RENDER), obmat);
2305                 GPU_lamp_update_colors(lamp, la->r, la->g, la->b, la->energy);
2306                 
2307                 if ((ob->lay & v3d->lay) && GPU_lamp_has_shadow_buffer(lamp)) {
2308                         shadow = MEM_callocN(sizeof(View3DShadow), "View3DShadow");
2309                         shadow->lamp = lamp;
2310                         BLI_addtail(shadows, shadow);
2311                 }
2312         }
2313 }
2314
2315 static void gpu_update_lamps_shadows(Scene *scene, View3D *v3d)
2316 {
2317         ListBase shadows;
2318         View3DShadow *shadow;
2319         Scene *sce_iter;
2320         Base *base;
2321         Object *ob;
2322         
2323         shadows.first = shadows.last = NULL;
2324         
2325         /* update lamp transform and gather shadow lamps */
2326         for (SETLOOPER(scene, sce_iter, base)) {
2327                 ob = base->object;
2328                 
2329                 if (ob->type == OB_LAMP)
2330                         gpu_render_lamp_update(scene, v3d, ob, NULL, ob->obmat, &shadows);
2331                 
2332                 if (ob->transflag & OB_DUPLI) {
2333                         DupliObject *dob;
2334                         ListBase *lb = object_duplilist(scene, ob);
2335                         
2336                         for (dob = lb->first; dob; dob = dob->next)
2337                                 if (dob->ob->type == OB_LAMP)
2338                                         gpu_render_lamp_update(scene, v3d, dob->ob, ob, dob->mat, &shadows);
2339                         
2340                         free_object_duplilist(lb);
2341                 }
2342         }
2343         
2344         /* render shadows after updating all lamps, nested object_duplilist
2345          * don't work correct since it's replacing object matrices */
2346         for (shadow = shadows.first; shadow; shadow = shadow->next) {
2347                 /* this needs to be done better .. */
2348                 float viewmat[4][4], winmat[4][4];
2349                 int drawtype, lay, winsize, flag2 = v3d->flag2;
2350                 ARegion ar = {NULL};
2351                 RegionView3D rv3d = {{{0}}};
2352                 
2353                 drawtype = v3d->drawtype;
2354                 lay = v3d->lay;
2355                 
2356                 v3d->drawtype = OB_SOLID;
2357                 v3d->lay &= GPU_lamp_shadow_layer(shadow->lamp);
2358                 v3d->flag2 &= ~V3D_SOLID_TEX;
2359                 v3d->flag2 |= V3D_RENDER_OVERRIDE | V3D_RENDER_SHADOW;
2360                 
2361                 GPU_lamp_shadow_buffer_bind(shadow->lamp, viewmat, &winsize, winmat);
2362
2363                 ar.regiondata = &rv3d;
2364                 ar.regiontype = RGN_TYPE_WINDOW;
2365                 rv3d.persp = RV3D_CAMOB;
2366                 copy_m4_m4(rv3d.winmat, winmat);
2367                 copy_m4_m4(rv3d.viewmat, viewmat);
2368                 invert_m4_m4(rv3d.viewinv, rv3d.viewmat);
2369                 mult_m4_m4m4(rv3d.persmat, rv3d.winmat, rv3d.viewmat);
2370                 invert_m4_m4(rv3d.persinv, rv3d.viewinv);
2371
2372                 ED_view3d_draw_offscreen(scene, v3d, &ar, winsize, winsize, viewmat, winmat, FALSE);
2373                 GPU_lamp_shadow_buffer_unbind(shadow->lamp);
2374                 
2375                 v3d->drawtype = drawtype;
2376                 v3d->lay = lay;
2377                 v3d->flag2 = flag2;
2378         }
2379         
2380         BLI_freelistN(&shadows);
2381 }
2382
2383 /* *********************** customdata **************** */
2384
2385 CustomDataMask ED_view3d_datamask(Scene *scene, View3D *v3d)
2386 {
2387         CustomDataMask mask = 0;
2388
2389         if (ELEM(v3d->drawtype, OB_TEXTURE, OB_MATERIAL) ||
2390             ((v3d->drawtype == OB_SOLID) && (v3d->flag2 & V3D_SOLID_TEX)))
2391         {
2392                 mask |= CD_MASK_MTFACE | CD_MASK_MCOL;
2393
2394                 if (BKE_scene_use_new_shading_nodes(scene)) {
2395                         if (v3d->drawtype == OB_MATERIAL)
2396                                 mask |= CD_MASK_ORCO;
2397                 }
2398                 else {
2399                         if (scene->gm.matmode == GAME_MAT_GLSL)
2400                                 mask |= CD_MASK_ORCO;
2401                 }
2402         }
2403
2404         return mask;
2405 }
2406
2407 CustomDataMask ED_view3d_object_datamask(Scene *scene)
2408 {
2409         Object *ob = scene->basact ? scene->basact->object : NULL;
2410         CustomDataMask mask = 0;
2411
2412         if (ob) {
2413                 /* check if we need tfaces & mcols due to face select or texture paint */
2414                 if (paint_facesel_test(ob) || (ob->mode & OB_MODE_TEXTURE_PAINT)) {
2415                         mask |= CD_MASK_MTFACE | CD_MASK_MCOL;
2416                 }
2417
2418                 /* check if we need mcols due to vertex paint or weightpaint */
2419                 if (ob->mode & OB_MODE_VERTEX_PAINT) {
2420                         mask |= CD_MASK_MCOL;
2421                 }
2422
2423                 if (ob->mode & OB_MODE_WEIGHT_PAINT) {
2424                         mask |= CD_MASK_PREVIEW_MCOL;
2425                 }
2426
2427                 if (ob->mode & OB_MODE_EDIT)
2428                         mask |= CD_MASK_MVERT_SKIN;
2429         }
2430
2431         return mask;
2432 }
2433
2434 /* goes over all modes and view3d settings */
2435 CustomDataMask ED_view3d_screen_datamask(bScreen *screen)
2436 {
2437         Scene *scene = screen->scene;
2438         CustomDataMask mask = CD_MASK_BAREMESH;
2439         ScrArea *sa;
2440         
2441         /* check if we need tfaces & mcols due to view mode */
2442         for (sa = screen->areabase.first; sa; sa = sa->next) {
2443                 if (sa->spacetype == SPACE_VIEW3D) {
2444                         mask |= ED_view3d_datamask(scene, (View3D *)sa->spacedata.first);
2445                 }
2446         }
2447
2448         mask |= ED_view3d_object_datamask(scene);
2449
2450         return mask;
2451 }
2452
2453 void ED_view3d_update_viewmat(Scene *scene, View3D *v3d, ARegion *ar, float viewmat[][4], float winmat[][4])
2454 {
2455         RegionView3D *rv3d = ar->regiondata;
2456
2457         /* setup window matrices */
2458         if (winmat)
2459                 copy_m4_m4(rv3d->winmat, winmat);
2460         else
2461                 setwinmatrixview3d(ar, v3d, NULL);  /* NULL= no pickrect */
2462
2463         /* setup view matrix */
2464         if (viewmat)
2465                 copy_m4_m4(rv3d->viewmat, viewmat);
2466         else
2467                 setviewmatrixview3d(scene, v3d, rv3d);  /* note: calls BKE_object_where_is_calc for camera... */
2468
2469         /* update utilitity matrices */
2470         mult_m4_m4m4(rv3d->persmat, rv3d->winmat, rv3d->viewmat);
2471         invert_m4_m4(rv3d->persinv, rv3d->persmat);
2472         invert_m4_m4(rv3d->viewinv, rv3d->viewmat);
2473
2474         /* calculate pixelsize factor once, is used for lamps and obcenters */
2475         {
2476                 /* note:  '1.0f / len_v3(v1)'  replaced  'len_v3(rv3d->viewmat[0])'
2477                  * because of float point precision problems at large values [#23908] */
2478                 float v1[3], v2[3];
2479                 float len1, len2;
2480
2481                 v1[0] = rv3d->persmat[0][0];
2482                 v1[1] = rv3d->persmat[1][0];
2483                 v1[2] = rv3d->persmat[2][0];
2484
2485                 v2[0] = rv3d->persmat[0][1];
2486                 v2[1] = rv3d->persmat[1][1];
2487                 v2[2] = rv3d->persmat[2][1];
2488
2489                 len1 = 1.0f / len_v3(v1);
2490                 len2 = 1.0f / len_v3(v2);
2491
2492                 rv3d->pixsize = (2.0f * MAX2(len1, len2)) / (float)MAX2(ar->winx, ar->winy);
2493         }
2494 }
2495
2496 static void view3d_main_area_setup_view(Scene *scene, View3D *v3d, ARegion *ar, float viewmat[][4], float winmat[][4])
2497 {
2498         RegionView3D *rv3d = ar->regiondata;
2499
2500         ED_view3d_update_viewmat(scene, v3d, ar, viewmat, winmat);
2501
2502         /* set for opengl */
2503         glMatrixMode(GL_PROJECTION);
2504         glLoadMatrixf(rv3d->winmat);
2505         glMatrixMode(GL_MODELVIEW);
2506         glLoadMatrixf(rv3d->viewmat);
2507 }
2508
2509 void ED_view3d_draw_offscreen(Scene *scene, View3D *v3d, ARegion *ar,
2510                               int winx, int winy, float viewmat[][4], float winmat[][4],
2511                               int do_bgpic)
2512 {
2513         RegionView3D *rv3d = ar->regiondata;
2514         Base *base;
2515         float backcol[3];
2516         int bwinx, bwiny;
2517         rcti brect;
2518
2519         glPushMatrix();
2520
2521         /* set temporary new size */
2522         bwinx = ar->winx;
2523         bwiny = ar->winy;
2524         brect = ar->winrct;
2525         
2526         ar->winx = winx;
2527         ar->winy = winy;
2528         ar->winrct.xmin = 0;
2529         ar->winrct.ymin = 0;
2530         ar->winrct.xmax = winx;
2531         ar->winrct.ymax = winy;
2532
2533         /* set theme */
2534         UI_SetTheme(SPACE_VIEW3D, RGN_TYPE_WINDOW);
2535         
2536         /* set flags */
2537         G.f |= G_RENDER_OGL;
2538
2539         /* free images which can have changed on frame-change
2540          * warning! can be slow so only free animated images - campbell */
2541         GPU_free_images_anim();
2542         
2543         /* shadow buffers, before we setup matrices */
2544         if (draw_glsl_material(scene, NULL, v3d, v3d->drawtype))
2545                 gpu_update_lamps_shadows(scene, v3d);
2546
2547         /* set background color, fallback on the view background color
2548          * (if active clip is set but frame is failed to load fallback to horizon color as background) */
2549         if (scene->world) {
2550                 if (scene->r.color_mgt_flag & R_COLOR_MANAGEMENT)
2551                         linearrgb_to_srgb_v3_v3(backcol, &scene->world->horr);
2552                 else
2553                         copy_v3_v3(backcol, &scene->world->horr);
2554                 glClearColor(backcol[0], backcol[1], backcol[2], 0.0);
2555         }
2556         else {
2557                 UI_ThemeClearColor(TH_BACK);
2558         }
2559
2560
2561         glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
2562
2563         /* setup view matrices */
2564         view3d_main_area_setup_view(scene, v3d, ar, viewmat, winmat);
2565
2566         if (rv3d->rflag & RV3D_CLIPPING)
2567                 view3d_draw_clipping(rv3d);
2568
2569         /* set zbuffer */
2570         if (v3d->drawtype > OB_WIRE) {
2571                 v3d->zbuf = TRUE;
2572                 glEnable(GL_DEPTH_TEST);
2573         }
2574         else
2575                 v3d->zbuf = FALSE;
2576
2577         /* important to do before clipping */
2578         if (do_bgpic) {
2579                 view3d_draw_bgpic_test(scene, ar, v3d, FALSE, FALSE);
2580         }
2581
2582         if (rv3d->rflag & RV3D_CLIPPING)
2583                 ED_view3d_clipping_set(rv3d);
2584
2585         /* draw set first */
2586         if (scene->set) {
2587                 Scene *sce_iter;
2588                 for (SETLOOPER(scene->set, sce_iter, base)) {
2589                         if (v3d->lay & base->lay) {
2590                                 UI_ThemeColorBlend(TH_WIRE, TH_BACK, 0.6f);
2591                                 draw_object(scene, ar, v3d, base, DRAW_CONSTCOLOR | DRAW_SCENESET);
2592                                 
2593                                 if (base->object->transflag & OB_DUPLI)
2594                                         draw_dupli_objects_color(scene, ar, v3d, base, TH_WIRE);
2595                         }
2596                 }
2597         }
2598         
2599         /* then draw not selected and the duplis, but skip editmode object */
2600         for (base = scene->base.first; base; base = base->next) {
2601                 if (v3d->lay & base->lay) {
2602                         /* dupli drawing */
2603                         if (base->object->transflag & OB_DUPLI)
2604                                 draw_dupli_objects(scene, ar, v3d, base);
2605
2606                         draw_object(scene, ar, v3d, base, 0);
2607                 }
2608         }
2609
2610         /* must be before xray draw which clears the depth buffer */
2611         if (v3d->zbuf) glDisable(GL_DEPTH_TEST);
2612         draw_gpencil_view3d(scene, v3d, ar, 1);
2613         if (v3d->zbuf) glEnable(GL_DEPTH_TEST);
2614
2615         /* transp and X-ray afterdraw stuff */
2616         if (v3d->afterdraw_transp.first)     view3d_draw_transp(scene, ar, v3d);
2617         if (v3d->afterdraw_xray.first)       view3d_draw_xray(scene, ar, v3d, 1);       /* clears zbuffer if it is used! */
2618         if (v3d->afterdraw_xraytransp.first) view3d_draw_xraytransp(scene, ar, v3d, 1);
2619
2620         if (rv3d->rflag & RV3D_CLIPPING)
2621                 ED_view3d_clipping_disable();
2622
2623         /* important to do after clipping */
2624         if (do_bgpic) {
2625                 view3d_draw_bgpic_test(scene, ar, v3d, TRUE, FALSE);
2626         }
2627
2628         /* cleanup */
2629         if (v3d->zbuf) {
2630                 v3d->zbuf = FALSE;
2631                 glDisable(GL_DEPTH_TEST);
2632         }
2633
2634         /* draw grease-pencil stuff */
2635         ED_region_pixelspace(ar);
2636
2637         /* draw grease-pencil stuff - needed to get paint-buffer shown too (since it's 2D) */
2638         draw_gpencil_view3d(scene, v3d, ar, 0);
2639
2640         /* freeing the images again here could be done after the operator runs, leaving for now */
2641         GPU_free_images_anim();
2642
2643         /* restore size */
2644         ar->winx = bwinx;
2645         ar->winy = bwiny;
2646         ar->winrct = brect;
2647
2648         glPopMatrix();
2649
2650         /* XXX, without this the sequencer flickers with opengl draw enabled, need to find out why - campbell */
2651         glColor4ub(255, 255, 255, 255);
2652
2653         G.f &= ~G_RENDER_OGL;
2654 }
2655
2656 /* utility func for ED_view3d_draw_offscreen */
2657 ImBuf *ED_view3d_draw_offscreen_imbuf(Scene *scene, View3D *v3d, ARegion *ar,
2658                                       int sizex, int sizey, unsigned int flag, int draw_background, char err_out[256])
2659 {
2660         RegionView3D *rv3d = ar->regiondata;
2661         ImBuf *ibuf;
2662         GPUOffScreen *ofs;
2663         
2664         /* state changes make normal drawing go weird otherwise */
2665         glPushAttrib(GL_LIGHTING_BIT);
2666
2667         /* bind */
2668         ofs = GPU_offscreen_create(sizex, sizey, err_out);
2669         if (ofs == NULL)
2670                 return NULL;
2671
2672         GPU_offscreen_bind(ofs);
2673
2674         /* render 3d view */
2675         if (rv3d->persp == RV3D_CAMOB && v3d->camera) {
2676                 CameraParams params;
2677
2678                 BKE_camera_params_init(&params);
2679                 BKE_camera_params_from_object(&params, v3d->camera);
2680                 BKE_camera_params_compute_viewplane(&params, sizex, sizey, scene->r.xasp, scene->r.yasp);
2681                 BKE_camera_params_compute_matrix(&params);
2682
2683                 ED_view3d_draw_offscreen(scene, v3d, ar, sizex, sizey, NULL, params.winmat, draw_background);
2684         }
2685         else {
2686                 ED_view3d_draw_offscreen(scene, v3d, ar, sizex, sizey, NULL, NULL, draw_background);
2687         }
2688
2689         /* read in pixels & stamp */
2690         ibuf = IMB_allocImBuf(sizex, sizey, 32, flag);
2691
2692         if (ibuf->rect_float)
2693                 GPU_offscreen_read_pixels(ofs, GL_FLOAT, ibuf->rect_float);
2694         else if (ibuf->rect)
2695                 GPU_offscreen_read_pixels(ofs, GL_UNSIGNED_BYTE, ibuf->rect);
2696
2697         /* unbind */
2698         GPU_offscreen_unbind(ofs);
2699         GPU_offscreen_free(ofs);
2700
2701         glPopAttrib();
2702         
2703         if (ibuf->rect_float && ibuf->rect)
2704                 IMB_rect_from_float(ibuf);
2705         
2706         return ibuf;
2707 }
2708
2709 /* creates own 3d views, used by the sequencer */
2710 ImBuf *ED_view3d_draw_offscreen_imbuf_simple(Scene *scene, Object *camera, int width, int height,
2711                                              unsigned int flag, int drawtype, int draw_background, char err_out[256])
2712 {
2713         View3D v3d = {NULL};
2714         ARegion ar = {NULL};
2715         RegionView3D rv3d = {{{0}}};
2716
2717         /* connect data */
2718         v3d.regionbase.first = v3d.regionbase.last = &ar;
2719         ar.regiondata = &rv3d;
2720         ar.regiontype = RGN_TYPE_WINDOW;
2721
2722         v3d.camera = camera;
2723         v3d.lay = scene->lay;
2724         v3d.drawtype = drawtype;
2725         v3d.flag2 = V3D_RENDER_OVERRIDE;
2726
2727         rv3d.persp = RV3D_CAMOB;
2728
2729         copy_m4_m4(rv3d.viewinv, v3d.camera->obmat);
2730         normalize_m4(rv3d.viewinv);
2731         invert_m4_m4(rv3d.viewmat, rv3d.viewinv);
2732
2733         {
2734                 CameraParams params;
2735
2736                 BKE_camera_params_init(&params);
2737                 BKE_camera_params_from_object(&params, v3d.camera);
2738                 BKE_camera_params_compute_viewplane(&params, width, height, scene->r.xasp, scene->r.yasp);
2739                 BKE_camera_params_compute_matrix(&params);
2740
2741                 copy_m4_m4(rv3d.winmat, params.winmat);
2742                 v3d.near = params.clipsta;
2743                 v3d.far = params.clipend;
2744                 v3d.lens = params.lens;
2745         }
2746
2747         mult_m4_m4m4(rv3d.persmat, rv3d.winmat, rv3d.viewmat);
2748         invert_m4_m4(rv3d.persinv, rv3d.viewinv);
2749
2750         return ED_view3d_draw_offscreen_imbuf(scene, &v3d, &ar, width, height, flag, draw_background, err_out);
2751
2752         // seq_view3d_cb(scene, cfra, render_size, seqrectx, seqrecty);
2753 }
2754
2755
2756 /* NOTE: the info that this uses is updated in ED_refresh_viewport_fps(), 
2757  * which currently gets called during SCREEN_OT_animation_step.
2758  */
2759 static void draw_viewport_fps(Scene *scene, ARegion *ar)
2760 {
2761         ScreenFrameRateInfo *fpsi = scene->fps_info;
2762         float fps;
2763         char printable[16];
2764         int i, tot;
2765         
2766         if (!fpsi || !fpsi->lredrawtime || !fpsi->redrawtime)
2767                 return;
2768         
2769         printable[0] = '\0';
2770         
2771 #if 0
2772         /* this is too simple, better do an average */
2773         fps = (float)(1.0 / (fpsi->lredrawtime - fpsi->redrawtime))
2774 #else
2775         fpsi->redrawtimes_fps[fpsi->redrawtime_index] = (float)(1.0 / (fpsi->lredrawtime - fpsi->redrawtime));
2776         
2777         for (i = 0, tot = 0, fps = 0.0f; i < REDRAW_FRAME_AVERAGE; i++) {
2778                 if (fpsi->redrawtimes_fps[i]) {
2779                         fps += fpsi->redrawtimes_fps[i];
2780                         tot++;
2781                 }
2782         }
2783         if (tot) {
2784                 fpsi->redrawtime_index = (fpsi->redrawtime_index + 1) % REDRAW_FRAME_AVERAGE;
2785                 
2786                 //fpsi->redrawtime_index++;
2787                 //if (fpsi->redrawtime >= REDRAW_FRAME_AVERAGE)
2788                 //      fpsi->redrawtime = 0;
2789                 
2790                 fps = fps / tot;
2791         }
2792 #endif
2793
2794         /* is this more then half a frame behind? */
2795         if (fps + 0.5f < (float)(FPS)) {
2796                 UI_ThemeColor(TH_REDALERT);
2797                 BLI_snprintf(printable, sizeof(printable), "fps: %.2f", fps);
2798         } 
2799         else {
2800                 UI_ThemeColor(TH_TEXT_HI);
2801                 BLI_snprintf(printable, sizeof(printable), "fps: %i", (int)(fps + 0.5f));
2802         }
2803         
2804         BLF_draw_default_ascii(22,  ar->winy - 17, 0.0f, printable, sizeof(printable));
2805 }
2806
2807 static void view3d_main_area_draw_objects(const bContext *C, ARegion *ar, const char **grid_unit);
2808
2809 static int view3d_main_area_do_render_draw(const bContext *C)
2810 {
2811         Scene *scene = CTX_data_scene(C);
2812         RenderEngineType *type = RE_engines_find(scene->r.engine);
2813
2814         return (type && type->view_update && type->view_draw);
2815 }
2816
2817 static int view3d_main_area_draw_engine(const bContext *C, ARegion *ar, int draw_border)
2818 {
2819         Scene *scene = CTX_data_scene(C);
2820         View3D *v3d = CTX_wm_view3d(C);
2821         RegionView3D *rv3d = CTX_wm_region_view3d(C);
2822         RenderEngineType *type;
2823         GLint scissor[4];
2824
2825         /* create render engine */
2826         if (!rv3d->render_engine) {
2827                 RenderEngine *engine;
2828
2829                 type = RE_engines_find(scene->r.engine);
2830
2831                 if (!(type->view_update && type->view_draw))
2832                         return 0;
2833
2834                 engine = RE_engine_create(type);
2835
2836                 engine->tile_x = scene->r.xparts;
2837                 engine->tile_y = scene->r.yparts;
2838
2839                 type->view_update(engine, C);
2840
2841                 rv3d->render_engine = engine;
2842         }
2843
2844         /* setup view matrices */
2845         view3d_main_area_setup_view(scene, v3d, ar, NULL, NULL);
2846
2847         /* background draw */
2848         ED_region_pixelspace(ar);
2849
2850         if (draw_border) {
2851                 /* for border draw, we only need to clear a subset of the 3d view */
2852                 rctf viewborder;
2853                 rcti cliprct;
2854
2855                 ED_view3d_calc_camera_border(scene, ar, v3d, rv3d, &viewborder, FALSE);
2856
2857                 cliprct.xmin = viewborder.xmin + scene->r.border.xmin * BLI_RCT_SIZE_X(&viewborder);
2858                 cliprct.ymin = viewborder.ymin + scene->r.border.ymin * BLI_RCT_SIZE_Y(&viewborder);
2859                 cliprct.xmax = viewborder.xmin + scene->r.border.xmax * BLI_RCT_SIZE_X(&viewborder);
2860                 cliprct.ymax = viewborder.ymin + scene->r.border.ymax * BLI_RCT_SIZE_Y(&viewborder);
2861
2862                 cliprct.xmin += ar->winrct.xmin;
2863                 cliprct.xmax += ar->winrct.xmin;
2864                 cliprct.ymin += ar->winrct.ymin;
2865                 cliprct.ymax += ar->winrct.ymin;
2866
2867                 cliprct.xmin = CLAMPIS(cliprct.xmin, ar->winrct.xmin, ar->winrct.xmax);
2868                 cliprct.ymin = CLAMPIS(cliprct.ymin, ar->winrct.ymin, ar->winrct.ymax);
2869                 cliprct.xmax = CLAMPIS(cliprct.xmax, ar->winrct.xmin, ar->winrct.xmax);
2870                 cliprct.ymax = CLAMPIS(cliprct.ymax, ar->winrct.ymin, ar->winrct.ymax);
2871
2872                 if (cliprct.xmax > cliprct.xmin && cliprct.ymax > cliprct.ymin) {
2873                         glGetIntegerv(GL_SCISSOR_BOX, scissor);
2874                         glScissor(cliprct.xmin, cliprct.ymin, BLI_RCT_SIZE_X(&cliprct), BLI_RCT_SIZE_Y(&cliprct));
2875                 }
2876                 else
2877                         return 0;
2878         }
2879
2880         glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
2881         glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
2882
2883         if (v3d->flag & V3D_DISPBGPICS)
2884                 view3d_draw_bgpic(scene, ar, v3d, FALSE, TRUE);
2885         else
2886                 fdrawcheckerboard(0, 0, ar->winx, ar->winy);
2887
2888         /* render result draw */
2889         type = rv3d->render_engine->type;
2890         type->view_draw(rv3d->render_engine, C);
2891
2892         if (v3d->flag & V3D_DISPBGPICS)
2893                 view3d_draw_bgpic(scene, ar, v3d, TRUE, TRUE);
2894
2895         if (draw_border) {
2896                 /* restore scissor as it was before */
2897                 glScissor(scissor[0], scissor[1], scissor[2], scissor[3]);
2898         }
2899
2900         return 1;
2901 }
2902
2903 static void view3d_main_area_draw_engine_info(RegionView3D *rv3d, ARegion *ar)
2904 {
2905         if (!rv3d->render_engine || !rv3d->render_engine->text)
2906                 return;
2907
2908         ED_region_info_draw(ar, rv3d->render_engine->text, 1, 0.25);
2909 }
2910
2911 /* warning: this function has duplicate drawing in ED_view3d_draw_offscreen() */
2912 static void view3d_main_area_draw_objects(const bContext *C, ARegion *ar, const char **grid_unit)
2913 {
2914         Scene *scene = CTX_data_scene(C);
2915         View3D *v3d = CTX_wm_view3d(C);
2916         RegionView3D *rv3d = CTX_wm_region_view3d(C);
2917         Base *base;
2918         float backcol[3];
2919         unsigned int lay_used;
2920
2921         /* shadow buffers, before we setup matrices */
2922         if (draw_glsl_material(scene, NULL, v3d, v3d->drawtype))
2923                 gpu_update_lamps_shadows(scene, v3d);
2924         
2925         /* reset default OpenGL lights if needed (i.e. after preferences have been altered) */
2926         if (rv3d->rflag & RV3D_GPULIGHT_UPDATE) {
2927                 rv3d->rflag &= ~RV3D_GPULIGHT_UPDATE;
2928                 GPU_default_lights();
2929         }
2930
2931         /* clear background */
2932         if ((v3d->flag2 & V3D_RENDER_OVERRIDE) && scene->world) {
2933                 if (scene->r.color_mgt_flag & R_COLOR_MANAGEMENT)
2934                         linearrgb_to_srgb_v3_v3(backcol, &scene->world->horr);
2935                 else
2936                         copy_v3_v3(backcol, &scene->world->horr);
2937                 glClearColor(backcol[0], backcol[1], backcol[2], 0.0);
2938         }
2939         else
2940                 UI_ThemeClearColor(TH_BACK);
2941
2942         glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
2943         
2944         /* setup view matrices */
2945         view3d_main_area_setup_view(scene, v3d, ar, NULL, NULL);
2946
2947         ED_region_draw_cb_draw(C, ar, REGION_DRAW_PRE_VIEW);
2948
2949         if (rv3d->rflag & RV3D_CLIPPING)
2950                 view3d_draw_clipping(rv3d);
2951         
2952         /* set zbuffer after we draw clipping region */
2953         if (v3d->drawtype > OB_WIRE) {
2954                 v3d->zbuf = TRUE;
2955                 glEnable(GL_DEPTH_TEST);
2956         }
2957         else
2958                 v3d->zbuf = FALSE;
2959
2960         /* enables anti-aliasing for 3D view drawing */
2961 #if 0
2962         if (!(U.gameflags & USER_DISABLE_AA))
2963                 glEnable(GL_MULTISAMPLE_ARB);
2964 #endif
2965
2966         /* needs to be done always, gridview is adjusted in drawgrid() now */
2967         rv3d->gridview = v3d->grid;
2968
2969         if ((rv3d->view == RV3D_VIEW_USER) || (rv3d->persp != RV3D_ORTHO)) {
2970                 if ((v3d->flag2 & V3D_RENDER_OVERRIDE) == 0) {
2971                         drawfloor(scene, v3d, grid_unit);
2972                 }
2973                 if (rv3d->persp == RV3D_CAMOB) {
2974                         if (scene->world) {
2975                                 if (scene->world->mode & WO_STARS) {
2976                                         RE_make_stars(NULL, scene, star_stuff_init_func, star_stuff_vertex_func,
2977                                                       star_stuff_term_func);
2978                                 }
2979                         }
2980                 }
2981         }
2982         else {
2983                 if ((v3d->flag2 & V3D_RENDER_OVERRIDE) == 0) {
2984                         ED_region_pixelspace(ar);
2985                         drawgrid(&scene->unit, ar, v3d, grid_unit);
2986                         /* XXX make function? replaces persp(1) */
2987                         glMatrixMode(GL_PROJECTION);
2988                         glLoadMatrixf(rv3d->winmat);
2989                         glMatrixMode(GL_MODELVIEW);
2990                         glLoadMatrixf(rv3d->viewmat);
2991                 }
2992         }
2993
2994         view3d_draw_bgpic_test(scene, ar, v3d, FALSE, TRUE);
2995
2996         if (rv3d->rflag & RV3D_CLIPPING)
2997                 ED_view3d_clipping_set(rv3d);
2998
2999         /* draw set first */
3000         if (scene->set) {
3001                 Scene *sce_iter;
3002                 for (SETLOOPER(scene->set, sce_iter, base)) {
3003                         
3004                         if (v3d->lay & base->lay) {
3005                                 
3006                                 UI_ThemeColorBlend(TH_WIRE, TH_BACK, 0.6f);
3007                                 draw_object(scene, ar, v3d, base, DRAW_CONSTCOLOR | DRAW_SCENESET);
3008                                 
3009                                 if (base->object->transflag & OB_DUPLI) {
3010                                         draw_dupli_objects_color(scene, ar, v3d, base, TH_WIRE);
3011                                 }
3012                         }
3013                 }
3014                 
3015                 /* Transp and X-ray afterdraw stuff for sets is done later */
3016         }
3017
3018         lay_used = 0;
3019
3020         /* then draw not selected and the duplis, but skip editmode object */
3021         for (base = scene->base.first; base; base = base->next) {
3022                 lay_used |= base->lay & ((1 << 20) - 1);
3023
3024                 if (v3d->lay & base->lay) {
3025                         
3026                         /* dupli drawing */
3027                         if (base->object->transflag & OB_DUPLI) {
3028                                 draw_dupli_objects(scene, ar, v3d, base);
3029                         }
3030                         if ((base->flag & SELECT) == 0) {
3031                                 if (base->object != scene->obedit)
3032                                         draw_object(scene, ar, v3d, base, 0);
3033                         }
3034                 }
3035         }
3036
3037         if (v3d->lay_used != lay_used) { /* happens when loading old files or loading with UI load */
3038                 /* find header and force tag redraw */
3039                 ScrArea *sa = CTX_wm_area(C);
3040                 ARegion *ar_header = BKE_area_find_region_type(sa, RGN_TYPE_HEADER);
3041                 ED_region_tag_redraw(ar_header); /* can be NULL */
3042                 v3d->lay_used = lay_used;
3043         }
3044
3045         /* draw selected and editmode */
3046         for (base = scene->base.first; base; base = base->next) {
3047                 if (v3d->lay & base->lay) {
3048                         if (base->object == scene->obedit || (base->flag & SELECT) )
3049                                 draw_object(scene, ar, v3d, base, 0);
3050                 }
3051         }
3052
3053 //      REEB_draw();
3054
3055         if ((v3d->flag2 & V3D_RENDER_OVERRIDE) == 0) {
3056                 /* must be before xray draw which clears the depth buffer */
3057                 if (v3d->zbuf) glDisable(GL_DEPTH_TEST);
3058                 draw_gpencil_view3d(scene, v3d, ar, 1);
3059                 if (v3d->zbuf) glEnable(GL_DEPTH_TEST);
3060         }
3061
3062         /* Transp and X-ray afterdraw stuff */
3063         if (v3d->afterdraw_transp.first) view3d_draw_transp(scene, ar, v3d);
3064         if (v3d->afterdraw_xray.first) view3d_draw_xray(scene, ar, v3d, 1);  /* clears zbuffer if it is used! */
3065         if (v3d->afterdraw_xraytransp.first) view3d_draw_xraytransp(scene, ar, v3d, 1);
3066         
3067         ED_region_draw_cb_draw(C, ar, REGION_DRAW_POST_VIEW);
3068
3069         if (rv3d->rflag & RV3D_CLIPPING)
3070                 ED_view3d_clipping_disable();
3071         
3072         /* important to do after clipping */
3073         view3d_draw_bgpic_test(scene, ar, v3d, TRUE, TRUE);
3074
3075         BIF_draw_manipulator(C);
3076
3077 #if 0
3078         /* Disable back anti-aliasing */
3079         if (!(U.gameflags & USER_DISABLE_AA))
3080                 glDisable(GL_MULTISAMPLE_ARB);
3081 #endif
3082
3083         if (v3d->zbuf) {
3084                 v3d->zbuf = FALSE;
3085                 glDisable(GL_DEPTH_TEST);
3086         }
3087
3088         if ((v3d->flag2 & V3D_RENDER_OVERRIDE) == 0) {
3089                 BDR_drawSketch(C);
3090         }
3091
3092         if ((U.ndof_flag & NDOF_SHOW_GUIDE) && (rv3d->viewlock != RV3D_LOCKED) && (rv3d->persp != RV3D_CAMOB))
3093                 /* TODO: draw something else (but not this) during fly mode */
3094                 draw_rotation_guide(rv3d);
3095
3096 }
3097
3098 static void view3d_main_area_draw_info(const bContext *C, ARegion *ar, const char *grid_unit)
3099 {
3100         wmWindowManager *wm = CTX_wm_manager(C);
3101         Scene *scene = CTX_data_scene(C);