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