79448ecf8754857896bd066c2e8df16888a868ce
[blender-staging.git] / source / blender / editors / space_view3d / view3d_draw.c
1 /**
2  * $Id:
3  *
4  * ***** BEGIN GPL LICENSE BLOCK *****
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License
8  * as published by the Free Software Foundation; either version 2
9  * of the License, or (at your option) any later version. 
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software Foundation,
18  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19  *
20  * The Original Code is Copyright (C) 2008 Blender Foundation.
21  * All rights reserved.
22  *
23  * 
24  * Contributor(s): Blender Foundation
25  *
26  * ***** END GPL LICENSE BLOCK *****
27  */
28
29 #include <string.h>
30 #include <stdio.h>
31 #include <math.h>
32
33 #include "DNA_action_types.h"
34 #include "DNA_armature_types.h"
35 #include "DNA_camera_types.h"
36 #include "DNA_customdata_types.h"
37 #include "DNA_group_types.h"
38 #include "DNA_key_types.h"
39 #include "DNA_lamp_types.h"
40 #include "DNA_object_types.h"
41 #include "DNA_space_types.h"
42 #include "DNA_scene_types.h"
43 #include "DNA_screen_types.h"
44 #include "DNA_userdef_types.h"
45 #include "DNA_view3d_types.h"
46 #include "DNA_world_types.h"
47
48 #include "MEM_guardedalloc.h"
49
50 #include "BLI_blenlib.h"
51 #include "BLI_math.h"
52 #include "BLI_rand.h"
53
54 #include "BKE_anim.h"
55 #include "BKE_context.h"
56 #include "BKE_customdata.h"
57 #include "BKE_image.h"
58 #include "BKE_ipo.h"
59 #include "BKE_key.h"
60 #include "BKE_object.h"
61 #include "BKE_global.h"
62 #include "BKE_paint.h"
63 #include "BKE_scene.h"
64 #include "BKE_screen.h"
65 #include "BKE_utildefines.h"
66 #include "BKE_unit.h"
67
68 #include "RE_pipeline.h"        // make_stars
69
70 #include "IMB_imbuf_types.h"
71 #include "IMB_imbuf.h"
72
73 #include "BIF_gl.h"
74 #include "BIF_glutil.h"
75
76 #include "WM_api.h"
77 #include "WM_types.h"
78 #include "BLF_api.h"
79
80 #include "ED_armature.h"
81 #include "ED_keyframing.h"
82 #include "ED_gpencil.h"
83 #include "ED_mesh.h"
84 #include "ED_screen.h"
85 #include "ED_space_api.h"
86 #include "ED_screen_types.h"
87 #include "ED_util.h"
88 #include "ED_transform.h"
89 #include "ED_types.h"
90
91 #include "UI_interface.h"
92 #include "UI_interface_icons.h"
93 #include "UI_resources.h"
94 #include "UI_view2d.h"
95
96 #include "GPU_draw.h"
97 #include "GPU_material.h"
98 #include "GPU_extensions.h"
99
100 #include "view3d_intern.h"      // own include
101
102
103
104 static void star_stuff_init_func(void)
105 {
106         cpack(-1);
107         glPointSize(1.0);
108         glBegin(GL_POINTS);
109 }
110 static void star_stuff_vertex_func(float* i)
111 {
112         glVertex3fv(i);
113 }
114 static void star_stuff_term_func(void)
115 {
116         glEnd();
117 }
118
119 void circf(float x, float y, float rad)
120 {
121         GLUquadricObj *qobj = gluNewQuadric(); 
122         
123         gluQuadricDrawStyle(qobj, GLU_FILL); 
124         
125         glPushMatrix(); 
126         
127         glTranslatef(x,  y, 0.); 
128         
129         gluDisk( qobj, 0.0,  rad, 32, 1); 
130         
131         glPopMatrix(); 
132         
133         gluDeleteQuadric(qobj);
134 }
135
136 void circ(float x, float y, float rad)
137 {
138         GLUquadricObj *qobj = gluNewQuadric(); 
139         
140         gluQuadricDrawStyle(qobj, GLU_SILHOUETTE); 
141         
142         glPushMatrix(); 
143         
144         glTranslatef(x,  y, 0.); 
145         
146         gluDisk( qobj, 0.0,  rad, 32, 1); 
147         
148         glPopMatrix(); 
149         
150         gluDeleteQuadric(qobj);
151 }
152
153
154 /* ********* custom clipping *********** */
155
156 static void view3d_draw_clipping(RegionView3D *rv3d)
157 {
158         BoundBox *bb= rv3d->clipbb;
159         
160         if(bb) {
161                 UI_ThemeColorShade(TH_BACK, -8);
162                 
163                 glBegin(GL_QUADS);
164                 
165                 glVertex3fv(bb->vec[0]); glVertex3fv(bb->vec[1]); glVertex3fv(bb->vec[2]); glVertex3fv(bb->vec[3]);
166                 glVertex3fv(bb->vec[0]); glVertex3fv(bb->vec[4]); glVertex3fv(bb->vec[5]); glVertex3fv(bb->vec[1]);
167                 glVertex3fv(bb->vec[4]); glVertex3fv(bb->vec[7]); glVertex3fv(bb->vec[6]); glVertex3fv(bb->vec[5]);
168                 glVertex3fv(bb->vec[7]); glVertex3fv(bb->vec[3]); glVertex3fv(bb->vec[2]); glVertex3fv(bb->vec[6]);
169                 glVertex3fv(bb->vec[1]); glVertex3fv(bb->vec[5]); glVertex3fv(bb->vec[6]); glVertex3fv(bb->vec[2]);
170                 glVertex3fv(bb->vec[7]); glVertex3fv(bb->vec[4]); glVertex3fv(bb->vec[0]); glVertex3fv(bb->vec[3]);
171                 
172                 glEnd();
173         }
174 }
175
176 void view3d_set_clipping(RegionView3D *rv3d)
177 {
178         double plane[4];
179         int a, tot=4;
180         
181         if(rv3d->viewlock) tot= 6;
182         
183         for(a=0; a<tot; a++) {
184                 QUATCOPY(plane, rv3d->clip[a]);
185                 glClipPlane(GL_CLIP_PLANE0+a, plane);
186                 glEnable(GL_CLIP_PLANE0+a);
187         }
188 }
189
190 void view3d_clr_clipping(void)
191 {
192         int a;
193         
194         for(a=0; a<6; a++) {
195                 glDisable(GL_CLIP_PLANE0+a);
196         }
197 }
198
199 static int test_clipping(float *vec, float clip[][4])
200 {
201         float view[3];
202         VECCOPY(view, vec);
203         
204         if(0.0f < clip[0][3] + INPR(view, clip[0]))
205                 if(0.0f < clip[1][3] + INPR(view, clip[1]))
206                         if(0.0f < clip[2][3] + INPR(view, clip[2]))
207                                 if(0.0f < clip[3][3] + INPR(view, clip[3]))
208                                         return 0;
209
210         return 1;
211 }
212
213 /* for 'local' ED_view3d_local_clipping must run first
214  * then all comparisons can be done in localspace */
215 int view3d_test_clipping(RegionView3D *rv3d, float *vec, int local)
216 {
217         return test_clipping(vec, local ? rv3d->clip_local : rv3d->clip);
218 }
219
220 /* ********* end custom clipping *********** */
221
222
223 static void drawgrid_draw(ARegion *ar, float wx, float wy, float x, float y, float dx)
224 {
225         float fx, fy;
226         
227         x+= (wx); 
228         y+= (wy);
229         fx= x/dx;
230         fx= x-dx*floor(fx);
231         
232         while(fx< ar->winx) {
233                 fdrawline(fx,  0.0,  fx,  (float)ar->winy); 
234                 fx+= dx; 
235         }
236
237         fy= y/dx;
238         fy= y-dx*floor(fy);
239         
240
241         while(fy< ar->winy) {
242                 fdrawline(0.0,  fy,  (float)ar->winx,  fy); 
243                 fy+= dx;
244         }
245
246 }
247
248 #define GRID_MIN_PX 6.0f
249
250 static void drawgrid(UnitSettings *unit, ARegion *ar, View3D *v3d, char **grid_unit)
251 {
252         /* extern short bgpicmode; */
253         RegionView3D *rv3d= ar->regiondata;
254         float wx, wy, x, y, fw, fx, fy, dx;
255         float vec4[4];
256         char col[3], col2[3];
257         
258         *grid_unit= NULL;
259
260         vec4[0]=vec4[1]=vec4[2]=0.0; 
261         vec4[3]= 1.0;
262         mul_m4_v4(rv3d->persmat, vec4);
263         fx= vec4[0]; 
264         fy= vec4[1]; 
265         fw= vec4[3];
266
267         wx= (ar->winx/2.0);     /* because of rounding errors, grid at wrong location */
268         wy= (ar->winy/2.0);
269
270         x= (wx)*fx/fw;
271         y= (wy)*fy/fw;
272
273         vec4[0]=vec4[1]= (unit->system) ? 1.0 : v3d->grid;
274
275         vec4[2]= 0.0;
276         vec4[3]= 1.0;
277         mul_m4_v4(rv3d->persmat, vec4);
278         fx= vec4[0]; 
279         fy= vec4[1]; 
280         fw= vec4[3];
281
282         dx= fabs(x-(wx)*fx/fw);
283         if(dx==0) dx= fabs(y-(wy)*fy/fw);
284         
285         glDepthMask(0);         // disable write in zbuffer
286
287         /* check zoom out */
288         UI_ThemeColor(TH_GRID);
289         
290         if(unit->system) {
291                 /* Use GRID_MIN_PX*2 for units because very very small grid
292                  * items are less useful when dealing with units */
293                 void *usys;
294                 int len, i;
295                 double scalar;
296                 float dx_scalar;
297                 float blend_fac;
298
299                 bUnit_GetSystem(&usys, &len, unit->system, B_UNIT_LENGTH);
300
301                 if(usys) {
302                         i= len;
303                         while(i--) {
304                                 scalar= bUnit_GetScaler(usys, i);
305
306                                 dx_scalar = dx * scalar * unit->scale_length;
307                                 if (dx_scalar < (GRID_MIN_PX*2))
308                                         continue;
309
310                                 /* Store the smallest drawn grid size units name so users know how big each grid cell is */
311                                 if(*grid_unit==NULL) {
312                                         *grid_unit= bUnit_GetNameDisplay(usys, i);
313                                         rv3d->gridview= (scalar * unit->scale_length);
314                                 }
315                                 blend_fac= 1-((GRID_MIN_PX*2)/dx_scalar);
316
317                                 /* tweak to have the fade a bit nicer */
318                                 blend_fac= (blend_fac * blend_fac) * 2.0f;
319                                 CLAMP(blend_fac, 0.3f, 1.0f);
320
321
322                                 UI_ThemeColorBlend(TH_BACK, TH_GRID, blend_fac);
323
324                                 drawgrid_draw(ar, wx, wy, x, y, dx_scalar);
325                         }
326                 }
327         }
328         else {
329                 short sublines = v3d->gridsubdiv;
330
331                 if(dx<GRID_MIN_PX) {
332                         rv3d->gridview*= sublines;
333                         dx*= sublines;
334                         
335                         if(dx<GRID_MIN_PX) {
336                                 rv3d->gridview*= sublines;
337                                 dx*= sublines;
338
339                                 if(dx<GRID_MIN_PX) {
340                                         rv3d->gridview*= sublines;
341                                         dx*=sublines;
342                                         if(dx<GRID_MIN_PX);
343                                         else {
344                                                 UI_ThemeColor(TH_GRID);
345                                                 drawgrid_draw(ar, wx, wy, x, y, dx);
346                                         }
347                                 }
348                                 else {  // start blending out
349                                         UI_ThemeColorBlend(TH_BACK, TH_GRID, dx/(GRID_MIN_PX*6));
350                                         drawgrid_draw(ar, wx, wy, x, y, dx);
351
352                                         UI_ThemeColor(TH_GRID);
353                                         drawgrid_draw(ar, wx, wy, x, y, sublines*dx);
354                                 }
355                         }
356                         else {  // start blending out (GRID_MIN_PX < dx < (GRID_MIN_PX*10))
357                                 UI_ThemeColorBlend(TH_BACK, TH_GRID, dx/(GRID_MIN_PX*6));
358                                 drawgrid_draw(ar, wx, wy, x, y, dx);
359
360                                 UI_ThemeColor(TH_GRID);
361                                 drawgrid_draw(ar, wx, wy, x, y, sublines*dx);
362                         }
363                 }
364                 else {
365                         if(dx>(GRID_MIN_PX*10)) {               // start blending in
366                                 rv3d->gridview/= sublines;
367                                 dx/= sublines;
368                                 if(dx>(GRID_MIN_PX*10)) {               // start blending in
369                                         rv3d->gridview/= sublines;
370                                         dx/= sublines;
371                                         if(dx>(GRID_MIN_PX*10)) {
372                                                 UI_ThemeColor(TH_GRID);
373                                                 drawgrid_draw(ar, wx, wy, x, y, dx);
374                                         }
375                                         else {
376                                                 UI_ThemeColorBlend(TH_BACK, TH_GRID, dx/(GRID_MIN_PX*6));
377                                                 drawgrid_draw(ar, wx, wy, x, y, dx);
378                                                 UI_ThemeColor(TH_GRID);
379                                                 drawgrid_draw(ar, wx, wy, x, y, dx*sublines);
380                                         }
381                                 }
382                                 else {
383                                         UI_ThemeColorBlend(TH_BACK, TH_GRID, dx/(GRID_MIN_PX*6));
384                                         drawgrid_draw(ar, wx, wy, x, y, dx);
385                                         UI_ThemeColor(TH_GRID);
386                                         drawgrid_draw(ar, wx, wy, x, y, dx*sublines);
387                                 }
388                         }
389                         else {
390                                 UI_ThemeColorBlend(TH_BACK, TH_GRID, dx/(GRID_MIN_PX*6));
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         }
397
398
399         x+= (wx); 
400         y+= (wy);
401         UI_GetThemeColor3ubv(TH_GRID, col);
402
403         setlinestyle(0);
404         
405         /* center cross */
406         if( ELEM(rv3d->view, RV3D_VIEW_RIGHT, RV3D_VIEW_LEFT)) 
407                 UI_make_axis_color(col, col2, 'y');
408         else UI_make_axis_color(col, col2, 'x');
409         glColor3ubv((GLubyte *)col2);
410         
411         fdrawline(0.0,  y,  (float)ar->winx,  y); 
412         
413         if( ELEM(rv3d->view, RV3D_VIEW_TOP, RV3D_VIEW_BOTTOM)) 
414                 UI_make_axis_color(col, col2, 'y');
415         else UI_make_axis_color(col, col2, 'z');
416         glColor3ubv((GLubyte *)col2);
417
418         fdrawline(x, 0.0, x, (float)ar->winy); 
419
420         glDepthMask(1);         // enable write in zbuffer
421 }
422 #undef GRID_MIN_PX
423
424 static void drawfloor(Scene *scene, View3D *v3d)
425 {
426         float vert[3], grid;
427         int a, gridlines, emphasise;
428         char col[3], col2[3];
429         short draw_line = 0;
430         
431         vert[2]= 0.0;
432         
433         if(v3d->gridlines<3) return;
434         
435         if(v3d->zbuf && scene->obedit) glDepthMask(0);  // for zbuffer-select
436         
437         gridlines= v3d->gridlines/2;
438         grid= gridlines*v3d->grid;
439         
440         UI_GetThemeColor3ubv(TH_GRID, col);
441         UI_GetThemeColor3ubv(TH_BACK, col2);
442         
443         /* emphasise division lines lighter instead of darker, if background is darker than grid */
444         if ( ((col[0]+col[1]+col[2])/3+10) > (col2[0]+col2[1]+col2[2])/3 )
445                 emphasise = 20;
446         else
447                 emphasise = -10;
448         
449         /* draw the Y axis and/or grid lines */
450         for(a= -gridlines;a<=gridlines;a++) {
451                 if(a==0) {
452                         /* check for the 'show Y axis' preference */
453                         if (v3d->gridflag & V3D_SHOW_Y) { 
454                                 UI_make_axis_color(col, col2, 'y');
455                                 glColor3ubv((GLubyte *)col2);
456                                 
457                                 draw_line = 1;
458                         } else if (v3d->gridflag & V3D_SHOW_FLOOR) {
459                                 UI_ThemeColorShade(TH_GRID, emphasise);
460                         } else {
461                                 draw_line = 0;
462                         }
463                 } else {
464                         /* check for the 'show grid floor' preference */
465                         if (v3d->gridflag & V3D_SHOW_FLOOR) {
466                                 if( (a % 10)==0) {
467                                         UI_ThemeColorShade(TH_GRID, emphasise);
468                                 }
469                                 else UI_ThemeColorShade(TH_GRID, 10);
470                                 
471                                 draw_line = 1;
472                         } else {
473                                 draw_line = 0;
474                         }
475                 }
476                 
477                 if (draw_line) {
478                         glBegin(GL_LINE_STRIP);
479                 vert[0]= a*v3d->grid;
480                 vert[1]= grid;
481                 glVertex3fv(vert);
482                 vert[1]= -grid;
483                 glVertex3fv(vert);
484                         glEnd();
485                 }
486         }
487         
488         /* draw the X axis and/or grid lines */
489         for(a= -gridlines;a<=gridlines;a++) {
490                 if(a==0) {
491                         /* check for the 'show X axis' preference */
492                         if (v3d->gridflag & V3D_SHOW_X) { 
493                                 UI_make_axis_color(col, col2, 'x');
494                                 glColor3ubv((GLubyte *)col2);
495                                 
496                                 draw_line = 1;
497                         } else if (v3d->gridflag & V3D_SHOW_FLOOR) {
498                                 UI_ThemeColorShade(TH_GRID, emphasise);
499                         } else {
500                                 draw_line = 0;
501                         }
502                 } else {
503                         /* check for the 'show grid floor' preference */
504                         if (v3d->gridflag & V3D_SHOW_FLOOR) {
505                                 if( (a % 10)==0) {
506                                         UI_ThemeColorShade(TH_GRID, emphasise);
507                                 }
508                                 else UI_ThemeColorShade(TH_GRID, 10);
509                                 
510                                 draw_line = 1;
511                         } else {
512                                 draw_line = 0;
513                         }
514                 }
515                 
516                 if (draw_line) {
517                         glBegin(GL_LINE_STRIP);
518                 vert[1]= a*v3d->grid;
519                 vert[0]= grid;
520                 glVertex3fv(vert );
521                 vert[0]= -grid;
522                 glVertex3fv(vert);
523                         glEnd();
524                 }
525         }
526         
527         /* draw the Z axis line */      
528         /* check for the 'show Z axis' preference */
529         if (v3d->gridflag & V3D_SHOW_Z) {
530                 UI_make_axis_color(col, col2, 'z');
531                 glColor3ubv((GLubyte *)col2);
532                 
533                 glBegin(GL_LINE_STRIP);
534                 vert[0]= 0;
535                 vert[1]= 0;
536                 vert[2]= grid;
537                 glVertex3fv(vert );
538                 vert[2]= -grid;
539                 glVertex3fv(vert);
540                 glEnd();
541         }
542         
543         if(v3d->zbuf && scene->obedit) glDepthMask(1);  
544         
545 }
546
547 static void drawcursor(Scene *scene, ARegion *ar, View3D *v3d)
548 {
549         short mx,my,co[2];
550         int flag;
551         
552         /* we dont want the clipping for cursor */
553         flag= v3d->flag;
554         v3d->flag= 0;
555         project_short(ar, give_cursor(scene, v3d), co);
556         v3d->flag= flag;
557         
558         mx = co[0];
559         my = co[1];
560         
561         if(mx!=IS_CLIPPED) {
562                 setlinestyle(0); 
563                 cpack(0xFF);
564                 circ((float)mx, (float)my, 10.0);
565                 setlinestyle(4); 
566                 cpack(0xFFFFFF);
567                 circ((float)mx, (float)my, 10.0);
568                 setlinestyle(0);
569                 cpack(0x0);
570                 
571                 sdrawline(mx-20, my, mx-5, my);
572                 sdrawline(mx+5, my, mx+20, my);
573                 sdrawline(mx, my-20, mx, my-5);
574                 sdrawline(mx, my+5, mx, my+20);
575         }
576 }
577
578 /* Draw a live substitute of the view icon, which is always shown */
579 static void draw_view_axis(RegionView3D *rv3d)
580 {
581         const float k = U.rvisize;   /* axis size */
582         const float toll = 0.5;      /* used to see when view is quasi-orthogonal */
583         const float start = k + 1.0; /* axis center in screen coordinates, x=y */
584         float ydisp = 0.0;          /* vertical displacement to allow obj info text */
585         
586         /* rvibright ranges approx. from original axis icon color to gizmo color */
587         float bright = U.rvibright / 15.0f;
588         
589         unsigned char col[3];
590         unsigned char gridcol[3];
591         float colf[3];
592         
593         float vec[4];
594         float dx, dy;
595         float h, s, v;
596         
597         /* thickness of lines is proportional to k */
598         /*      (log(k)-1) gives a more suitable thickness, but fps decreased by about 3 fps */
599         glLineWidth(k / 10);
600         //glLineWidth(log(k)-1); // a bit slow
601         
602         UI_GetThemeColor3ubv(TH_GRID, (char *)gridcol);
603         
604         /* X */
605         vec[0] = vec[3] = 1;
606         vec[1] = vec[2] = 0;
607         mul_qt_v3(rv3d->viewquat, vec);
608         
609         UI_make_axis_color((char *)gridcol, (char *)col, 'x');
610         rgb_to_hsv(col[0]/255.0f, col[1]/255.0f, col[2]/255.0f, &h, &s, &v);
611         s = s<0.5 ? s+0.5 : 1.0;
612         v = 0.3;
613         v = (v<1.0-(bright) ? v+bright : 1.0);
614         hsv_to_rgb(h, s, v, colf, colf+1, colf+2);
615         glColor3fv(colf);
616         
617         dx = vec[0] * k;
618         dy = vec[1] * k;
619         fdrawline(start, start + ydisp, start + dx, start + dy + ydisp);
620         if (fabs(dx) > toll || fabs(dy) > toll) {
621                 BLF_draw_default(start + dx + 2, start + dy + ydisp + 2, 0.0f, "x");
622         }
623         
624         /* Y */
625         vec[1] = vec[3] = 1;
626         vec[0] = vec[2] = 0;
627         mul_qt_v3(rv3d->viewquat, vec);
628         
629         UI_make_axis_color((char *)gridcol, (char *)col, 'y');
630         rgb_to_hsv(col[0]/255.0f, col[1]/255.0f, col[2]/255.0f, &h, &s, &v);
631         s = s<0.5 ? s+0.5 : 1.0;
632         v = 0.3;
633         v = (v<1.0-(bright) ? v+bright : 1.0);
634         hsv_to_rgb(h, s, v, colf, colf+1, colf+2);
635         glColor3fv(colf);
636         
637         dx = vec[0] * k;
638         dy = vec[1] * k;
639         fdrawline(start, start + ydisp, start + dx, start + dy + ydisp);
640         if (fabs(dx) > toll || fabs(dy) > toll) {
641                 BLF_draw_default(start + dx + 2, start + dy + ydisp + 2, 0.0f, "y");
642         }
643         
644         /* Z */
645         vec[2] = vec[3] = 1;
646         vec[1] = vec[0] = 0;
647         mul_qt_v3(rv3d->viewquat, vec);
648         
649         UI_make_axis_color((char *)gridcol, (char *)col, 'z');
650         rgb_to_hsv(col[0]/255.0f, col[1]/255.0f, col[2]/255.0f, &h, &s, &v);
651         s = s<0.5 ? s+0.5 : 1.0;
652         v = 0.5;
653         v = (v<1.0-(bright) ? v+bright : 1.0);
654         hsv_to_rgb(h, s, v, colf, colf+1, colf+2);
655         glColor3fv(colf);
656         
657         dx = vec[0] * k;
658         dy = vec[1] * k;
659         fdrawline(start, start + ydisp, start + dx, start + dy + ydisp);
660         if (fabs(dx) > toll || fabs(dy) > toll) {
661                 BLF_draw_default(start + dx + 2, start + dy + ydisp + 2, 0.0f, "z");
662         }
663         
664         /* restore line-width */
665         glLineWidth(1.0);
666 }
667
668
669 static void draw_view_icon(RegionView3D *rv3d)
670 {
671         BIFIconID icon;
672         
673         if( ELEM(rv3d->view, RV3D_VIEW_TOP, RV3D_VIEW_BOTTOM)) 
674                 icon= ICON_AXIS_TOP;
675         else if( ELEM(rv3d->view, RV3D_VIEW_FRONT, RV3D_VIEW_BACK)) 
676                 icon= ICON_AXIS_FRONT;
677         else if( ELEM(rv3d->view, RV3D_VIEW_RIGHT, RV3D_VIEW_LEFT)) 
678                 icon= ICON_AXIS_SIDE;
679         else return ;
680         
681         glEnable(GL_BLEND);
682         glBlendFunc(GL_SRC_ALPHA,  GL_ONE_MINUS_SRC_ALPHA); 
683         
684         UI_icon_draw(5.0, 5.0, icon);
685         
686         glDisable(GL_BLEND);
687 }
688
689 static char *view3d_get_name(View3D *v3d, RegionView3D *rv3d)
690 {
691         char *name = NULL;
692         
693         switch (rv3d->view) {
694                 case RV3D_VIEW_FRONT:
695                         if (rv3d->persp == RV3D_ORTHO) name = "Front Ortho";
696                         else name = "Front Persp";
697                         break;
698                 case RV3D_VIEW_BACK:
699                         if (rv3d->persp == RV3D_ORTHO) name = "Back Ortho";
700                         else name = "Back Persp";
701                         break;
702                 case RV3D_VIEW_TOP:
703                         if (rv3d->persp == RV3D_ORTHO) name = "Top Ortho";
704                         else name = "Top Persp";
705                         break;
706                 case RV3D_VIEW_BOTTOM:
707                         if (rv3d->persp == RV3D_ORTHO) name = "Bottom Ortho";
708                         else name = "Bottom Persp";
709                         break;
710                 case RV3D_VIEW_RIGHT:
711                         if (rv3d->persp == RV3D_ORTHO) name = "Right Ortho";
712                         else name = "Right Persp";
713                         break;
714                 case RV3D_VIEW_LEFT:
715                         if (rv3d->persp == RV3D_ORTHO) name = "Left Ortho";
716                         else name = "Left Persp";
717                         break;
718                         
719                 default:
720                         if (rv3d->persp==RV3D_CAMOB) {
721                                 if ((v3d->camera) && (v3d->camera->type == OB_CAMERA)) {
722                                         Camera *cam;
723                                         cam = v3d->camera->data;
724                                         name = (cam->type != CAM_ORTHO) ? "Camera Persp" : "Camera Ortho";
725                                 } else {
726                                         name = "Object as Camera";
727                                 }
728                         } else { 
729                                 name = (rv3d->persp == RV3D_ORTHO) ? "User Ortho" : "User Persp";
730                         }
731                         break;
732         }
733         
734         return name;
735 }
736
737 static void draw_viewport_name(ARegion *ar, View3D *v3d)
738 {
739         RegionView3D *rv3d= ar->regiondata;
740         char *name = view3d_get_name(v3d, rv3d);
741         char *printable = NULL;
742         
743         if (v3d->localvd) {
744                 printable = MEM_mallocN(strlen(name) + strlen(" (Local)_"), "viewport_name"); /* '_' gives space for '\0' */
745                                                                                                  strcpy(printable, name);
746                                                                                                  strcat(printable, " (Local)");
747         } else {
748                 printable = name;
749         }
750
751         if (printable) {
752                 UI_ThemeColor(TH_TEXT_HI);
753                 BLF_draw_default(22,  ar->winy-17, 0.0f, printable);
754         }
755
756         if (v3d->localvd) {
757                 MEM_freeN(printable);
758         }
759 }
760
761 /* draw info beside axes in bottom left-corner: 
762 *       framenum, object name, bone name (if available), marker name (if available)
763 */
764 static void draw_selected_name(Scene *scene, Object *ob, View3D *v3d)
765 {
766         char info[256], *markern;
767         short offset=30;
768         
769         /* get name of marker on current frame (if available) */
770         markern= scene_find_marker_name(scene, CFRA);
771         
772         /* check if there is an object */
773         if(ob) {
774                 /* name(s) to display depends on type of object */
775                 if(ob->type==OB_ARMATURE) {
776                         bArmature *arm= ob->data;
777                         char *name= NULL;
778                         
779                         /* show name of active bone too (if possible) */
780                         if(arm->edbo) {
781
782                                 if(arm->act_edbone)
783                                         name= ((EditBone *)arm->act_edbone)->name;
784
785                         }
786                         else if(ob->mode & OB_MODE_POSE) {
787                                 if(arm->act_bone) {
788
789                                         if(arm->act_bone->layer & arm->layer)
790                                                 name= arm->act_bone->name;
791
792                                 }
793                         }
794                         if(name && markern)
795                                 sprintf(info, "(%d) %s %s <%s>", CFRA, ob->id.name+2, name, markern);
796                         else if(name)
797                                 sprintf(info, "(%d) %s %s", CFRA, ob->id.name+2, name);
798                         else
799                                 sprintf(info, "(%d) %s", CFRA, ob->id.name+2);
800                 }
801                 else if(ELEM3(ob->type, OB_MESH, OB_LATTICE, OB_CURVE)) {
802                         Key *key= NULL;
803                         KeyBlock *kb = NULL;
804                         char shapes[75];
805                         
806                         /* try to display active shapekey too */
807                         shapes[0] = 0;
808                         key = ob_get_key(ob);
809                         if(key){
810                                 kb = BLI_findlink(&key->block, ob->shapenr-1);
811                                 if(kb){
812                                         sprintf(shapes, ": %s ", kb->name);             
813                                         if(ob->shapeflag == OB_SHAPE_LOCK){
814                                                 strcat(shapes, " (Pinned)");
815                                         }
816                                 }
817                         }
818                         
819                         if(markern)
820                                 sprintf(info, "(%d) %s %s <%s>", CFRA, ob->id.name+2, shapes, markern);
821                         else
822                                 sprintf(info, "(%d) %s %s", CFRA, ob->id.name+2, shapes);
823                 }
824                 else {
825                         /* standard object */
826                         if (markern)
827                                 sprintf(info, "(%d) %s <%s>", CFRA, ob->id.name+2, markern);
828                         else
829                                 sprintf(info, "(%d) %s", CFRA, ob->id.name+2);
830                 }
831                 
832                 /* colour depends on whether there is a keyframe */
833                 if (id_frame_has_keyframe((ID *)ob, /*frame_to_float(scene, CFRA)*/(float)(CFRA), v3d->keyflags))
834                         UI_ThemeColor(TH_VERTEX_SELECT);
835                 else
836                         UI_ThemeColor(TH_TEXT_HI);
837         }
838         else {
839                 /* no object */
840                 if (markern)
841                         sprintf(info, "(%d) <%s>", CFRA, markern);
842                 else
843                         sprintf(info, "(%d)", CFRA);
844                 
845                 /* colour is always white */
846                 UI_ThemeColor(TH_TEXT_HI);
847         }
848         
849         if (U.uiflag & USER_SHOW_ROTVIEWICON)
850                 offset = 14 + (U.rvisize * 2);
851
852         BLF_draw_default(offset,  10, 0.0f, info);
853 }
854
855 static void view3d_get_viewborder_size(Scene *scene, ARegion *ar, float size_r[2])
856 {
857         float winmax= MAX2(ar->winx, ar->winy);
858         float aspect= (scene->r.xsch*scene->r.xasp) / (scene->r.ysch*scene->r.yasp);
859         
860         if(aspect>1.0) {
861                 size_r[0]= winmax;
862                 size_r[1]= winmax/aspect;
863         } else {
864                 size_r[0]= winmax*aspect;
865                 size_r[1]= winmax;
866         }
867 }
868
869 void calc_viewborder(Scene *scene, ARegion *ar, View3D *v3d, rctf *viewborder_r)
870 {
871         RegionView3D *rv3d= ar->regiondata;
872         float zoomfac, size[2];
873         float dx= 0.0f, dy= 0.0f;
874         
875         view3d_get_viewborder_size(scene, ar, size);
876         
877         /* magic zoom calculation, no idea what
878                 * it signifies, if you find out, tell me! -zr
879                 */
880         /* simple, its magic dude!
881                 * well, to be honest, this gives a natural feeling zooming
882                 * with multiple keypad presses (ton)
883                 */
884         
885         zoomfac= (M_SQRT2 + rv3d->camzoom/50.0);
886         zoomfac= (zoomfac*zoomfac)*0.25;
887         
888         size[0]= size[0]*zoomfac;
889         size[1]= size[1]*zoomfac;
890         
891         /* center in window */
892         viewborder_r->xmin= 0.5*ar->winx - 0.5*size[0];
893         viewborder_r->ymin= 0.5*ar->winy - 0.5*size[1];
894         viewborder_r->xmax= viewborder_r->xmin + size[0];
895         viewborder_r->ymax= viewborder_r->ymin + size[1];
896         
897         dx= ar->winx*rv3d->camdx*zoomfac*2.0f;
898         dy= ar->winy*rv3d->camdy*zoomfac*2.0f;
899         
900         /* apply offset */
901         viewborder_r->xmin-= dx;
902         viewborder_r->ymin-= dy;
903         viewborder_r->xmax-= dx;
904         viewborder_r->ymax-= dy;
905         
906         if(v3d->camera && v3d->camera->type==OB_CAMERA) {
907                 Camera *cam= v3d->camera->data;
908                 float w = viewborder_r->xmax - viewborder_r->xmin;
909                 float h = viewborder_r->ymax - viewborder_r->ymin;
910                 float side = MAX2(w, h);
911                 
912                 viewborder_r->xmin+= cam->shiftx*side;
913                 viewborder_r->xmax+= cam->shiftx*side;
914                 viewborder_r->ymin+= cam->shifty*side;
915                 viewborder_r->ymax+= cam->shifty*side;
916         }
917 }
918
919 void view3d_set_1_to_1_viewborder(Scene *scene, ARegion *ar)
920 {
921         RegionView3D *rv3d= ar->regiondata;
922         float size[2];
923         int im_width= (scene->r.size*scene->r.xsch)/100;
924         
925         view3d_get_viewborder_size(scene, ar, size);
926         
927         rv3d->camzoom= (sqrt(4.0*im_width/size[0]) - M_SQRT2)*50.0;
928         rv3d->camzoom= CLAMPIS(rv3d->camzoom, -30, 300);
929 }
930
931
932 static void drawviewborder_flymode(ARegion *ar) 
933 {
934         /* draws 4 edge brackets that frame the safe area where the
935         mouse can move during fly mode without spinning the view */
936         float x1, x2, y1, y2;
937         
938         x1= 0.45*(float)ar->winx;
939         y1= 0.45*(float)ar->winy;
940         x2= 0.55*(float)ar->winx;
941         y2= 0.55*(float)ar->winy;
942         cpack(0);
943         
944         
945         glBegin(GL_LINES);
946         /* bottom left */
947         glVertex2f(x1,y1); 
948         glVertex2f(x1,y1+5);
949         
950         glVertex2f(x1,y1); 
951         glVertex2f(x1+5,y1);
952         
953         /* top right */
954         glVertex2f(x2,y2); 
955         glVertex2f(x2,y2-5);
956         
957         glVertex2f(x2,y2); 
958         glVertex2f(x2-5,y2);
959         
960         /* top left */
961         glVertex2f(x1,y2); 
962         glVertex2f(x1,y2-5);
963         
964         glVertex2f(x1,y2); 
965         glVertex2f(x1+5,y2);
966         
967         /* bottom right */
968         glVertex2f(x2,y1); 
969         glVertex2f(x2,y1+5);
970         
971         glVertex2f(x2,y1); 
972         glVertex2f(x2-5,y1);
973         glEnd();        
974 }
975
976
977 static void drawviewborder(Scene *scene, ARegion *ar, View3D *v3d)
978 {
979         extern void gl_round_box(int mode, float minx, float miny, float maxx, float maxy, float rad);          // interface_panel.c
980         float fac, a;
981         float x1, x2, y1, y2;
982         float x3, y3, x4, y4;
983         rctf viewborder;
984         Camera *ca= NULL;
985         
986         if(v3d->camera==NULL)
987                 return;
988         if(v3d->camera->type==OB_CAMERA)
989                 ca = v3d->camera->data;
990         
991         calc_viewborder(scene, ar, v3d, &viewborder);
992         x1= viewborder.xmin;
993         y1= viewborder.ymin;
994         x2= viewborder.xmax;
995         y2= viewborder.ymax;
996         
997         /* passepartout, specified in camera edit buttons */
998         if (ca && (ca->flag & CAM_SHOWPASSEPARTOUT) && ca->passepartalpha > 0.000001) {
999                 if (ca->passepartalpha == 1.0) {
1000                         glColor3f(0, 0, 0);
1001                 } else {
1002                         glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA );
1003                         glEnable(GL_BLEND);
1004                         glColor4f(0, 0, 0, ca->passepartalpha);
1005                 }
1006                 if (x1 > 0.0)
1007                         glRectf(0.0, (float)ar->winy, x1, 0.0);
1008                 if (x2 < (float)ar->winx)
1009                         glRectf(x2, (float)ar->winy, (float)ar->winx, 0.0);
1010                 if (y2 < (float)ar->winy)
1011                         glRectf(x1, (float)ar->winy, x2, y2);
1012                 if (y2 > 0.0) 
1013                         glRectf(x1, y1, x2, 0.0);
1014                 
1015                 glDisable(GL_BLEND);
1016         }
1017         
1018         /* edge */
1019         glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); 
1020         
1021         setlinestyle(0);
1022         UI_ThemeColor(TH_BACK);
1023         glRectf(x1, y1, x2, y2);
1024         
1025         setlinestyle(3);
1026         UI_ThemeColor(TH_WIRE);
1027         glRectf(x1, y1, x2, y2);
1028         
1029         /* border */
1030         if(scene->r.mode & R_BORDER) {
1031                 
1032                 cpack(0);
1033                 x3= x1+ scene->r.border.xmin*(x2-x1);
1034                 y3= y1+ scene->r.border.ymin*(y2-y1);
1035                 x4= x1+ scene->r.border.xmax*(x2-x1);
1036                 y4= y1+ scene->r.border.ymax*(y2-y1);
1037                 
1038                 cpack(0x4040FF);
1039                 glRectf(x3,  y3,  x4,  y4); 
1040         }
1041         
1042         /* safety border */
1043         if (ca && (ca->flag & CAM_SHOWTITLESAFE)) {
1044                 fac= 0.1;
1045                 
1046                 a= fac*(x2-x1);
1047                 x1+= a; 
1048                 x2-= a;
1049                 
1050                 a= fac*(y2-y1);
1051                 y1+= a;
1052                 y2-= a;
1053                 
1054                 UI_ThemeColorBlendShade(TH_WIRE, TH_BACK, 0.25, 0);
1055                 
1056                 uiSetRoundBox(15);
1057                 gl_round_box(GL_LINE_LOOP, x1, y1, x2, y2, 12.0);
1058         }
1059         
1060         setlinestyle(0);
1061         glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
1062         
1063         /* camera name - draw in highlighted text color */
1064         if (ca && (ca->flag & CAM_SHOWNAME)) {
1065                 UI_ThemeColor(TH_TEXT_HI);
1066                 BLF_draw_default(x1, y1-15, 0.0f, v3d->camera->id.name+2);
1067                 UI_ThemeColor(TH_WIRE);
1068         }
1069 }
1070
1071 /* *********************** backdraw for selection *************** */
1072
1073 void backdrawview3d(Scene *scene, ARegion *ar, View3D *v3d)
1074 {
1075         RegionView3D *rv3d= ar->regiondata;
1076         struct Base *base = scene->basact;
1077         rcti winrct;
1078
1079         if(base && (base->object->mode & (OB_MODE_VERTEX_PAINT|OB_MODE_WEIGHT_PAINT) ||
1080                      paint_facesel_test(base->object)));
1081         else if((base && (base->object->mode & OB_MODE_TEXTURE_PAINT)) &&
1082                 scene->toolsettings && (scene->toolsettings->imapaint.flag & IMAGEPAINT_PROJECT_DISABLE));
1083         else if((base && (base->object->mode & OB_MODE_PARTICLE_EDIT)) && v3d->drawtype>OB_WIRE && (v3d->flag & V3D_ZBUF_SELECT));
1084         else if(scene->obedit && v3d->drawtype>OB_WIRE && (v3d->flag & V3D_ZBUF_SELECT));
1085         else {
1086                 v3d->flag &= ~V3D_INVALID_BACKBUF;
1087                 return;
1088         }
1089
1090         if( !(v3d->flag & V3D_INVALID_BACKBUF) ) return;
1091
1092 //      if(test) {
1093 //              if(qtest()) {
1094 //                      addafterqueue(ar->win, BACKBUFDRAW, 1);
1095 //                      return;
1096 //              }
1097 //      }
1098
1099         if(v3d->drawtype > OB_WIRE) v3d->zbuf= TRUE;
1100         
1101         glDisable(GL_DITHER);
1102
1103         region_scissor_winrct(ar, &winrct);
1104         glScissor(winrct.xmin, winrct.ymin, winrct.xmax - winrct.xmin, winrct.ymax - winrct.ymin);
1105
1106         glClearColor(0.0, 0.0, 0.0, 0.0); 
1107         if(v3d->zbuf) {
1108                 glEnable(GL_DEPTH_TEST);
1109                 glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
1110         }
1111         else {
1112                 glClear(GL_COLOR_BUFFER_BIT);
1113                 glDisable(GL_DEPTH_TEST);
1114         }
1115         
1116         if(rv3d->rflag & RV3D_CLIPPING)
1117                 view3d_set_clipping(rv3d);
1118         
1119         G.f |= G_BACKBUFSEL;
1120         
1121         if(base && (base->lay & v3d->lay)) {
1122                 draw_object_backbufsel(scene, v3d, rv3d, base->object);
1123         }
1124
1125         v3d->flag &= ~V3D_INVALID_BACKBUF;
1126
1127         G.f &= ~G_BACKBUFSEL;
1128         v3d->zbuf= FALSE; 
1129         glDisable(GL_DEPTH_TEST);
1130         glEnable(GL_DITHER);
1131
1132         if(rv3d->rflag & RV3D_CLIPPING)
1133                 view3d_clr_clipping();
1134
1135         /* it is important to end a view in a transform compatible with buttons */
1136 //      persp(PERSP_WIN);  // set ortho
1137
1138 }
1139
1140 void view3d_validate_backbuf(ViewContext *vc)
1141 {
1142         if(vc->v3d->flag & V3D_INVALID_BACKBUF)
1143                 backdrawview3d(vc->scene, vc->ar, vc->v3d);
1144 }
1145
1146 /* samples a single pixel (copied from vpaint) */
1147 unsigned int view3d_sample_backbuf(ViewContext *vc, int x, int y)
1148 {
1149         unsigned int col;
1150         
1151         if(x >= vc->ar->winx || y >= vc->ar->winy) return 0;
1152         x+= vc->ar->winrct.xmin;
1153         y+= vc->ar->winrct.ymin;
1154         
1155         view3d_validate_backbuf(vc);
1156
1157         glReadPixels(x,  y, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE,  &col);
1158         glReadBuffer(GL_BACK);  
1159         
1160         if(ENDIAN_ORDER==B_ENDIAN) SWITCH_INT(col);
1161         
1162         return WM_framebuffer_to_index(col);
1163 }
1164
1165 /* reads full rect, converts indices */
1166 ImBuf *view3d_read_backbuf(ViewContext *vc, short xmin, short ymin, short xmax, short ymax)
1167 {
1168         unsigned int *dr, *rd;
1169         struct ImBuf *ibuf, *ibuf1;
1170         int a;
1171         short xminc, yminc, xmaxc, ymaxc, xs, ys;
1172         
1173         /* clip */
1174         if(xmin<0) xminc= 0; else xminc= xmin;
1175         if(xmax >= vc->ar->winx) xmaxc= vc->ar->winx-1; else xmaxc= xmax;
1176         if(xminc > xmaxc) return NULL;
1177
1178         if(ymin<0) yminc= 0; else yminc= ymin;
1179         if(ymax >= vc->ar->winy) ymaxc= vc->ar->winy-1; else ymaxc= ymax;
1180         if(yminc > ymaxc) return NULL;
1181         
1182         ibuf= IMB_allocImBuf((xmaxc-xminc+1), (ymaxc-yminc+1), 32, IB_rect,0);
1183
1184         view3d_validate_backbuf(vc); 
1185         
1186         glReadPixels(vc->ar->winrct.xmin+xminc, vc->ar->winrct.ymin+yminc, (xmaxc-xminc+1), (ymaxc-yminc+1), GL_RGBA, GL_UNSIGNED_BYTE, ibuf->rect);
1187         glReadBuffer(GL_BACK);  
1188
1189         if(ENDIAN_ORDER==B_ENDIAN) IMB_convert_rgba_to_abgr(ibuf);
1190
1191         a= (xmaxc-xminc+1)*(ymaxc-yminc+1);
1192         dr= ibuf->rect;
1193         while(a--) {
1194                 if(*dr) *dr= WM_framebuffer_to_index(*dr);
1195                 dr++;
1196         }
1197         
1198         /* put clipped result back, if needed */
1199         if(xminc==xmin && xmaxc==xmax && yminc==ymin && ymaxc==ymax) 
1200                 return ibuf;
1201         
1202         ibuf1= IMB_allocImBuf( (xmax-xmin+1),(ymax-ymin+1),32,IB_rect,0);
1203         rd= ibuf->rect;
1204         dr= ibuf1->rect;
1205                 
1206         for(ys= ymin; ys<=ymax; ys++) {
1207                 for(xs= xmin; xs<=xmax; xs++, dr++) {
1208                         if( xs>=xminc && xs<=xmaxc && ys>=yminc && ys<=ymaxc) {
1209                                 *dr= *rd;
1210                                 rd++;
1211                         }
1212                 }
1213         }
1214         IMB_freeImBuf(ibuf);
1215         return ibuf1;
1216 }
1217
1218 /* smart function to sample a rect spiralling outside, nice for backbuf selection */
1219 unsigned int view3d_sample_backbuf_rect(ViewContext *vc, short mval[2], int size, 
1220                                                                                 unsigned int min, unsigned int max, int *dist, short strict, 
1221                                                                                 void *handle, unsigned int (*indextest)(void *handle, unsigned int index))
1222 {
1223         struct ImBuf *buf;
1224         unsigned int *bufmin, *bufmax, *tbuf;
1225         int minx, miny;
1226         int a, b, rc, nr, amount, dirvec[4][2];
1227         int distance=0;
1228         unsigned int index = 0;
1229         short indexok = 0;      
1230
1231         amount= (size-1)/2;
1232
1233         minx = mval[0]-(amount+1);
1234         miny = mval[1]-(amount+1);
1235         buf = view3d_read_backbuf(vc, minx, miny, minx+size-1, miny+size-1);
1236         if (!buf) return 0;
1237
1238         rc= 0;
1239         
1240         dirvec[0][0]= 1; dirvec[0][1]= 0;
1241         dirvec[1][0]= 0; dirvec[1][1]= -size;
1242         dirvec[2][0]= -1; dirvec[2][1]= 0;
1243         dirvec[3][0]= 0; dirvec[3][1]= size;
1244         
1245         bufmin = buf->rect;
1246         tbuf = buf->rect;
1247         bufmax = buf->rect + size*size;
1248         tbuf+= amount*size+ amount;
1249         
1250         for(nr=1; nr<=size; nr++) {
1251                 
1252                 for(a=0; a<2; a++) {
1253                         for(b=0; b<nr; b++, distance++) {
1254                                 if (*tbuf && *tbuf>=min && *tbuf<max) { //we got a hit
1255                                         if(strict){
1256                                                 indexok =  indextest(handle, *tbuf - min+1);
1257                                                 if(indexok){
1258                                                         *dist= (short) sqrt( (float)distance   );
1259                                                         index = *tbuf - min+1;
1260                                                         goto exit; 
1261                                                 }                                               
1262                                         }
1263                                         else{
1264                                                 *dist= (short) sqrt( (float)distance ); // XXX, this distance is wrong - 
1265                                                 index = *tbuf - min+1; // messy yah, but indices start at 1
1266                                                 goto exit;
1267                                         }                       
1268                                 }
1269                                 
1270                                 tbuf+= (dirvec[rc][0]+dirvec[rc][1]);
1271                                 
1272                                 if(tbuf<bufmin || tbuf>=bufmax) {
1273                                         goto exit;
1274                                 }
1275                         }
1276                         rc++;
1277                         rc &= 3;
1278                 }
1279         }
1280
1281 exit:
1282         IMB_freeImBuf(buf);
1283         return index;
1284 }
1285
1286
1287 /* ************************************************************* */
1288
1289 static void draw_bgpic(Scene *scene, ARegion *ar, View3D *v3d)
1290 {
1291         RegionView3D *rv3d= ar->regiondata;
1292         BGpic *bgpic;
1293         Image *ima;
1294         ImBuf *ibuf= NULL;
1295         float vec[4], fac, asp, zoomx, zoomy;
1296         float x1, y1, x2, y2, cx, cy;
1297
1298
1299         for ( bgpic= v3d->bgpicbase.first; bgpic; bgpic= bgpic->next ) {
1300
1301                 if(     (bgpic->view == 0) || /* zero for any */
1302                         (bgpic->view & (1<<rv3d->view)) || /* check agaist flags */
1303                         (rv3d->persp==RV3D_CAMOB && bgpic->view == (1<<RV3D_VIEW_CAMERA))
1304                 ) {
1305                         ima= bgpic->ima;
1306                         if(ima==NULL)
1307                                 continue;
1308                         BKE_image_user_calc_frame(&bgpic->iuser, CFRA, 0);
1309                         ibuf= BKE_image_get_ibuf(ima, &bgpic->iuser);
1310                         if(ibuf==NULL || (ibuf->rect==NULL && ibuf->rect_float==NULL) )
1311                                 continue;
1312                         if(ibuf->channels!=4)
1313                                 continue;
1314                         if(ibuf->rect==NULL)
1315                                 IMB_rect_from_float(ibuf);
1316
1317                         if(rv3d->persp==RV3D_CAMOB) {
1318                                 rctf vb;
1319
1320                                 calc_viewborder(scene, ar, v3d, &vb);
1321
1322                                 x1= vb.xmin;
1323                                 y1= vb.ymin;
1324                                 x2= vb.xmax;
1325                                 y2= vb.ymax;
1326                         }
1327                         else {
1328                                 float sco[2];
1329
1330                                 /* calc window coord */
1331                                 initgrabz(rv3d, 0.0, 0.0, 0.0);
1332                                 window_to_3d_delta(ar, vec, 1, 0);
1333                                 fac= MAX3( fabs(vec[0]), fabs(vec[1]), fabs(vec[1]) );
1334                                 fac= 1.0/fac;
1335
1336                                 asp= ( (float)ibuf->y)/(float)ibuf->x;
1337
1338                                 vec[0] = vec[1] = vec[2] = 0.0;
1339                                 view3d_project_float(ar, vec, sco, rv3d->persmat);
1340                                 cx = sco[0];
1341                                 cy = sco[1];
1342
1343                                 x1=  cx+ fac*(bgpic->xof-bgpic->size);
1344                                 y1=  cy+ asp*fac*(bgpic->yof-bgpic->size);
1345                                 x2=  cx+ fac*(bgpic->xof+bgpic->size);
1346                                 y2=  cy+ asp*fac*(bgpic->yof+bgpic->size);
1347                         }
1348
1349                         /* complete clip? */
1350
1351                         if(x2 < 0 ) continue;
1352                         if(y2 < 0 ) continue;
1353                         if(x1 > ar->winx ) continue;
1354                         if(y1 > ar->winy ) continue;
1355
1356                         zoomx= (x2-x1)/ibuf->x;
1357                         zoomy= (y2-y1)/ibuf->y;
1358
1359                         /* for some reason; zoomlevels down refuses to use GL_ALPHA_SCALE */
1360                         if(zoomx < 1.0f || zoomy < 1.0f) {
1361                                 float tzoom= MIN2(zoomx, zoomy);
1362                                 int mip= 0;
1363
1364                                 if(ibuf->mipmap[0]==NULL)
1365                                         IMB_makemipmap(ibuf, 0);
1366
1367                                 while(tzoom < 1.0f && mip<8 && ibuf->mipmap[mip]) {
1368                                         tzoom*= 2.0f;
1369                                         zoomx*= 2.0f;
1370                                         zoomy*= 2.0f;
1371                                         mip++;
1372                                 }
1373                                 if(mip>0)
1374                                         ibuf= ibuf->mipmap[mip-1];
1375                         }
1376
1377                         if(v3d->zbuf) glDisable(GL_DEPTH_TEST);
1378                         glDepthMask(0);
1379
1380                         glEnable(GL_BLEND);
1381                         glBlendFunc(GL_SRC_ALPHA,  GL_ONE_MINUS_SRC_ALPHA);
1382
1383                         glMatrixMode(GL_PROJECTION);
1384                         glPushMatrix();
1385                         glMatrixMode(GL_MODELVIEW);
1386                         glPushMatrix();
1387                         ED_region_pixelspace(ar);
1388
1389                         glPixelZoom(zoomx, zoomy);
1390                         glColor4f(1.0, 1.0, 1.0, 1.0-bgpic->blend);
1391                         glaDrawPixelsTex(x1, y1, ibuf->x, ibuf->y, GL_UNSIGNED_BYTE, ibuf->rect);
1392
1393                         glPixelZoom(1.0, 1.0);
1394                         glPixelTransferf(GL_ALPHA_SCALE, 1.0f);
1395
1396                         glMatrixMode(GL_PROJECTION);
1397                         glPopMatrix();
1398                         glMatrixMode(GL_MODELVIEW);
1399                         glPopMatrix();
1400
1401                         glDisable(GL_BLEND);
1402
1403                         glDepthMask(1);
1404                         if(v3d->zbuf) glEnable(GL_DEPTH_TEST);
1405                 }
1406         }
1407 }
1408
1409 /* ****************** View3d afterdraw *************** */
1410
1411 typedef struct View3DAfter {
1412         struct View3DAfter *next, *prev;
1413         struct Base *base;
1414         int type, flag;
1415 } View3DAfter;
1416
1417 /* temp storage of Objects that need to be drawn as last */
1418 void add_view3d_after(View3D *v3d, Base *base, int type, int flag)
1419 {
1420         View3DAfter *v3da= MEM_callocN(sizeof(View3DAfter), "View 3d after");
1421         
1422         BLI_addtail(&v3d->afterdraw, v3da);
1423         v3da->base= base;
1424         v3da->type= type;
1425         v3da->flag= flag;
1426 }
1427
1428 /* clears zbuffer and draws it over */
1429 static void view3d_draw_xray(Scene *scene, ARegion *ar, View3D *v3d, int clear)
1430 {
1431         View3DAfter *v3da, *next;
1432         int doit= 0;
1433         
1434         for(v3da= v3d->afterdraw.first; v3da; v3da= v3da->next)
1435                 if(v3da->type==V3D_XRAY) doit= 1;
1436         
1437         if(doit) {
1438                 if(clear && v3d->zbuf) glClear(GL_DEPTH_BUFFER_BIT);
1439                 v3d->xray= TRUE;
1440                 
1441                 for(v3da= v3d->afterdraw.first; v3da; v3da= next) {
1442                         next= v3da->next;
1443                         if(v3da->type==V3D_XRAY) {
1444                                 draw_object(scene, ar, v3d, v3da->base, v3da->flag);
1445                                 BLI_remlink(&v3d->afterdraw, v3da);
1446                                 MEM_freeN(v3da);
1447                         }
1448                 }
1449                 v3d->xray= FALSE;
1450         }
1451 }
1452
1453 /* disables write in zbuffer and draws it over */
1454 static void view3d_draw_transp(Scene *scene, ARegion *ar, View3D *v3d)
1455 {
1456         View3DAfter *v3da, *next;
1457         
1458         glDepthMask(0);
1459         v3d->transp= TRUE;
1460         
1461         for(v3da= v3d->afterdraw.first; v3da; v3da= next) {
1462                 next= v3da->next;
1463                 if(v3da->type==V3D_TRANSP) {
1464                         draw_object(scene, ar, v3d, v3da->base, v3da->flag);
1465                         BLI_remlink(&v3d->afterdraw, v3da);
1466                         MEM_freeN(v3da);
1467                 }
1468         }
1469         v3d->transp= FALSE;
1470         
1471         glDepthMask(1);
1472         
1473 }
1474
1475 /* *********************** */
1476
1477 /*
1478         In most cases call draw_dupli_objects,
1479         draw_dupli_objects_color was added because when drawing set dupli's
1480         we need to force the color
1481  */
1482
1483 #if 0
1484 int dupli_ob_sort(void *arg1, void *arg2)
1485 {
1486         void *p1= ((DupliObject *)arg1)->ob;
1487         void *p2= ((DupliObject *)arg2)->ob;
1488         int val = 0;
1489         if (p1 < p2)            val = -1;
1490         else if (p1 > p2)       val = 1;
1491         return val;
1492 }
1493 #endif
1494
1495
1496 static DupliObject *dupli_step(DupliObject *dob)
1497 {
1498         while(dob && dob->no_draw)
1499                 dob= dob->next;
1500         return dob;
1501 }
1502
1503 static void draw_dupli_objects_color(Scene *scene, ARegion *ar, View3D *v3d, Base *base, int color)
1504 {
1505         RegionView3D *rv3d= ar->regiondata;
1506         ListBase *lb;
1507         DupliObject *dob_prev= NULL, *dob, *dob_next;
1508         Base tbase;
1509         BoundBox bb, *bb_tmp; /* use a copy because draw_object, calls clear_mesh_caches */
1510         GLuint displist=0;
1511         short transflag, use_displist= -1;      /* -1 is initialize */
1512         char dt, dtx;
1513         
1514         if (base->object->restrictflag & OB_RESTRICT_VIEW) return;
1515         
1516         tbase.flag= OB_FROMDUPLI|base->flag;
1517         lb= object_duplilist(scene, base->object);
1518         // BLI_sortlist(lb, dupli_ob_sort); // might be nice to have if we have a dupli list with mixed objects.
1519
1520         dob=dupli_step(lb->first);
1521         if(dob) dob_next= dupli_step(dob->next);
1522
1523         for( ; dob ; dob_prev= dob, dob= dob_next, dob_next= dob_next ? dupli_step(dob_next->next) : NULL) {
1524                 tbase.object= dob->ob;
1525
1526                 /* extra service: draw the duplicator in drawtype of parent */
1527                 /* MIN2 for the drawtype to allow bounding box objects in groups for lods */
1528                 dt= tbase.object->dt;   tbase.object->dt= MIN2(tbase.object->dt, base->object->dt);
1529                 dtx= tbase.object->dtx; tbase.object->dtx= base->object->dtx;
1530
1531                 /* negative scale flag has to propagate */
1532                 transflag= tbase.object->transflag;
1533                 if(base->object->transflag & OB_NEG_SCALE)
1534                         tbase.object->transflag ^= OB_NEG_SCALE;
1535
1536                 UI_ThemeColorBlend(color, TH_BACK, 0.5);
1537
1538                 /* generate displist, test for new object */
1539                 if(dob_prev && dob_prev->ob != dob->ob) {
1540                         if(use_displist==1)
1541                                 glDeleteLists(displist, 1);
1542
1543                         use_displist= -1;
1544                 }
1545
1546                 /* generate displist */
1547                 if(use_displist == -1) {
1548
1549                         /* note, since this was added, its checked dob->type==OB_DUPLIGROUP
1550                          * however this is very slow, it was probably needed for the NLA
1551                          * offset feature (used in group-duplicate.blend but no longer works in 2.5)
1552                          * so for now it should be ok to - campbell */
1553
1554                         if(             (dob_next==NULL || dob_next->ob != dob->ob) || /* if this is the last no need  to make a displist */
1555                                         (dob->ob->type == OB_LAMP) || /* lamp drawing messes with matrices, could be handled smarter... but this works */
1556                                         (dob->type == OB_DUPLIGROUP && dob->animated) ||
1557                                         !(bb_tmp= object_get_boundbox(dob->ob))
1558                         ) {
1559                                 // printf("draw_dupli_objects_color: skipping displist for %s\n", dob->ob->id.name+2);
1560                                 use_displist= 0;
1561                         }
1562                         else {
1563                                 // printf("draw_dupli_objects_color: using displist for %s\n", dob->ob->id.name+2);
1564                                 bb= *bb_tmp; /* must make a copy  */
1565
1566                                 /* disable boundbox check for list creation */
1567                                 object_boundbox_flag(dob->ob, OB_BB_DISABLED, 1);
1568                                 /* need this for next part of code */
1569                                 unit_m4(dob->ob->obmat);        /* obmat gets restored */
1570
1571                                 displist= glGenLists(1);
1572                                 glNewList(displist, GL_COMPILE);
1573                                 draw_object(scene, ar, v3d, &tbase, DRAW_CONSTCOLOR);
1574                                 glEndList();
1575
1576                                 use_displist= 1;
1577                                 object_boundbox_flag(dob->ob, OB_BB_DISABLED, 0);
1578                         }
1579                 }
1580                 if(use_displist) {
1581                         glMultMatrixf(dob->mat);
1582                         if(boundbox_clip(rv3d, dob->mat, &bb))
1583                                 glCallList(displist);
1584                         glLoadMatrixf(rv3d->viewmat);
1585                 }
1586                 else {
1587                         copy_m4_m4(dob->ob->obmat, dob->mat);
1588                         draw_object(scene, ar, v3d, &tbase, DRAW_CONSTCOLOR);
1589                 }
1590
1591                 tbase.object->dt= dt;
1592                 tbase.object->dtx= dtx;
1593                 tbase.object->transflag= transflag;
1594         }
1595         
1596         /* Transp afterdraw disabled, afterdraw only stores base pointers, and duplis can be same obj */
1597         
1598         free_object_duplilist(lb);      /* does restore */
1599         
1600         if(use_displist)
1601                 glDeleteLists(displist, 1);
1602 }
1603
1604 static void draw_dupli_objects(Scene *scene, ARegion *ar, View3D *v3d, Base *base)
1605 {
1606         /* define the color here so draw_dupli_objects_color can be called
1607         * from the set loop */
1608         
1609         int color= (base->flag & SELECT)?TH_SELECT:TH_WIRE;
1610         /* debug */
1611         if(base->object->dup_group && base->object->dup_group->id.us<1)
1612                 color= TH_REDALERT;
1613         
1614         draw_dupli_objects_color(scene, ar, v3d, base, color);
1615 }
1616
1617
1618 void view3d_update_depths(ARegion *ar, View3D *v3d)
1619 {
1620         RegionView3D *rv3d= ar->regiondata;
1621         
1622         /* Create storage for, and, if necessary, copy depth buffer */
1623         if(!rv3d->depths) rv3d->depths= MEM_callocN(sizeof(ViewDepths),"ViewDepths");
1624         if(rv3d->depths) {
1625                 ViewDepths *d= rv3d->depths;
1626                 if(d->w != ar->winx ||
1627                    d->h != ar->winy ||
1628                    !d->depths) {
1629                         d->w= ar->winx;
1630                         d->h= ar->winy;
1631                         if(d->depths)
1632                                 MEM_freeN(d->depths);
1633                         d->depths= MEM_mallocN(sizeof(float)*d->w*d->h,"View depths");
1634                         d->damaged= 1;
1635                 }
1636                 
1637                 if(d->damaged) {
1638                         glReadPixels(ar->winrct.xmin,ar->winrct.ymin,d->w,d->h,
1639                                                  GL_DEPTH_COMPONENT,GL_FLOAT, d->depths);
1640                         
1641                         glGetDoublev(GL_DEPTH_RANGE,d->depth_range);
1642                         
1643                         d->damaged= 0;
1644                 }
1645         }
1646 }
1647
1648 void draw_depth_gpencil(Scene *scene, ARegion *ar, View3D *v3d)
1649 {
1650         short zbuf= v3d->zbuf;
1651         RegionView3D *rv3d= ar->regiondata;
1652
1653         setwinmatrixview3d(ar, v3d, NULL);      /* 0= no pick rect */
1654         setviewmatrixview3d(scene, v3d, rv3d);  /* note: calls where_is_object for camera... */
1655
1656         mul_m4_m4m4(rv3d->persmat, rv3d->viewmat, rv3d->winmat);
1657         invert_m4_m4(rv3d->persinv, rv3d->persmat);
1658         invert_m4_m4(rv3d->viewinv, rv3d->viewmat);
1659
1660         glClear(GL_DEPTH_BUFFER_BIT);
1661
1662         glLoadMatrixf(rv3d->viewmat);
1663
1664         v3d->zbuf= TRUE;
1665         glEnable(GL_DEPTH_TEST);
1666
1667         draw_gpencil_3dview_ext(scene, ar, 1);
1668         
1669         v3d->zbuf= zbuf;
1670
1671 }
1672
1673 void draw_depth(Scene *scene, ARegion *ar, View3D *v3d, int (* func)(void *))
1674 {
1675         RegionView3D *rv3d= ar->regiondata;
1676         Base *base;
1677         Scene *sce;
1678         short zbuf= v3d->zbuf;
1679         short flag= v3d->flag;
1680         float glalphaclip= U.glalphaclip;
1681         int obcenter_dia= U.obcenter_dia;
1682         /* temp set drawtype to solid */
1683         
1684         /* Setting these temporarily is not nice */
1685         v3d->flag &= ~V3D_SELECT_OUTLINE;
1686         U.glalphaclip = 0.5; /* not that nice but means we wont zoom into billboards */
1687         U.obcenter_dia= 0;
1688         
1689         setwinmatrixview3d(ar, v3d, NULL);      /* 0= no pick rect */
1690         setviewmatrixview3d(scene, v3d, rv3d);  /* note: calls where_is_object for camera... */
1691         
1692         mul_m4_m4m4(rv3d->persmat, rv3d->viewmat, rv3d->winmat);
1693         invert_m4_m4(rv3d->persinv, rv3d->persmat);
1694         invert_m4_m4(rv3d->viewinv, rv3d->viewmat);
1695         
1696         glClear(GL_DEPTH_BUFFER_BIT);
1697         
1698         glLoadMatrixf(rv3d->viewmat);
1699 //      persp(PERSP_STORE);  // store correct view for persp(PERSP_VIEW) calls
1700         
1701         if(rv3d->rflag & RV3D_CLIPPING) {
1702                 view3d_set_clipping(rv3d);
1703         }
1704         
1705         v3d->zbuf= TRUE;
1706         glEnable(GL_DEPTH_TEST);
1707         
1708         /* draw set first */
1709         if(scene->set) {
1710                 for(SETLOOPER(scene->set, base)) {
1711                         if(v3d->lay & base->lay) {
1712                                 if (func == NULL || func(base)) {
1713                                         draw_object(scene, ar, v3d, base, 0);
1714                                         if(base->object->transflag & OB_DUPLI) {
1715                                                 draw_dupli_objects_color(scene, ar, v3d, base, TH_WIRE);
1716                                         }
1717                                 }
1718                         }
1719                 }
1720         }
1721         
1722         for(base= scene->base.first; base; base= base->next) {
1723                 if(v3d->lay & base->lay) {
1724                         if (func == NULL || func(base)) {
1725                                 /* dupli drawing */
1726                                 if(base->object->transflag & OB_DUPLI) {
1727                                         draw_dupli_objects(scene, ar, v3d, base);
1728                                 }
1729                                 draw_object(scene, ar, v3d, base, 0);
1730                         }
1731                 }
1732         }
1733         
1734         /* this isnt that nice, draw xray objects as if they are normal */
1735         if (v3d->afterdraw.first) {
1736                 View3DAfter *v3da, *next;
1737                 int num = 0;
1738                 v3d->xray= TRUE;
1739                 
1740                 glDepthFunc(GL_ALWAYS); /* always write into the depth bufer, overwriting front z values */
1741                 for(v3da= v3d->afterdraw.first; v3da; v3da= next) {
1742                         next= v3da->next;
1743                         if(v3da->type==V3D_XRAY) {
1744                                 draw_object(scene, ar, v3d, v3da->base, 0);
1745                                 num++;
1746                         }
1747                         /* dont remove this time */
1748                 }
1749                 v3d->xray= FALSE;
1750                 
1751                 glDepthFunc(GL_LEQUAL); /* Now write the depth buffer normally */
1752                 for(v3da= v3d->afterdraw.first; v3da; v3da= next) {
1753                         next= v3da->next;
1754                         if(v3da->type==V3D_XRAY) {
1755                                 v3d->xray= TRUE; v3d->transp= FALSE;  
1756                         } else if (v3da->type==V3D_TRANSP) {
1757                                 v3d->xray= FALSE; v3d->transp= TRUE;
1758                         }
1759                         
1760                         draw_object(scene, ar, v3d, v3da->base, 0); /* Draw Xray or Transp objects normally */
1761                         BLI_remlink(&v3d->afterdraw, v3da);
1762                         MEM_freeN(v3da);
1763                 }
1764                 v3d->xray= FALSE;
1765                 v3d->transp= FALSE;
1766         }
1767         
1768         if(rv3d->rflag & RV3D_CLIPPING)
1769                 view3d_clr_clipping();
1770         
1771         v3d->zbuf = zbuf;
1772         if(!v3d->zbuf) glDisable(GL_DEPTH_TEST);
1773
1774         U.glalphaclip = glalphaclip;
1775         v3d->flag = flag;
1776         U.obcenter_dia= obcenter_dia;
1777 }
1778
1779 typedef struct View3DShadow {
1780         struct View3DShadow *next, *prev;
1781         GPULamp *lamp;
1782 } View3DShadow;
1783
1784 static void gpu_render_lamp_update(Scene *scene, View3D *v3d, Object *ob, Object *par, float obmat[][4], ListBase *shadows)
1785 {
1786         GPULamp *lamp;
1787         Lamp *la = (Lamp*)ob->data;
1788         View3DShadow *shadow;
1789         
1790         lamp = GPU_lamp_from_blender(scene, ob, par);
1791         
1792         if(lamp) {
1793                 GPU_lamp_update(lamp, ob->lay, obmat);
1794                 GPU_lamp_update_colors(lamp, la->r, la->g, la->b, la->energy);
1795                 
1796                 if((ob->lay & v3d->lay) && GPU_lamp_has_shadow_buffer(lamp)) {
1797                         shadow= MEM_callocN(sizeof(View3DShadow), "View3DShadow");
1798                         shadow->lamp = lamp;
1799                         BLI_addtail(shadows, shadow);
1800                 }
1801         }
1802 }
1803
1804 static void gpu_update_lamps_shadows(Scene *scene, View3D *v3d)
1805 {
1806         ListBase shadows;
1807         View3DShadow *shadow;
1808         Scene *sce;
1809         Base *base;
1810         Object *ob;
1811         
1812         shadows.first= shadows.last= NULL;
1813         
1814         /* update lamp transform and gather shadow lamps */
1815         for(SETLOOPER(scene, base)) {
1816                 ob= base->object;
1817                 
1818                 if(ob->type == OB_LAMP)
1819                         gpu_render_lamp_update(scene, v3d, ob, NULL, ob->obmat, &shadows);
1820                 
1821                 if (ob->transflag & OB_DUPLI) {
1822                         DupliObject *dob;
1823                         ListBase *lb = object_duplilist(scene, ob);
1824                         
1825                         for(dob=lb->first; dob; dob=dob->next)
1826                                 if(dob->ob->type==OB_LAMP)
1827                                         gpu_render_lamp_update(scene, v3d, dob->ob, ob, dob->mat, &shadows);
1828                         
1829                         free_object_duplilist(lb);
1830                 }
1831         }
1832         
1833         /* render shadows after updating all lamps, nested object_duplilist
1834                 * don't work correct since it's replacing object matrices */
1835         for(shadow=shadows.first; shadow; shadow=shadow->next) {
1836                 /* this needs to be done better .. */
1837                 float viewmat[4][4], winmat[4][4];
1838                 int drawtype, lay, winsize, flag2;
1839                 
1840                 drawtype= v3d->drawtype;
1841                 lay= v3d->lay;
1842                 flag2= v3d->flag2 & V3D_SOLID_TEX;
1843                 
1844                 v3d->drawtype = OB_SOLID;
1845                 v3d->lay &= GPU_lamp_shadow_layer(shadow->lamp);
1846                 v3d->flag2 &= ~V3D_SOLID_TEX;
1847                 
1848                 GPU_lamp_shadow_buffer_bind(shadow->lamp, viewmat, &winsize, winmat);
1849 // XXX          drawview3d_render(v3d, viewmat, winsize, winsize, winmat, 1);
1850                 GPU_lamp_shadow_buffer_unbind(shadow->lamp);
1851                 
1852                 v3d->drawtype= drawtype;
1853                 v3d->lay= lay;
1854                 v3d->flag2 |= flag2;
1855         }
1856         
1857         BLI_freelistN(&shadows);
1858 }
1859
1860 /* *********************** customdata **************** */
1861
1862 /* goes over all modes and view3d settings */
1863 static CustomDataMask get_viewedit_datamask(bScreen *screen, Scene *scene, Object *ob)
1864 {
1865         CustomDataMask mask = CD_MASK_BAREMESH;
1866         ScrArea *sa;
1867         
1868         /* check if we need tfaces & mcols due to face select or texture paint */
1869         if(paint_facesel_test(ob) || (ob && ob->mode & OB_MODE_TEXTURE_PAINT))
1870                 mask |= CD_MASK_MTFACE | CD_MASK_MCOL;
1871         
1872         /* check if we need tfaces & mcols due to view mode */
1873         for(sa = screen->areabase.first; sa; sa = sa->next) {
1874                 if(sa->spacetype == SPACE_VIEW3D) {
1875                         View3D *view = sa->spacedata.first;
1876                         if(view->drawtype == OB_SHADED) {
1877                                 /* this includes normals for mesh_create_shadedColors */
1878                                 mask |= CD_MASK_MTFACE | CD_MASK_MCOL | CD_MASK_NORMAL | CD_MASK_ORCO;
1879                         }
1880                         if((view->drawtype == OB_TEXTURE) || ((view->drawtype == OB_SOLID) && (view->flag2 & V3D_SOLID_TEX))) {
1881                                 mask |= CD_MASK_MTFACE | CD_MASK_MCOL;
1882
1883                                 if(scene->gm.matmode == GAME_MAT_GLSL)
1884                                         mask |= CD_MASK_ORCO;
1885                         }
1886                 }
1887         }
1888         
1889         /* check if we need mcols due to vertex paint or weightpaint */
1890         if(ob) {
1891                 if(ob->mode & OB_MODE_VERTEX_PAINT)
1892                         mask |= CD_MASK_MCOL;
1893                 if(ob->mode & OB_MODE_WEIGHT_PAINT)
1894                         mask |= CD_MASK_WEIGHT_MCOL;
1895         }
1896
1897         return mask;
1898 }
1899
1900 static void view3d_main_area_setup_view(Scene *scene, View3D *v3d, ARegion *ar, float viewmat[][4], float winmat[][4])
1901 {
1902         RegionView3D *rv3d= ar->regiondata;
1903
1904         /* setup window matrices */
1905         if(winmat)
1906                 copy_m4_m4(rv3d->winmat, winmat);
1907         else
1908                 setwinmatrixview3d(ar, v3d, NULL); /* NULL= no pickrect */
1909         
1910         /* setup view matrix */
1911         if(viewmat)
1912                 copy_m4_m4(rv3d->viewmat, viewmat);
1913         else
1914                 setviewmatrixview3d(scene, v3d, rv3d);  /* note: calls where_is_object for camera... */
1915         
1916         /* update utilitity matrices */
1917         mul_m4_m4m4(rv3d->persmat, rv3d->viewmat, rv3d->winmat);
1918         invert_m4_m4(rv3d->persinv, rv3d->persmat);
1919         invert_m4_m4(rv3d->viewinv, rv3d->viewmat);
1920         
1921         /* calculate pixelsize factor once, is used for lamps and obcenters */
1922         {
1923                 float len1, len2, vec[3];
1924                 
1925                 VECCOPY(vec, rv3d->persinv[0]);
1926                 len1= normalize_v3(vec);
1927                 VECCOPY(vec, rv3d->persinv[1]);
1928                 len2= normalize_v3(vec);
1929                 
1930                 rv3d->pixsize= 2.0f*(len1>len2?len1:len2);
1931                 
1932                 /* correct for window size */
1933                 if(ar->winx > ar->winy) rv3d->pixsize/= (float)ar->winx;
1934                 else rv3d->pixsize/= (float)ar->winy;
1935         }
1936         
1937         /* set for opengl */
1938         glMatrixMode(GL_PROJECTION);
1939         glLoadMatrixf(rv3d->winmat);
1940         glMatrixMode(GL_MODELVIEW);
1941         glLoadMatrixf(rv3d->viewmat);
1942 }
1943
1944 void ED_view3d_draw_offscreen(Scene *scene, View3D *v3d, ARegion *ar, int winx, int winy, float viewmat[][4], float winmat[][4])
1945 {
1946         Scene *sce;
1947         Base *base;
1948         int bwinx, bwiny;
1949
1950         glPushMatrix();
1951
1952         /* set temporary new size */
1953         bwinx= ar->winx;
1954         bwiny= ar->winy;
1955         ar->winx= winx;
1956         ar->winy= winy;
1957
1958         /* set flags */
1959         G.f |= G_RENDER_OGL;
1960         GPU_free_images();
1961
1962         /* set background color, fallback on the view background color */
1963         if(scene->world) {
1964                 glClearColor(scene->world->horr, scene->world->horg, scene->world->horb, 0.0);
1965         }
1966         else {
1967                 float col[3];
1968                 UI_GetThemeColor3fv(TH_BACK, col);
1969                 glClearColor(col[0], col[1], col[2], 0.0);      
1970         }
1971
1972         glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
1973
1974         /* setup view matrices */
1975         view3d_main_area_setup_view(scene, v3d, ar, viewmat, winmat);
1976
1977         /* set zbuffer */
1978         if(v3d->drawtype > OB_WIRE) {
1979                 v3d->zbuf= TRUE;
1980                 glEnable(GL_DEPTH_TEST);
1981         }
1982         else
1983                 v3d->zbuf= FALSE;
1984
1985         /* draw set first */
1986         if(scene->set) {
1987                 for(SETLOOPER(scene->set, base)) {
1988                         if(v3d->lay & base->lay) {
1989                                 UI_ThemeColorBlend(TH_WIRE, TH_BACK, 0.6f);
1990                                 draw_object(scene, ar, v3d, base, DRAW_CONSTCOLOR|DRAW_SCENESET);
1991                                 
1992                                 if(base->object->transflag & OB_DUPLI)
1993                                         draw_dupli_objects_color(scene, ar, v3d, base, TH_WIRE);
1994                         }
1995                 }
1996         }
1997         
1998         /* then draw not selected and the duplis, but skip editmode object */
1999         for(base= scene->base.first; base; base= base->next) {
2000                 if(v3d->lay & base->lay) {
2001                         /* dupli drawing */
2002                         if(base->object->transflag & OB_DUPLI)
2003                                 draw_dupli_objects(scene, ar, v3d, base);
2004
2005                         draw_object(scene, ar, v3d, base, 0);
2006                 }
2007         }
2008
2009         /* transp and X-ray afterdraw stuff */
2010         view3d_draw_transp(scene, ar, v3d);
2011         view3d_draw_xray(scene, ar, v3d, 1);    // clears zbuffer if it is used!
2012
2013         /* cleanup */
2014         if(v3d->zbuf) {
2015                 v3d->zbuf= FALSE;
2016                 glDisable(GL_DEPTH_TEST);
2017         }
2018
2019         /* draw grease-pencil stuff */
2020         draw_gpencil_3dview_ext(scene, ar, 1);
2021
2022         ED_region_pixelspace(ar);
2023
2024         /* draw grease-pencil stuff - needed to get paint-buffer shown too (since it's 2D) */
2025         draw_gpencil_3dview_ext(scene, ar, 0);
2026
2027         GPU_free_images();
2028
2029         /* restore size */
2030         ar->winx= bwinx;
2031         ar->winy= bwiny;
2032
2033         glPopMatrix();
2034
2035         glColor4ub(255, 255, 255, 255); // XXX, without this the sequencer flickers with opengl draw enabled, need to find out why - campbell
2036 }
2037
2038 /* utility func for ED_view3d_draw_offscreen */
2039 ImBuf *ED_view3d_draw_offscreen_imbuf(Scene *scene, View3D *v3d, ARegion *ar, int sizex, int sizey)
2040 {
2041         RegionView3D *rv3d= ar->regiondata;
2042         ImBuf *ibuf;
2043         GPUOffScreen *ofs;
2044
2045         /* bind */
2046         ofs= GPU_offscreen_create(sizex, sizey);
2047         if(ofs == NULL)
2048                 return NULL;
2049
2050         GPU_offscreen_bind(ofs);
2051
2052         /* render 3d view */
2053         if(rv3d->persp==RV3D_CAMOB && v3d->camera) {
2054                 float winmat[4][4];
2055                 float _clipsta, _clipend, _lens, _yco, _dx, _dy;
2056                 rctf _viewplane;
2057
2058                 object_camera_matrix(&scene->r, v3d->camera, sizex, sizey, 0, winmat, &_viewplane, &_clipsta, &_clipend, &_lens, &_yco, &_dx, &_dy);
2059
2060                 ED_view3d_draw_offscreen(scene, v3d, ar, sizex, sizey, NULL, winmat);
2061         }
2062         else {
2063                 ED_view3d_draw_offscreen(scene, v3d, ar, sizex, sizey, NULL, NULL);
2064         }
2065
2066         /* read in pixels & stamp */
2067         ibuf= IMB_allocImBuf(sizex, sizey, 24, IB_rect, 0);
2068         glReadPixels(0, 0, sizex, sizey, GL_RGBA, GL_UNSIGNED_BYTE, ibuf->rect);
2069
2070         //if((scene->r.stamp & R_STAMP_ALL) && (scene->r.stamp & R_STAMP_DRAW))
2071         //      BKE_stamp_buf(scene, NULL, rr->rectf, rr->rectx, rr->recty, 4);
2072
2073         /* unbind */
2074         GPU_offscreen_unbind(ofs);
2075         GPU_offscreen_free(ofs);
2076
2077         return ibuf;
2078 }
2079
2080 /* creates own 3d views, used by the sequencer */
2081 ImBuf *ED_view3d_draw_offscreen_imbuf_simple(Scene *scene, int width, int height, int drawtype)
2082 {
2083         View3D v3d;
2084         ARegion ar;
2085         RegionView3D rv3d;
2086
2087         memset(&v3d, 0, sizeof(v3d));
2088         memset(&ar, 0, sizeof(ar));
2089         memset(&rv3d, 0, sizeof(rv3d));
2090
2091         /* connect data */
2092         v3d.regionbase.first= v3d.regionbase.last= &ar;
2093         ar.regiondata= &rv3d;
2094         ar.regiontype= RGN_TYPE_WINDOW;
2095
2096         v3d.camera= scene->camera;
2097         v3d.lay= scene->lay;
2098         v3d.drawtype = drawtype;
2099         v3d.flag2 = V3D_RENDER_OVERRIDE;
2100
2101         rv3d.persp= RV3D_CAMOB;
2102
2103         copy_m4_m4(rv3d.viewinv, v3d.camera->obmat);
2104         normalize_m4(rv3d.viewinv);
2105         invert_m4_m4(rv3d.viewmat, rv3d.viewinv);
2106
2107         {
2108                 float _yco, _dx, _dy;
2109                 rctf _viewplane;
2110                 object_camera_matrix(&scene->r, v3d.camera, width, height, 0, rv3d.winmat, &_viewplane, &v3d.near, &v3d.far, &v3d.lens, &_yco, &_dx, &_dy);
2111         }
2112
2113         mul_m4_m4m4(rv3d.persmat, rv3d.viewmat, rv3d.winmat);
2114         invert_m4_m4(rv3d.persinv, rv3d.viewinv);
2115
2116         return ED_view3d_draw_offscreen_imbuf(scene, &v3d, &ar, width, height);
2117
2118         // seq_view3d_cb(scene, cfra, render_size, seqrectx, seqrecty);
2119 }
2120
2121
2122 /* NOTE: the info that this uses is updated in ED_refresh_viewport_fps(), 
2123  * which currently gets called during SCREEN_OT_animation_step.
2124  */
2125 static void draw_viewport_fps(Scene *scene, ARegion *ar)
2126 {
2127         ScreenFrameRateInfo *fpsi= scene->fps_info;
2128         float fps;
2129         char printable[16];
2130         int i, tot;
2131         
2132         if (!fpsi || !fpsi->lredrawtime || !fpsi->redrawtime)
2133                 return;
2134         
2135         printable[0] = '\0';
2136         
2137 #if 0
2138         /* this is too simple, better do an average */
2139         fps = (float)(1.0/(fpsi->lredrawtime-fpsi->redrawtime))
2140 #else
2141         fpsi->redrawtimes_fps[fpsi->redrawtime_index] = (float)(1.0/(fpsi->lredrawtime-fpsi->redrawtime));
2142         
2143         for (i=0, tot=0, fps=0.0f ; i < REDRAW_FRAME_AVERAGE ; i++) {
2144                 if (fpsi->redrawtimes_fps[i]) {
2145                         fps += fpsi->redrawtimes_fps[i];
2146                         tot++;
2147                 }
2148         }
2149         if (tot) {
2150                 fpsi->redrawtime_index = (fpsi->redrawtime_index + 1) % REDRAW_FRAME_AVERAGE;
2151                 
2152                 //fpsi->redrawtime_index++;
2153                 //if (fpsi->redrawtime >= REDRAW_FRAME_AVERAGE)
2154                 //      fpsi->redrawtime = 0;
2155                 
2156                 fps = fps / tot;
2157         }
2158 #endif
2159         
2160         /* is this more then half a frame behind? */
2161         if (fps+0.5 < FPS) {
2162                 UI_ThemeColor(TH_REDALERT);
2163                 sprintf(printable, "fps: %.2f", (float)fps);
2164         } 
2165         else {
2166                 UI_ThemeColor(TH_TEXT_HI);
2167                 sprintf(printable, "fps: %i", (int)(fps+0.5));
2168         }
2169         
2170         BLF_draw_default(22,  ar->winy-17, 0.0f, printable);
2171 }
2172
2173 void view3d_main_area_draw(const bContext *C, ARegion *ar)
2174 {
2175         Scene *scene= CTX_data_scene(C);
2176         View3D *v3d = CTX_wm_view3d(C);
2177         RegionView3D *rv3d= CTX_wm_region_view3d(C);
2178         Scene *sce;
2179         Base *base;
2180         Object *ob;
2181         float col[3];
2182         int retopo= 0, sculptparticle= 0;
2183         Object *obact = OBACT;
2184         char *grid_unit= NULL;
2185
2186         /* from now on all object derived meshes check this */
2187         v3d->customdata_mask= get_viewedit_datamask(CTX_wm_screen(C), scene, obact);
2188
2189         /* shadow buffers, before we setup matrices */
2190         if(draw_glsl_material(scene, NULL, v3d, v3d->drawtype))
2191                 gpu_update_lamps_shadows(scene, v3d);
2192         
2193         /* reset default OpenGL lights if needed (i.e. after preferences have been altered) */
2194         if (rv3d->rflag & RV3D_GPULIGHT_UPDATE) {
2195                 rv3d->rflag &= ~RV3D_GPULIGHT_UPDATE;
2196                 GPU_default_lights();
2197         }
2198
2199         /* clear background */
2200         UI_GetThemeColor3fv(TH_BACK, col);
2201         glClearColor(col[0], col[1], col[2], 0.0); 
2202         glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
2203         
2204         /* setup view matrices */
2205         view3d_main_area_setup_view(scene, v3d, ar, NULL, NULL);
2206
2207         ED_region_draw_cb_draw(C, ar, REGION_DRAW_PRE_VIEW);
2208
2209         if(rv3d->rflag & RV3D_CLIPPING)
2210                 view3d_draw_clipping(rv3d);
2211         
2212         /* set zbuffer after we draw clipping region */
2213         if(v3d->drawtype > OB_WIRE) {
2214                 v3d->zbuf= TRUE;
2215                 glEnable(GL_DEPTH_TEST);
2216         }
2217         else
2218                 v3d->zbuf= FALSE;
2219
2220         /* enables anti-aliasing for 3D view drawing */
2221         /*if (!(U.gameflags & USER_DISABLE_AA))
2222                 glEnable(GL_MULTISAMPLE_ARB);*/
2223         
2224         // needs to be done always, gridview is adjusted in drawgrid() now
2225         rv3d->gridview= v3d->grid;
2226         
2227         if ((v3d->flag2 & V3D_RENDER_OVERRIDE)==0) {
2228
2229                 if(rv3d->view==0 || rv3d->persp != RV3D_ORTHO) {
2230                         drawfloor(scene, v3d);
2231                         if(rv3d->persp==RV3D_CAMOB) {
2232                                 if(scene->world) {
2233                                         if(scene->world->mode & WO_STARS) {
2234                                                 RE_make_stars(NULL, scene, star_stuff_init_func, star_stuff_vertex_func,
2235                                                                           star_stuff_term_func);
2236                                         }
2237                                 }
2238                                 if(v3d->flag & V3D_DISPBGPICS) draw_bgpic(scene, ar, v3d);
2239                         }
2240                 }
2241                 else {
2242                         ED_region_pixelspace(ar);
2243                         drawgrid(&scene->unit, ar, v3d, &grid_unit);
2244                         /* XXX make function? replaces persp(1) */
2245                         glMatrixMode(GL_PROJECTION);
2246                         glLoadMatrixf(rv3d->winmat);
2247                         glMatrixMode(GL_MODELVIEW);
2248                         glLoadMatrixf(rv3d->viewmat);
2249
2250                         if(v3d->flag & V3D_DISPBGPICS) {
2251                                 draw_bgpic(scene, ar, v3d);
2252                         }
2253                 }
2254         }
2255         
2256         if(rv3d->rflag & RV3D_CLIPPING)
2257                 view3d_set_clipping(rv3d);
2258
2259         /* draw set first */
2260         if(scene->set) {
2261                 for(SETLOOPER(scene->set, base)) {
2262                         
2263                         if(v3d->lay & base->lay) {
2264                                 
2265                                 UI_ThemeColorBlend(TH_WIRE, TH_BACK, 0.6f);
2266                                 draw_object(scene, ar, v3d, base, DRAW_CONSTCOLOR|DRAW_SCENESET);
2267                                 
2268                                 if(base->object->transflag & OB_DUPLI) {
2269                                         draw_dupli_objects_color(scene, ar, v3d, base, TH_WIRE);
2270                                 }
2271                         }
2272                 }
2273                 
2274                 /* Transp and X-ray afterdraw stuff for sets is done later */
2275         }
2276         
2277         /* extra service in layerbuttons, showing used layers */
2278         v3d->lay_used = 0;
2279
2280         /* then draw not selected and the duplis, but skip editmode object */
2281         for(base= scene->base.first; base; base= base->next) {
2282                 v3d->lay_used |= base->lay;
2283                 
2284                 if(v3d->lay & base->lay) {
2285                         
2286                         /* dupli drawing */
2287                         if(base->object->transflag & OB_DUPLI) {
2288                                 draw_dupli_objects(scene, ar, v3d, base);
2289                         }
2290                         if((base->flag & SELECT)==0) {
2291                                 if(base->object!=scene->obedit) 
2292                                         draw_object(scene, ar, v3d, base, 0);
2293                         }
2294                 }
2295         }
2296
2297 //      retopo= retopo_mesh_check() || retopo_curve_check();
2298         sculptparticle= (obact && obact->mode & (OB_MODE_PARTICLE_EDIT)) && !scene->obedit;
2299         if(retopo)
2300                 view3d_update_depths(ar, v3d);
2301         
2302         /* draw selected and editmode */
2303         for(base= scene->base.first; base; base= base->next) {
2304                 if(v3d->lay & base->lay) {
2305                         if (base->object==scene->obedit || ( base->flag & SELECT) ) 
2306                                 draw_object(scene, ar, v3d, base, 0);
2307                 }
2308         }
2309         
2310         if(!retopo && sculptparticle && !(obact && (obact->dtx & OB_DRAWXRAY))) {
2311                 view3d_update_depths(ar, v3d);
2312         }
2313         
2314 //      REEB_draw();
2315         
2316         /* Transp and X-ray afterdraw stuff */
2317         view3d_draw_transp(scene, ar, v3d);
2318         view3d_draw_xray(scene, ar, v3d, 1);    // clears zbuffer if it is used!
2319         
2320         ED_region_draw_cb_draw(C, ar, REGION_DRAW_POST_VIEW);
2321         
2322         if(!retopo && sculptparticle && (obact && (OBACT->dtx & OB_DRAWXRAY))) {
2323                 view3d_update_depths(ar, v3d);
2324         }
2325         
2326         if(rv3d->rflag & RV3D_CLIPPING)
2327                 view3d_clr_clipping();
2328         
2329         BIF_draw_manipulator(C);
2330         
2331         /* Disable back anti-aliasing */
2332         /*if (!(U.gameflags & USER_DISABLE_AA))
2333                 glDisable(GL_MULTISAMPLE_ARB);*/
2334
2335         if(v3d->zbuf) {
2336                 v3d->zbuf= FALSE;
2337                 glDisable(GL_DEPTH_TEST);
2338         }
2339         
2340         if ((v3d->flag2 & V3D_RENDER_OVERRIDE)==0) {
2341                 /* draw grease-pencil stuff (3d-space strokes) */
2342                 //if (v3d->flag2 & V3D_DISPGP)
2343                         draw_gpencil_3dview((bContext *)C, 1);
2344
2345                 BDR_drawSketch(C);
2346         }
2347
2348         ED_region_pixelspace(ar);
2349         
2350 //      retopo_paint_view_update(v3d);
2351 //      retopo_draw_paint_lines();
2352         
2353         /* Draw particle edit brush XXX (removed) */
2354         
2355
2356         if(rv3d->persp==RV3D_CAMOB) drawviewborder(scene, ar, v3d);
2357         if(rv3d->rflag & RV3D_FLYMODE) drawviewborder_flymode(ar);
2358
2359         if ((v3d->flag2 & V3D_RENDER_OVERRIDE)==0) {
2360                 /* draw grease-pencil stuff - needed to get paint-buffer shown too (since it's 2D) */
2361         //      if (v3d->flag2 & V3D_DISPGP)
2362                         draw_gpencil_3dview((bContext *)C, 0);
2363
2364                 drawcursor(scene, ar, v3d);
2365         }
2366         
2367         if(U.uiflag & USER_SHOW_ROTVIEWICON)
2368                 draw_view_axis(rv3d);
2369         else    
2370                 draw_view_icon(rv3d);
2371         
2372         if((U.uiflag & USER_SHOW_FPS) && (CTX_wm_screen(C)->animtimer)) {
2373                 draw_viewport_fps(scene, ar);
2374         }
2375         else if(U.uiflag & USER_SHOW_VIEWPORTNAME) {
2376                 draw_viewport_name(ar, v3d);
2377         }
2378         if (grid_unit) { /* draw below the viewport name */
2379                 UI_ThemeColor(TH_TEXT_HI);
2380                 BLF_draw_default(10,  ar->winy-(USER_SHOW_VIEWPORTNAME?40:20), 0.0f, grid_unit);
2381         }
2382
2383         ob= OBACT;
2384         if(U.uiflag & USER_DRAWVIEWINFO) 
2385                 draw_selected_name(scene, ob, v3d);
2386
2387         ED_region_draw_cb_draw(C, ar, REGION_DRAW_POST_PIXEL);
2388         
2389         /* XXX here was the blockhandlers for floating panels */
2390
2391         v3d->flag |= V3D_INVALID_BACKBUF;
2392 }