Changes to "Face Select" mode
[blender.git] / source / blender / src / drawview.c
1 /**
2  * $Id$
3  *
4  * ***** BEGIN GPL/BL DUAL 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. The Blender
10  * Foundation also sells licenses for use in proprietary software under
11  * the Blender License.  See http://www.blender.org/BL/ for information
12  * about this.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU General Public License for more details.
18  *
19  * You should have received a copy of the GNU General Public License
20  * along with this program; if not, write to the Free Software Foundation,
21  * Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
22  *
23  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
24  * All rights reserved.
25  *
26  * The Original Code is: all of this file.
27  *
28  * Contributor(s): none yet.
29  *
30  * ***** END GPL/BL DUAL LICENSE BLOCK *****
31  */
32
33 //#define NAN_LINEAR_PHYSICS
34
35 #include <math.h>
36 #include <string.h>
37
38 #ifndef WIN32
39 #include <unistd.h>
40 #include <sys/times.h>
41 #else
42 #include <io.h>
43 #endif   
44
45 #ifdef WIN32
46 #ifndef snprintf
47 #define snprintf _snprintf
48 #endif
49 #endif
50
51 #include "MEM_guardedalloc.h"
52
53 #include "PIL_time.h"
54
55 #include "BMF_Api.h"
56
57 #include "IMB_imbuf_types.h"
58 #include "IMB_imbuf.h"
59
60 #include "DNA_action_types.h"
61 #include "DNA_armature_types.h"
62 #include "DNA_brush_types.h"
63 #include "DNA_camera_types.h"
64 #include "DNA_constraint_types.h"
65 #include "DNA_curve_types.h"
66 #include "DNA_group_types.h"
67 #include "DNA_image_types.h"
68 #include "DNA_key_types.h"
69 #include "DNA_lattice_types.h"
70 #include "DNA_mesh_types.h"
71 #include "DNA_meshdata_types.h"
72 #include "DNA_meta_types.h"
73 #include "DNA_object_types.h"
74 #include "DNA_screen_types.h"
75 #include "DNA_scene_types.h"
76 #include "DNA_space_types.h"
77 #include "DNA_texture_types.h"
78 #include "DNA_userdef_types.h"
79 #include "DNA_view3d_types.h"
80 #include "DNA_world_types.h"
81
82 #include "BLI_blenlib.h"
83 #include "BLI_arithb.h"
84 #include "BLI_editVert.h"
85
86 #include "BKE_action.h"
87 #include "BKE_armature.h"
88 #include "BKE_anim.h"
89 #include "BKE_constraint.h"
90 #include "BKE_curve.h"
91 #include "BKE_customdata.h"
92 #include "BKE_displist.h"
93 #include "BKE_depsgraph.h"
94 #include "BKE_DerivedMesh.h"
95 #include "BKE_global.h"
96 #include "BKE_lattice.h"
97 #include "BKE_library.h"
98 #include "BKE_image.h"
99 #include "BKE_ipo.h"
100 #include "BKE_key.h"
101 #include "BKE_main.h"
102 #include "BKE_mesh.h"
103 #include "BKE_object.h"
104 #include "BKE_scene.h"
105 #include "BKE_texture.h"
106 #include "BKE_utildefines.h"
107
108 #include "BIF_butspace.h"
109 #include "BIF_drawimage.h"
110 #include "BIF_editgroup.h"
111 #include "BIF_editarmature.h"
112 #include "BIF_editmesh.h"
113 #include "BIF_gl.h"
114 #include "BIF_glutil.h"
115 #include "BIF_interface.h"
116 #include "BIF_interface_icons.h"
117 #include "BIF_mywindow.h"
118 #include "BIF_poseobject.h"
119 #include "BIF_previewrender.h"
120 #include "BIF_resources.h"
121 #include "BIF_retopo.h"
122 #include "BIF_screen.h"
123 #include "BIF_space.h"
124
125 #ifdef WITH_VERSE
126 #include "BIF_verse.h"
127 #endif
128
129 #include "BDR_drawmesh.h"
130 #include "BDR_drawobject.h"
131 #include "BDR_editobject.h"
132 #include "BDR_vpaint.h"
133 #include "BDR_sculptmode.h"
134
135 #include "BSE_drawview.h"
136 #include "BSE_filesel.h"
137 #include "BSE_headerbuttons.h"
138 #include "BSE_seqaudio.h"
139 #include "BSE_trans_types.h"
140 #include "BSE_time.h"
141 #include "BSE_view.h"
142
143 #include "BPY_extern.h"
144
145 #include "RE_render_ext.h"
146
147 #include "blendef.h"
148 #include "mydevice.h"
149 #include "butspace.h"  // event codes
150
151 #include "BIF_transform.h"
152
153 #include "RE_pipeline.h"        // make_stars
154
155 #include "multires.h"
156
157 /* For MULTISAMPLE_ARB #define.
158    Note that older systems like irix 
159    may not have this, and will need a #ifdef
160    to disable it.*/
161 /* #include "GL/glext.h" Disabled for release, to avoid possibly breaking platforms.
162    Instead, the define we need will just be #defined if it's not in the platform opengl.h.
163 */
164
165 /* Modules used */
166 #include "radio.h"
167
168 /* locals */
169 void drawname(Object *ob);
170
171 static void star_stuff_init_func(void)
172 {
173         cpack(-1);
174         glPointSize(1.0);
175         glBegin(GL_POINTS);
176 }
177 static void star_stuff_vertex_func(float* i)
178 {
179         glVertex3fv(i);
180 }
181 static void star_stuff_term_func(void)
182 {
183         glEnd();
184 }
185
186 void default_gl_light(void)
187 {
188         int a;
189         
190         /* initialize */
191         if(U.light[0].flag==0 && U.light[1].flag==0 && U.light[2].flag==0) {
192                 U.light[0].flag= 1;
193                 U.light[0].vec[0]= -0.3; U.light[0].vec[1]= 0.3; U.light[0].vec[2]= 0.9;
194                 U.light[0].col[0]= 0.8; U.light[0].col[1]= 0.8; U.light[0].col[2]= 0.8;
195                 U.light[0].spec[0]= 0.5; U.light[0].spec[1]= 0.5; U.light[0].spec[2]= 0.5;
196                 U.light[0].spec[3]= 1.0;
197                 
198                 U.light[1].flag= 0;
199                 U.light[1].vec[0]= 0.5; U.light[1].vec[1]= 0.5; U.light[1].vec[2]= 0.1;
200                 U.light[1].col[0]= 0.4; U.light[1].col[1]= 0.4; U.light[1].col[2]= 0.8;
201                 U.light[1].spec[0]= 0.3; U.light[1].spec[1]= 0.3; U.light[1].spec[2]= 0.5;
202                 U.light[1].spec[3]= 1.0;
203         
204                 U.light[2].flag= 0;
205                 U.light[2].vec[0]= 0.3; U.light[2].vec[1]= -0.3; U.light[2].vec[2]= -0.2;
206                 U.light[2].col[0]= 0.8; U.light[2].col[1]= 0.5; U.light[2].col[2]= 0.4;
207                 U.light[2].spec[0]= 0.5; U.light[2].spec[1]= 0.4; U.light[2].spec[2]= 0.3;
208                 U.light[2].spec[3]= 1.0;
209         }
210         
211
212         glLightfv(GL_LIGHT0, GL_POSITION, U.light[0].vec); 
213         glLightfv(GL_LIGHT0, GL_DIFFUSE, U.light[0].col); 
214         glLightfv(GL_LIGHT0, GL_SPECULAR, U.light[0].spec); 
215
216         glLightfv(GL_LIGHT1, GL_POSITION, U.light[1].vec); 
217         glLightfv(GL_LIGHT1, GL_DIFFUSE, U.light[1].col); 
218         glLightfv(GL_LIGHT1, GL_SPECULAR, U.light[1].spec); 
219
220         glLightfv(GL_LIGHT2, GL_POSITION, U.light[2].vec); 
221         glLightfv(GL_LIGHT2, GL_DIFFUSE, U.light[2].col); 
222         glLightfv(GL_LIGHT2, GL_SPECULAR, U.light[2].spec); 
223
224         for(a=0; a<8; a++) {
225                 if(a<3) {
226                         if(U.light[a].flag) glEnable(GL_LIGHT0+a);
227                         else glDisable(GL_LIGHT0+a);
228                         
229                         // clear stuff from other opengl lamp usage
230                         glLightf(GL_LIGHT0+a, GL_SPOT_CUTOFF, 180.0);
231                         glLightf(GL_LIGHT0+a, GL_CONSTANT_ATTENUATION, 1.0);
232                         glLightf(GL_LIGHT0+a, GL_LINEAR_ATTENUATION, 0.0);
233                 }
234                 else glDisable(GL_LIGHT0+a);
235         }
236         
237         glDisable(GL_LIGHTING);
238
239         glDisable(GL_COLOR_MATERIAL);
240 }
241
242 /* also called when render 'ogl' */
243 void init_gl_stuff(void)        
244 {
245         float mat_ambient[] = { 0.0, 0.0, 0.0, 0.0 };
246         float mat_specular[] = { 0.5, 0.5, 0.5, 1.0 };
247         float mat_shininess[] = { 35.0 };
248         int a, x, y;
249         GLubyte pat[32*32];
250         const GLubyte *patc= pat;
251         
252         
253         glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, mat_ambient);
254         glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, mat_specular);
255         glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, mat_specular);
256         glMaterialfv(GL_FRONT_AND_BACK, GL_SHININESS, mat_shininess);
257
258         default_gl_light();
259         
260         /* no local viewer, looks ugly in ortho mode */
261         /* glLightModelfv(GL_LIGHT_MODEL_LOCAL_VIEWER, &one); */
262         
263         glDepthFunc(GL_LEQUAL);
264         /* scaling matrices */
265         glEnable(GL_NORMALIZE);
266
267         glShadeModel(GL_FLAT);
268
269         glDisable(GL_ALPHA_TEST);
270         glDisable(GL_BLEND);
271         glDisable(GL_DEPTH_TEST);
272         glDisable(GL_FOG);
273         glDisable(GL_LIGHTING);
274         glDisable(GL_LOGIC_OP);
275         glDisable(GL_STENCIL_TEST);
276         glDisable(GL_TEXTURE_1D);
277         glDisable(GL_TEXTURE_2D);
278
279         /* default on, disable/enable should be local per function */
280         glEnableClientState(GL_VERTEX_ARRAY);
281         glEnableClientState(GL_NORMAL_ARRAY);
282         
283         glPixelTransferi(GL_MAP_COLOR, GL_FALSE);
284         glPixelTransferi(GL_RED_SCALE, 1);
285         glPixelTransferi(GL_RED_BIAS, 0);
286         glPixelTransferi(GL_GREEN_SCALE, 1);
287         glPixelTransferi(GL_GREEN_BIAS, 0);
288         glPixelTransferi(GL_BLUE_SCALE, 1);
289         glPixelTransferi(GL_BLUE_BIAS, 0);
290         glPixelTransferi(GL_ALPHA_SCALE, 1);
291         glPixelTransferi(GL_ALPHA_BIAS, 0);
292         
293         glPixelTransferi(GL_DEPTH_BIAS, 0);
294         glPixelTransferi(GL_DEPTH_SCALE, 1);
295         glDepthRange(0.0, 1.0);
296         
297         a= 0;
298         for(x=0; x<32; x++) {
299                 for(y=0; y<4; y++) {
300                         if( (x) & 1) pat[a++]= 0x88;
301                         else pat[a++]= 0x22;
302                 }
303         }
304         
305         glPolygonStipple(patc);
306
307
308         init_realtime_GL();     
309 }
310
311 void circf(float x, float y, float rad)
312 {
313         GLUquadricObj *qobj = gluNewQuadric(); 
314         
315         gluQuadricDrawStyle(qobj, GLU_FILL); 
316         
317         glPushMatrix(); 
318         
319         glTranslatef(x,  y, 0.); 
320         
321         gluDisk( qobj, 0.0,  rad, 32, 1); 
322         
323         glPopMatrix(); 
324         
325         gluDeleteQuadric(qobj);
326 }
327
328 void circ(float x, float y, float rad)
329 {
330         GLUquadricObj *qobj = gluNewQuadric(); 
331         
332         gluQuadricDrawStyle(qobj, GLU_SILHOUETTE); 
333         
334         glPushMatrix(); 
335         
336         glTranslatef(x,  y, 0.); 
337         
338         gluDisk( qobj, 0.0,  rad, 32, 1); 
339         
340         glPopMatrix(); 
341         
342         gluDeleteQuadric(qobj);
343 }
344
345 /* **********  ********** */
346
347 static void draw_bgpic(void)
348 {
349         BGpic *bgpic;
350         Image *ima;
351         ImBuf *ibuf= NULL;
352         float vec[4], fac, asp, zoomx, zoomy;
353         float x1, y1, x2, y2, cx, cy;
354         
355         bgpic= G.vd->bgpic;
356         if(bgpic==NULL) return;
357         
358         ima= bgpic->ima;
359         
360         if(ima)
361                 ibuf= BKE_image_get_ibuf(ima, &bgpic->iuser);
362         if(ibuf==NULL || (ibuf->rect==NULL && ibuf->rect_float==NULL) ) 
363                 return;
364         if(ibuf->channels!=4)
365                 return;
366         if(ibuf->rect==NULL)
367                 IMB_rect_from_float(ibuf);
368         
369         if(G.vd->persp==2) {
370                 rctf vb;
371
372                 calc_viewborder(G.vd, &vb);
373
374                 x1= vb.xmin;
375                 y1= vb.ymin;
376                 x2= vb.xmax;
377                 y2= vb.ymax;
378         }
379         else {
380                 float sco[2];
381
382                 /* calc window coord */
383                 initgrabz(0.0, 0.0, 0.0);
384                 window_to_3d(vec, 1, 0);
385                 fac= MAX3( fabs(vec[0]), fabs(vec[1]), fabs(vec[1]) );
386                 fac= 1.0/fac;
387         
388                 asp= ( (float)ibuf->y)/(float)ibuf->x;
389
390                 vec[0] = vec[1] = vec[2] = 0.0;
391                 view3d_project_float(curarea, vec, sco, G.vd->persmat);
392                 cx = sco[0];
393                 cy = sco[1];
394         
395                 x1=  cx+ fac*(bgpic->xof-bgpic->size);
396                 y1=  cy+ asp*fac*(bgpic->yof-bgpic->size);
397                 x2=  cx+ fac*(bgpic->xof+bgpic->size);
398                 y2=  cy+ asp*fac*(bgpic->yof+bgpic->size);
399         }
400         
401         /* complete clip? */
402         
403         if(x2 < 0 ) return;
404         if(y2 < 0 ) return;
405         if(x1 > curarea->winx ) return;
406         if(y1 > curarea->winy ) return;
407         
408         zoomx= (x2-x1)/ibuf->x;
409         zoomy= (y2-y1)/ibuf->y;
410         
411         /* for some reason; zoomlevels down refuses to use GL_ALPHA_SCALE */
412         if(zoomx < 1.0f || zoomy < 1.0f) {
413                 float tzoom= MIN2(zoomx, zoomy);
414                 int mip= 0;
415                 
416                 if(ibuf->mipmap[0]==NULL)
417                         IMB_makemipmap(ibuf, 0);
418                 
419                 while(tzoom < 1.0f && mip<8 && ibuf->mipmap[mip]) {
420                         tzoom*= 2.0f;
421                         zoomx*= 2.0f;
422                         zoomy*= 2.0f;
423                         mip++;
424                 }
425                 if(mip>0)
426                         ibuf= ibuf->mipmap[mip-1];
427         }
428         
429         if(G.vd->zbuf) glDisable(GL_DEPTH_TEST);
430
431         glBlendFunc(GL_SRC_ALPHA,  GL_ONE_MINUS_SRC_ALPHA); 
432          
433         glMatrixMode(GL_PROJECTION);
434         glPushMatrix();
435         glMatrixMode(GL_MODELVIEW);
436         glPushMatrix();
437         
438         glaDefine2DArea(&curarea->winrct);
439         glEnable(GL_BLEND);
440         glPixelTransferf(GL_ALPHA_SCALE, (1.0f-bgpic->blend));
441         glPixelZoom(zoomx, zoomy);
442         glaDrawPixelsSafe(x1, y1, ibuf->x, ibuf->y, ibuf->x, GL_RGBA, GL_UNSIGNED_BYTE, ibuf->rect);
443         glPixelZoom(1.0, 1.0);
444         glPixelTransferf(GL_ALPHA_SCALE, 1.0f);
445
446         glMatrixMode(GL_PROJECTION);
447         glPopMatrix();
448         glMatrixMode(GL_MODELVIEW);
449         glPopMatrix();
450         
451         glDisable(GL_BLEND);
452         if(G.vd->zbuf) glEnable(GL_DEPTH_TEST);
453         
454         areawinset(curarea->win);       // restore viewport / scissor
455 }
456
457 static void drawgrid_draw(float wx, float wy, float x, float y, float dx)
458 {
459         float fx, fy;
460         
461         x+= (wx); 
462         y+= (wy);
463         fx= x/dx;
464         fx= x-dx*floor(fx);
465         
466         while(fx< curarea->winx) {
467                 fdrawline(fx,  0.0,  fx,  (float)curarea->winy); 
468                 fx+= dx; 
469         }
470
471         fy= y/dx;
472         fy= y-dx*floor(fy);
473         
474
475         while(fy< curarea->winy) {
476                 fdrawline(0.0,  fy,  (float)curarea->winx,  fy); 
477                 fy+= dx;
478         }
479
480 }
481
482 // not intern, called in editobject for constraint axis too
483 void make_axis_color(char *col, char *col2, char axis)
484 {
485         if(axis=='x') {
486                 col2[0]= col[0]>219?255:col[0]+36;
487                 col2[1]= col[1]<26?0:col[1]-26;
488                 col2[2]= col[2]<26?0:col[2]-26;
489         }
490         else if(axis=='y') {
491                 col2[0]= col[0]<46?0:col[0]-36;
492                 col2[1]= col[1]>189?255:col[1]+66;
493                 col2[2]= col[2]<46?0:col[2]-36; 
494         }
495         else {
496                 col2[0]= col[0]<26?0:col[0]-26; 
497                 col2[1]= col[1]<26?0:col[1]-26; 
498                 col2[2]= col[2]>209?255:col[2]+46;
499         }
500         
501 }
502
503 static void drawgrid(void)
504 {
505         /* extern short bgpicmode; */
506         float wx, wy, x, y, fw, fx, fy, dx;
507         float vec4[4];
508         char col[3], col2[3];
509         short sublines = G.vd->gridsubdiv;
510         
511         vec4[0]=vec4[1]=vec4[2]=0.0; 
512         vec4[3]= 1.0;
513         Mat4MulVec4fl(G.vd->persmat, vec4);
514         fx= vec4[0]; 
515         fy= vec4[1]; 
516         fw= vec4[3];
517
518         wx= (curarea->winx/2.0);        /* because of rounding errors, grid at wrong location */
519         wy= (curarea->winy/2.0);
520
521         x= (wx)*fx/fw;
522         y= (wy)*fy/fw;
523
524         vec4[0]=vec4[1]=G.vd->grid; 
525         vec4[2]= 0.0;
526         vec4[3]= 1.0;
527         Mat4MulVec4fl(G.vd->persmat, vec4);
528         fx= vec4[0]; 
529         fy= vec4[1]; 
530         fw= vec4[3];
531
532         dx= fabs(x-(wx)*fx/fw);
533         if(dx==0) dx= fabs(y-(wy)*fy/fw);
534         
535         glDepthMask(0);         // disable write in zbuffer
536
537         /* check zoom out */
538         BIF_ThemeColor(TH_GRID);
539         persp(PERSP_WIN);
540         
541         if(dx<6.0) {
542                 G.vd->gridview*= sublines;
543                 dx*= sublines;
544                 
545                 if(dx<6.0) {    
546                         G.vd->gridview*= sublines;
547                         dx*= sublines;
548                         
549                         if(dx<6.0) {
550                                 G.vd->gridview*= sublines;
551                                 dx*=sublines;
552                                 if(dx<6.0);
553                                 else {
554                                         BIF_ThemeColor(TH_GRID);
555                                         drawgrid_draw(wx, wy, x, y, dx);
556                                 }
557                         }
558                         else {  // start blending out
559                                 BIF_ThemeColorBlend(TH_BACK, TH_GRID, dx/60.0);
560                                 drawgrid_draw(wx, wy, x, y, dx);
561                         
562                                 BIF_ThemeColor(TH_GRID);
563                                 drawgrid_draw(wx, wy, x, y, sublines*dx);
564                         }
565                 }
566                 else {  // start blending out (6 < dx < 60)
567                         BIF_ThemeColorBlend(TH_BACK, TH_GRID, dx/60.0);
568                         drawgrid_draw(wx, wy, x, y, dx);
569                         
570                         BIF_ThemeColor(TH_GRID);
571                         drawgrid_draw(wx, wy, x, y, sublines*dx);
572                 }
573         }
574         else {
575                 if(dx>60.0) {           // start blending in
576                         G.vd->gridview/= sublines;
577                         dx/= sublines;                  
578                         if(dx>60.0) {           // start blending in
579                                 G.vd->gridview/= sublines;
580                                 dx/= sublines;
581                                 if(dx>60.0) {
582                                         BIF_ThemeColor(TH_GRID);
583                                         drawgrid_draw(wx, wy, x, y, dx);
584                                 }
585                                 else {
586                                         BIF_ThemeColorBlend(TH_BACK, TH_GRID, dx/60.0);
587                                         drawgrid_draw(wx, wy, x, y, dx);
588                                         BIF_ThemeColor(TH_GRID);
589                                         drawgrid_draw(wx, wy, x, y, dx*sublines);
590                                 }
591                         }
592                         else {
593                                 BIF_ThemeColorBlend(TH_BACK, TH_GRID, dx/60.0);
594                                 drawgrid_draw(wx, wy, x, y, dx);
595                                 BIF_ThemeColor(TH_GRID);                                
596                                 drawgrid_draw(wx, wy, x, y, dx*sublines);
597                         }
598                 }
599                 else {
600                         BIF_ThemeColorBlend(TH_BACK, TH_GRID, dx/60.0);
601                         drawgrid_draw(wx, wy, x, y, dx);
602                         BIF_ThemeColor(TH_GRID);
603                         drawgrid_draw(wx, wy, x, y, dx*sublines);
604                 }
605         }
606
607         x+= (wx); 
608         y+= (wy);
609         BIF_GetThemeColor3ubv(TH_GRID, col);
610
611         setlinestyle(0);
612         
613         /* center cross */
614         if(G.vd->view==3) make_axis_color(col, col2, 'y');
615         else make_axis_color(col, col2, 'x');
616         glColor3ubv((GLubyte *)col2);
617         
618         fdrawline(0.0,  y,  (float)curarea->winx,  y); 
619         
620         if(G.vd->view==7) make_axis_color(col, col2, 'y');
621         else make_axis_color(col, col2, 'z');
622         glColor3ubv((GLubyte *)col2);
623
624         fdrawline(x, 0.0, x, (float)curarea->winy); 
625
626         glDepthMask(1);         // enable write in zbuffer
627         persp(PERSP_VIEW);
628 }
629
630
631
632 static void drawfloor(void)
633 {
634         View3D *vd;
635         float vert[3], grid;
636         int a, gridlines, emphasise;
637         char col[3], col2[3];
638         short draw_line = 0;
639                 
640         vd= curarea->spacedata.first;
641
642         vert[2]= 0.0;
643
644         if(vd->gridlines<3) return;
645         
646         if(G.vd->zbuf && G.obedit) glDepthMask(0);      // for zbuffer-select
647         
648         gridlines= vd->gridlines/2;
649         grid= gridlines*vd->grid;
650         
651         BIF_GetThemeColor3ubv(TH_GRID, col);
652         BIF_GetThemeColor3ubv(TH_BACK, col2);
653         
654         /* emphasise division lines lighter instead of darker, if background is darker than grid */
655         if ( ((col[0]+col[1]+col[2])/3+10) > (col2[0]+col2[1]+col2[2])/3 )
656                 emphasise = 20;
657         else
658                 emphasise = -10;
659         
660         /* draw the Y axis and/or grid lines */
661         for(a= -gridlines;a<=gridlines;a++) {
662                 if(a==0) {
663                         /* check for the 'show Y axis' preference */
664                         if (vd->gridflag & V3D_SHOW_Y) { 
665                                 make_axis_color(col, col2, 'y');
666                                 glColor3ubv((GLubyte *)col2);
667                                 
668                                 draw_line = 1;
669                         } else if (vd->gridflag & V3D_SHOW_FLOOR) {
670                                 BIF_ThemeColorShade(TH_GRID, emphasise);
671                         } else {
672                                 draw_line = 0;
673                         }
674                 } else {
675                         /* check for the 'show grid floor' preference */
676                         if (vd->gridflag & V3D_SHOW_FLOOR) {
677                                 if( (a % 10)==0) {
678                                         BIF_ThemeColorShade(TH_GRID, emphasise);
679                                 }
680                                 else BIF_ThemeColorShade(TH_GRID, 10);
681                                 
682                                 draw_line = 1;
683                         } else {
684                                 draw_line = 0;
685                         }
686                 }
687                 
688                 if (draw_line) {
689                         glBegin(GL_LINE_STRIP);
690                 vert[0]= a*vd->grid;
691                 vert[1]= grid;
692                 glVertex3fv(vert);
693                 vert[1]= -grid;
694                 glVertex3fv(vert);
695                         glEnd();
696                 }
697         }
698         
699         /* draw the X axis and/or grid lines */
700         for(a= -gridlines;a<=gridlines;a++) {
701                 if(a==0) {
702                         /* check for the 'show X axis' preference */
703                         if (vd->gridflag & V3D_SHOW_X) { 
704                                 make_axis_color(col, col2, 'x');
705                                 glColor3ubv((GLubyte *)col2);
706                                 
707                                 draw_line = 1;
708                         } else if (vd->gridflag & V3D_SHOW_FLOOR) {
709                                 BIF_ThemeColorShade(TH_GRID, emphasise);
710                         } else {
711                                 draw_line = 0;
712                         }
713                 } else {
714                         /* check for the 'show grid floor' preference */
715                         if (vd->gridflag & V3D_SHOW_FLOOR) {
716                                 if( (a % 10)==0) {
717                                         BIF_ThemeColorShade(TH_GRID, emphasise);
718                                 }
719                                 else BIF_ThemeColorShade(TH_GRID, 10);
720                                 
721                                 draw_line = 1;
722                         } else {
723                                 draw_line = 0;
724                         }
725                 }
726                 
727                 if (draw_line) {
728                         glBegin(GL_LINE_STRIP);
729                 vert[1]= a*vd->grid;
730                 vert[0]= grid;
731                 glVertex3fv(vert );
732                 vert[0]= -grid;
733                 glVertex3fv(vert);
734                         glEnd();
735                 }
736         }
737         
738         /* draw the Z axis line */      
739         /* check for the 'show Z axis' preference */
740         if (vd->gridflag & V3D_SHOW_Z) {
741                 make_axis_color(col, col2, 'z');
742                 glColor3ubv((GLubyte *)col2);
743                 
744                 glBegin(GL_LINE_STRIP);
745                 vert[0]= 0;
746                 vert[1]= 0;
747                 vert[2]= grid;
748                 glVertex3fv(vert );
749                 vert[2]= -grid;
750                 glVertex3fv(vert);
751                 glEnd();
752         }
753
754         if(G.vd->zbuf && G.obedit) glDepthMask(1);      
755
756 }
757
758 static void drawcursor(View3D *v3d)
759 {
760         short mx,my,co[2];
761         int flag;
762         
763         /* we dont want the clipping for cursor */
764         flag= v3d->flag;
765         v3d->flag= 0;
766         project_short( give_cursor(), co);
767         v3d->flag= flag;
768         
769         mx = co[0];
770         my = co[1];
771
772         if(mx!=IS_CLIPPED) {
773                 setlinestyle(0); 
774                 cpack(0xFF);
775                 circ((float)mx, (float)my, 10.0);
776                 setlinestyle(4); 
777                 cpack(0xFFFFFF);
778                 circ((float)mx, (float)my, 10.0);
779                 setlinestyle(0);
780                 cpack(0x0);
781                 
782                 sdrawline(mx-20, my, mx-5, my);
783                 sdrawline(mx+5, my, mx+20, my);
784                 sdrawline(mx, my-20, mx, my-5);
785                 sdrawline(mx, my+5, mx, my+20);
786         }
787 }
788
789 /* ********* custom clipping *********** */
790
791 static void view3d_draw_clipping(View3D *v3d)
792 {
793         BoundBox *bb= v3d->clipbb;
794         
795         BIF_ThemeColorShade(TH_BACK, -8);
796         
797         glBegin(GL_QUADS);
798
799         glVertex3fv(bb->vec[0]); glVertex3fv(bb->vec[1]); glVertex3fv(bb->vec[2]); glVertex3fv(bb->vec[3]);
800         glVertex3fv(bb->vec[0]); glVertex3fv(bb->vec[4]); glVertex3fv(bb->vec[5]); glVertex3fv(bb->vec[1]);
801         glVertex3fv(bb->vec[4]); glVertex3fv(bb->vec[7]); glVertex3fv(bb->vec[6]); glVertex3fv(bb->vec[5]);
802         glVertex3fv(bb->vec[7]); glVertex3fv(bb->vec[3]); glVertex3fv(bb->vec[2]); glVertex3fv(bb->vec[6]);
803         glVertex3fv(bb->vec[1]); glVertex3fv(bb->vec[5]); glVertex3fv(bb->vec[6]); glVertex3fv(bb->vec[2]);
804         glVertex3fv(bb->vec[7]); glVertex3fv(bb->vec[4]); glVertex3fv(bb->vec[0]); glVertex3fv(bb->vec[3]);
805         
806         glEnd();
807 }
808
809 void view3d_set_clipping(View3D *v3d)
810 {
811         double plane[4];
812         int a;
813         
814         for(a=0; a<4; a++) {
815                 QUATCOPY(plane, v3d->clip[a]);
816                 glClipPlane(GL_CLIP_PLANE0+a, plane);
817                 glEnable(GL_CLIP_PLANE0+a);
818         }
819 }
820
821 void view3d_clr_clipping(void)
822 {
823         int a;
824         
825         for(a=0; a<4; a++) {
826                 glDisable(GL_CLIP_PLANE0+a);
827         }
828 }
829
830 int view3d_test_clipping(View3D *v3d, float *vec)
831 {
832         /* vec in world coordinates, returns 1 if clipped */
833         float view[3];
834         
835         VECCOPY(view, vec);
836         
837         if(0.0f < v3d->clip[0][3] + INPR(view, v3d->clip[0]))
838                 if(0.0f < v3d->clip[1][3] + INPR(view, v3d->clip[1]))
839                         if(0.0f < v3d->clip[2][3] + INPR(view, v3d->clip[2]))
840                                 if(0.0f < v3d->clip[3][3] + INPR(view, v3d->clip[3]))
841                                         return 0;
842
843         return 1;
844 }
845
846 /* ********* end custom clipping *********** */
847
848 static void view3d_get_viewborder_size(View3D *v3d, float size_r[2])
849 {
850         float winmax= MAX2(v3d->area->winx, v3d->area->winy);
851         float aspect= (float) (G.scene->r.xsch*G.scene->r.xasp)/(G.scene->r.ysch*G.scene->r.yasp);
852
853         if(aspect>1.0) {
854                 size_r[0]= winmax;
855                 size_r[1]= winmax/aspect;
856         } else {
857                 size_r[0]= winmax*aspect;
858                 size_r[1]= winmax;
859         }
860 }
861
862 void calc_viewborder(struct View3D *v3d, rctf *viewborder_r)
863 {
864         float zoomfac, size[2];
865         float dx= 0.0f, dy= 0.0f;
866         
867         view3d_get_viewborder_size(v3d, size);
868
869                 /* magic zoom calculation, no idea what
870              * it signifies, if you find out, tell me! -zr
871                  */
872         /* simple, its magic dude!
873          * well, to be honest, this gives a natural feeling zooming
874          * with multiple keypad presses (ton)
875          */
876         
877         zoomfac= (M_SQRT2 + v3d->camzoom/50.0);
878         zoomfac= (zoomfac*zoomfac)*0.25;
879         
880         size[0]= size[0]*zoomfac;
881         size[1]= size[1]*zoomfac;
882
883                 /* center in window */
884         viewborder_r->xmin= 0.5*v3d->area->winx - 0.5*size[0];
885         viewborder_r->ymin= 0.5*v3d->area->winy - 0.5*size[1];
886         viewborder_r->xmax= viewborder_r->xmin + size[0];
887         viewborder_r->ymax= viewborder_r->ymin + size[1];
888         
889         dx= v3d->area->winx*G.vd->camdx*zoomfac*2.0f;
890         dy= v3d->area->winy*G.vd->camdy*zoomfac*2.0f;
891         
892         /* apply offset */
893         viewborder_r->xmin-= dx;
894         viewborder_r->ymin-= dy;
895         viewborder_r->xmax-= dx;
896         viewborder_r->ymax-= dy;
897         
898         if(v3d->camera && v3d->camera->type==OB_CAMERA) {
899                 Camera *cam= v3d->camera->data;
900                 float w = viewborder_r->xmax - viewborder_r->xmin;
901                 float h = viewborder_r->ymax - viewborder_r->ymin;
902                 float side = MAX2(w, h);
903
904                 viewborder_r->xmin+= cam->shiftx*side;
905                 viewborder_r->xmax+= cam->shiftx*side;
906                 viewborder_r->ymin+= cam->shifty*side;
907                 viewborder_r->ymax+= cam->shifty*side;
908         }
909 }
910
911 void view3d_set_1_to_1_viewborder(View3D *v3d)
912 {
913         float size[2];
914         int im_width= (G.scene->r.size*G.scene->r.xsch)/100;
915
916         view3d_get_viewborder_size(v3d, size);
917
918         v3d->camzoom= (sqrt(4.0*im_width/size[0]) - M_SQRT2)*50.0;
919         v3d->camzoom= CLAMPIS(v3d->camzoom, -30, 300);
920 }
921
922
923 static void drawviewborder_flymode(void)        
924 {
925         /* draws 4 edge brackets that frame the safe area where the
926         mouse can move during fly mode without spinning the view */
927         float x1, x2, y1, y2;
928         
929         x1= 0.45*(float)curarea->winx;
930         y1= 0.45*(float)curarea->winy;
931         x2= 0.55*(float)curarea->winx;
932         y2= 0.55*(float)curarea->winy;
933         cpack(0);
934         
935         
936         glBegin(GL_LINES);
937         /* bottom left */
938         glVertex2f(x1,y1); 
939         glVertex2f(x1,y1+5);
940         
941         glVertex2f(x1,y1); 
942         glVertex2f(x1+5,y1);
943
944         /* top right */
945         glVertex2f(x2,y2); 
946         glVertex2f(x2,y2-5);
947         
948         glVertex2f(x2,y2); 
949         glVertex2f(x2-5,y2);
950         
951         /* top left */
952         glVertex2f(x1,y2); 
953         glVertex2f(x1,y2-5);
954         
955         glVertex2f(x1,y2); 
956         glVertex2f(x1+5,y2);
957         
958         /* bottom right */
959         glVertex2f(x2,y1); 
960         glVertex2f(x2,y1+5);
961         
962         glVertex2f(x2,y1); 
963         glVertex2f(x2-5,y1);
964         glEnd();        
965 }
966
967
968 static void drawviewborder(void)
969 {
970         extern void gl_round_box(int mode, float minx, float miny, float maxx, float maxy, float rad);          // interface_panel.c
971         float fac, a;
972         float x1, x2, y1, y2;
973         float x3, y3, x4, y4;
974         rctf viewborder;
975         Camera *ca= NULL;
976
977         if(G.vd->camera==NULL)
978                 return;
979         if(G.vd->camera->type==OB_CAMERA)
980                 ca = G.vd->camera->data;
981         
982         calc_viewborder(G.vd, &viewborder);
983         x1= viewborder.xmin;
984         y1= viewborder.ymin;
985         x2= viewborder.xmax;
986         y2= viewborder.ymax;
987
988         /* passepartout, specified in camera edit buttons */
989         if (ca && (ca->flag & CAM_SHOWPASSEPARTOUT) && ca->passepartalpha > 0.000001) {
990                 if (ca->passepartalpha == 1.0) {
991                         glColor3f(0, 0, 0);
992                 } else {
993                         glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA );
994                         glEnable(GL_BLEND);
995                         glColor4f(0, 0, 0, ca->passepartalpha);
996                 }
997                 if (x1 > 0.0)
998                         glRectf(0.0, (float)curarea->winy, x1, 0.0);
999                 if (x2 < (float)curarea->winx)
1000                         glRectf(x2, (float)curarea->winy, (float)curarea->winx, 0.0);
1001                 if (y2 < (float)curarea->winy)
1002                         glRectf(x1, (float)curarea->winy, x2, y2);
1003                 if (y2 > 0.0) 
1004                         glRectf(x1, y1, x2, 0.0);
1005
1006                 glDisable(GL_BLEND);
1007         }
1008         
1009         /* edge */
1010         glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); 
1011         
1012         setlinestyle(0);
1013         BIF_ThemeColor(TH_BACK);
1014         glRectf(x1, y1, x2, y2);
1015         
1016         setlinestyle(3);
1017         BIF_ThemeColor(TH_WIRE);
1018         glRectf(x1, y1, x2, y2);
1019                 
1020         /* camera name - draw in highlighted text colour */
1021         if (ca && (ca->flag & CAM_SHOWNAME)) {
1022                 BIF_ThemeColor(TH_TEXT_HI);
1023                 glRasterPos2f(x1, y1-15);
1024                 
1025                 BMF_DrawString(G.font, G.vd->camera->id.name+2);
1026                 BIF_ThemeColor(TH_WIRE);
1027         }
1028
1029
1030         /* border */
1031         if(G.scene->r.mode & R_BORDER) {
1032                 
1033                 cpack(0);
1034                 x3= x1+ G.scene->r.border.xmin*(x2-x1);
1035                 y3= y1+ G.scene->r.border.ymin*(y2-y1);
1036                 x4= x1+ G.scene->r.border.xmax*(x2-x1);
1037                 y4= y1+ G.scene->r.border.ymax*(y2-y1);
1038                 
1039                 cpack(0x4040FF);
1040                 glRectf(x3,  y3,  x4,  y4); 
1041         }
1042
1043         /* safety border */
1044         if (ca && (ca->flag & CAM_SHOWTITLESAFE)) {
1045                 fac= 0.1;
1046                 
1047                 a= fac*(x2-x1);
1048                 x1+= a; 
1049                 x2-= a;
1050         
1051                 a= fac*(y2-y1);
1052                 y1+= a;
1053                 y2-= a;
1054         
1055                 BIF_ThemeColorBlendShade(TH_WIRE, TH_BACK, 0.25, 0);
1056                 
1057                 uiSetRoundBox(15);
1058                 gl_round_box(GL_LINE_LOOP, x1, y1, x2, y2, 12.0);
1059         }
1060         
1061         setlinestyle(0);
1062         glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
1063
1064 }
1065
1066 void backdrawview3d(int test)
1067 {
1068         struct Base *base;
1069
1070 /*for 2.43 release, don't use glext and just define the constant.
1071   this to avoid possibly breaking platforms before release.*/
1072 #ifndef GL_MULTISAMPLE_ARB
1073         #define GL_MULTISAMPLE_ARB      0x809D
1074 #endif
1075
1076 #ifdef GL_MULTISAMPLE_ARB
1077         int m;
1078 #endif
1079
1080         if(G.f & G_VERTEXPAINT || G.f & G_WEIGHTPAINT || G.f & G_TEXTUREPAINT);
1081         else if(G.obedit && G.vd->drawtype>OB_WIRE && (G.vd->flag & V3D_ZBUF_SELECT));
1082         else {
1083                 G.vd->flag &= ~V3D_NEEDBACKBUFDRAW;
1084                 return;
1085         }
1086
1087         if( !(G.vd->flag & V3D_NEEDBACKBUFDRAW) ) return;
1088
1089         if(test) {
1090                 if(qtest()) {
1091                         addafterqueue(curarea->win, BACKBUFDRAW, 1);
1092                         return;
1093                 }
1094         }
1095         persp(PERSP_VIEW);
1096
1097         /*Disable FSAA for backbuffer selection.  
1098         
1099         Only works if GL_MULTISAMPLE_ARB is defined by the header
1100         file, which is should be for every OS that supports FSAA.*/
1101
1102 #ifdef GL_MULTISAMPLE_ARB
1103         m = glIsEnabled(GL_MULTISAMPLE_ARB);
1104         if (m) glDisable(GL_MULTISAMPLE_ARB);
1105 #endif
1106
1107 #ifdef __APPLE__
1108         glDrawBuffer(GL_AUX0);
1109 #endif  
1110         if(G.vd->drawtype > OB_WIRE) G.vd->zbuf= TRUE;
1111         curarea->win_swap &= ~WIN_BACK_OK;
1112         
1113         glDisable(GL_DITHER);
1114
1115         glClearColor(0.0, 0.0, 0.0, 0.0); 
1116         if(G.vd->zbuf) {
1117                 glEnable(GL_DEPTH_TEST);
1118                 glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
1119         }
1120         else {
1121                 glClear(GL_COLOR_BUFFER_BIT);
1122                 glDisable(GL_DEPTH_TEST);
1123         }
1124         
1125         if(G.vd->flag & V3D_CLIPPING)
1126                 view3d_set_clipping(G.vd);
1127         
1128         G.f |= G_BACKBUFSEL;
1129         
1130         base= (G.scene->basact);
1131         if(base && (base->lay & G.vd->lay)) {
1132                 draw_object_backbufsel(base->object);
1133         }
1134
1135         G.vd->flag &= ~V3D_NEEDBACKBUFDRAW;
1136
1137         G.f &= ~G_BACKBUFSEL;
1138         G.vd->zbuf= FALSE; 
1139         glDisable(GL_DEPTH_TEST);
1140         glEnable(GL_DITHER);
1141
1142 #ifdef __APPLE__
1143         glDrawBuffer(GL_BACK); /* we were in aux buffers */
1144 #endif
1145
1146         if(G.vd->flag & V3D_CLIPPING)
1147                 view3d_clr_clipping();
1148
1149 #ifdef GL_MULTISAMPLE_ARB
1150         if (m) glEnable(GL_MULTISAMPLE_ARB);
1151 #endif
1152
1153         /* it is important to end a view in a transform compatible with buttons */
1154         persp(PERSP_WIN);  // set ortho
1155         bwin_scalematrix(curarea->win, G.vd->blockscale, G.vd->blockscale, G.vd->blockscale);
1156
1157 }
1158
1159 void check_backbuf(void)
1160 {
1161         if(G.vd->flag & V3D_NEEDBACKBUFDRAW)
1162                 backdrawview3d(0);
1163 }
1164
1165 /* samples a single pixel (copied from vpaint) */
1166 unsigned int sample_backbuf(int x, int y)
1167 {
1168         unsigned int col;
1169         
1170         if(x>=curarea->winx || y>=curarea->winy) return 0;
1171         x+= curarea->winrct.xmin;
1172         y+= curarea->winrct.ymin;
1173         
1174         check_backbuf(); // actually not needed for apple
1175
1176 #ifdef __APPLE__
1177         glReadBuffer(GL_AUX0);
1178 #endif
1179         glReadPixels(x,  y, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE,  &col);
1180         glReadBuffer(GL_BACK);  
1181         
1182         if(G.order==B_ENDIAN) SWITCH_INT(col);
1183         
1184         return framebuffer_to_index(col);
1185 }
1186
1187 /* reads full rect, converts indices */
1188 ImBuf *read_backbuf(short xmin, short ymin, short xmax, short ymax)
1189 {
1190         unsigned int *dr, *rd;
1191         struct ImBuf *ibuf, *ibuf1;
1192         int a;
1193         short xminc, yminc, xmaxc, ymaxc, xs, ys;
1194         
1195         /* clip */
1196         if(xmin<0) xminc= 0; else xminc= xmin;
1197         if(xmax>=curarea->winx) xmaxc= curarea->winx-1; else xmaxc= xmax;
1198         if(xminc > xmaxc) return NULL;
1199
1200         if(ymin<0) yminc= 0; else yminc= ymin;
1201         if(ymax>=curarea->winy) ymaxc= curarea->winy-1; else ymaxc= ymax;
1202         if(yminc > ymaxc) return NULL;
1203         
1204         ibuf= IMB_allocImBuf((xmaxc-xminc+1), (ymaxc-yminc+1), 32, IB_rect,0);
1205
1206         check_backbuf(); // actually not needed for apple
1207         
1208 #ifdef __APPLE__
1209         glReadBuffer(GL_AUX0);
1210 #endif
1211         glReadPixels(curarea->winrct.xmin+xminc, curarea->winrct.ymin+yminc, (xmaxc-xminc+1), (ymaxc-yminc+1), GL_RGBA, GL_UNSIGNED_BYTE, ibuf->rect);
1212         glReadBuffer(GL_BACK);  
1213
1214         if(G.order==B_ENDIAN) IMB_convert_rgba_to_abgr(ibuf);
1215
1216         a= (xmaxc-xminc+1)*(ymaxc-yminc+1);
1217         dr= ibuf->rect;
1218         while(a--) {
1219                 if(*dr) *dr= framebuffer_to_index(*dr);
1220                 dr++;
1221         }
1222         
1223         /* put clipped result back, if needed */
1224         if(xminc==xmin && xmaxc==xmax && yminc==ymin && ymaxc==ymax) 
1225                 return ibuf;
1226         
1227         ibuf1= IMB_allocImBuf( (xmax-xmin+1),(ymax-ymin+1),32,IB_rect,0);
1228         rd= ibuf->rect;
1229         dr= ibuf1->rect;
1230                 
1231         for(ys= ymin; ys<=ymax; ys++) {
1232                 for(xs= xmin; xs<=xmax; xs++, dr++) {
1233                         if( xs>=xminc && xs<=xmaxc && ys>=yminc && ys<=ymaxc) {
1234                                 *dr= *rd;
1235                                 rd++;
1236                         }
1237                 }
1238         }
1239         IMB_freeImBuf(ibuf);
1240         return ibuf1;
1241 }
1242
1243 /* smart function to sample a rect spiralling outside, nice for backbuf selection */
1244 unsigned int sample_backbuf_rect(short mval[2], int size, unsigned int min, unsigned int max, int *dist, short strict, unsigned int (*indextest)(unsigned int index))
1245 {
1246         struct ImBuf *buf;
1247         unsigned int *bufmin, *bufmax, *tbuf;
1248         int minx, miny;
1249         int a, b, rc, nr, amount, dirvec[4][2];
1250         int distance=0;
1251         unsigned int index = 0;
1252         short indexok = 0;      
1253
1254         amount= (size-1)/2;
1255
1256         minx = mval[0]-(amount+1);
1257         miny = mval[1]-(amount+1);
1258         buf = read_backbuf(minx, miny, minx+size-1, miny+size-1);
1259         if (!buf) return 0;
1260
1261         rc= 0;
1262         
1263         dirvec[0][0]= 1; dirvec[0][1]= 0;
1264         dirvec[1][0]= 0; dirvec[1][1]= -size;
1265         dirvec[2][0]= -1; dirvec[2][1]= 0;
1266         dirvec[3][0]= 0; dirvec[3][1]= size;
1267         
1268         bufmin = buf->rect;
1269         tbuf = buf->rect;
1270         bufmax = buf->rect + size*size;
1271         tbuf+= amount*size+ amount;
1272         
1273         for(nr=1; nr<=size; nr++) {
1274                 
1275                 for(a=0; a<2; a++) {
1276                         for(b=0; b<nr; b++, distance++) {
1277                                 if (*tbuf && *tbuf>=min && *tbuf<max) { //we got a hit
1278                                         if(strict){
1279                                                 indexok =  indextest(*tbuf - min+1);
1280                                                 if(indexok){
1281                                                         *dist= (short) sqrt( (float)distance   );
1282                                                         index = *tbuf - min+1;
1283                                                         goto exit; 
1284                                                 }                                               
1285                                         }
1286                                         else{
1287                                                 *dist= (short) sqrt( (float)distance ); // XXX, this distance is wrong - 
1288                                                 index = *tbuf - min+1; // messy yah, but indices start at 1
1289                                                 goto exit;
1290                                         }                       
1291                                 }
1292                                 
1293                                 tbuf+= (dirvec[rc][0]+dirvec[rc][1]);
1294                                 
1295                                 if(tbuf<bufmin || tbuf>=bufmax) {
1296                                         goto exit;
1297                                 }
1298                         }
1299                         rc++;
1300                         rc &= 3;
1301                 }
1302         }
1303
1304 exit:
1305         IMB_freeImBuf(buf);
1306         return index;
1307 }
1308
1309 void drawname(Object *ob)
1310 {
1311         cpack(0x404040);
1312         glRasterPos3f(0.0,  0.0,  0.0);
1313         
1314         BMF_DrawString(G.font, " ");
1315         BMF_DrawString(G.font, ob->id.name+2);
1316 }
1317
1318
1319 static void draw_selected_name(Object *ob)
1320 {
1321         char info[128];
1322         short offset=30;
1323
1324         if(ob->type==OB_ARMATURE) {
1325                 bArmature *arm= ob->data;
1326                 char *name= NULL;
1327                 
1328                 if(ob==G.obedit) {
1329                         EditBone *ebo;
1330                         for (ebo=G.edbo.first; ebo; ebo=ebo->next){
1331                                 if ((ebo->flag & BONE_ACTIVE) && (ebo->layer & arm->layer)) {
1332                                         name= ebo->name;
1333                                         break;
1334                                 }
1335                         }
1336                 }
1337                 else if(ob->pose && (ob->flag & OB_POSEMODE)) {
1338                         bPoseChannel *pchan;
1339                         for(pchan= ob->pose->chanbase.first; pchan; pchan= pchan->next) {
1340                                 if((pchan->bone->flag & BONE_ACTIVE) && (pchan->bone->layer & arm->layer)) {
1341                                         name= pchan->name;
1342                                         break;
1343                                 }
1344                         }
1345                 }
1346                 if(name)
1347                         sprintf(info, "(%d) %s %s", CFRA, ob->id.name+2, name);
1348                 else
1349                         sprintf(info, "(%d) %s", CFRA, ob->id.name+2);
1350         }
1351         else if(ob->type==OB_MESH) {
1352                 Key *key= NULL;
1353                 KeyBlock *kb = NULL;
1354                 char shapes[75];
1355                 
1356                 shapes[0] = 0;
1357                 key = ob_get_key(ob);
1358                 if(key){
1359                         kb = BLI_findlink(&key->block, ob->shapenr-1);
1360                         if(kb){
1361                                 sprintf(shapes, ": %s ", kb->name);             
1362                                 if(ob->shapeflag == OB_SHAPE_LOCK){
1363                                         sprintf(shapes, "%s (Pinned)",shapes);
1364                                 }
1365                         }
1366                 }
1367                 sprintf(info, "(%d) %s %s", CFRA, ob->id.name+2, shapes);
1368         }
1369         else sprintf(info, "(%d) %s", CFRA, ob->id.name+2);
1370
1371         BIF_ThemeColor(TH_TEXT_HI);
1372         if (U.uiflag & USER_SHOW_ROTVIEWICON)
1373                 offset = 14 + (U.rvisize * 2);
1374
1375         glRasterPos2i(offset,  10);
1376         BMF_DrawString(G.fonts, info);
1377 }
1378
1379
1380 /* Draw a live substitute of the view icon, which is always shown */
1381 static void draw_view_axis(void)
1382 {
1383         const float k = U.rvisize;   /* axis size */
1384         const float toll = 0.5;      /* used to see when view is quasi-orthogonal */
1385         const float start = k + 1.0; /* axis center in screen coordinates, x=y */
1386         float ydisp = 0.0;          /* vertical displacement to allow obj info text */
1387         
1388         /* rvibright ranges approx. from original axis icon color to gizmo color */
1389         float bright = U.rvibright / 15.0f;
1390         
1391         unsigned char col[3];
1392         unsigned char gridcol[3];
1393         float colf[3];
1394         
1395         float vec[4];
1396         float dx, dy;
1397         float h, s, v;
1398         
1399         BIF_GetThemeColor3ubv(TH_GRID, (char *)gridcol);
1400         
1401         /* X */
1402         vec[0] = vec[3] = 1;
1403         vec[1] = vec[2] = 0;
1404         QuatMulVecf(G.vd->viewquat, vec);
1405         
1406         make_axis_color((char *)gridcol, (char *)col, 'x');
1407         rgb_to_hsv(col[0]/255.0f, col[1]/255.0f, col[2]/255.0f, &h, &s, &v);
1408         s = s<0.5 ? s+0.5 : 1.0;
1409         v = 0.3;
1410         v = (v<1.0-(bright) ? v+bright : 1.0);
1411         hsv_to_rgb(h, s, v, colf, colf+1, colf+2);
1412         glColor3fv(colf);
1413         
1414         dx = vec[0] * k;
1415         dy = vec[1] * k;
1416         fdrawline(start, start + ydisp, start + dx, start + dy + ydisp);
1417         if (fabs(dx) > toll || fabs(dy) > toll) {
1418                 glRasterPos2i(start + dx + 2, start + dy + ydisp + 2);
1419                 BMF_DrawString(G.fonts, "x");
1420         }
1421         
1422         /* Y */
1423         vec[1] = vec[3] = 1;
1424         vec[0] = vec[2] = 0;
1425         QuatMulVecf(G.vd->viewquat, vec);
1426         
1427         make_axis_color((char *)gridcol, (char *)col, 'y');
1428         rgb_to_hsv(col[0]/255.0f, col[1]/255.0f, col[2]/255.0f, &h, &s, &v);
1429         s = s<0.5 ? s+0.5 : 1.0;
1430         v = 0.3;
1431         v = (v<1.0-(bright) ? v+bright : 1.0);
1432         hsv_to_rgb(h, s, v, colf, colf+1, colf+2);
1433         glColor3fv(colf);
1434         
1435         dx = vec[0] * k;
1436         dy = vec[1] * k;
1437         fdrawline(start, start + ydisp, start + dx, start + dy + ydisp);
1438         if (fabs(dx) > toll || fabs(dy) > toll) {
1439                 glRasterPos2i(start + dx + 2, start + dy + ydisp + 2);
1440                 BMF_DrawString(G.fonts, "y");
1441         }
1442         
1443         /* Z */
1444         vec[2] = vec[3] = 1;
1445         vec[1] = vec[0] = 0;
1446         QuatMulVecf(G.vd->viewquat, vec);
1447         
1448         make_axis_color((char *)gridcol, (char *)col, 'z');
1449         rgb_to_hsv(col[0]/255.0f, col[1]/255.0f, col[2]/255.0f, &h, &s, &v);
1450         s = s<0.5 ? s+0.5 : 1.0;
1451         v = 0.5;
1452         v = (v<1.0-(bright) ? v+bright : 1.0);
1453         hsv_to_rgb(h, s, v, colf, colf+1, colf+2);
1454         glColor3fv(colf);
1455         
1456         dx = vec[0] * k;
1457         dy = vec[1] * k;
1458         fdrawline(start, start + ydisp, start + dx, start + dy + ydisp);
1459         if (fabs(dx) > toll || fabs(dy) > toll) {
1460                 glRasterPos2i(start + dx + 2, start + dy + ydisp + 2);
1461                 BMF_DrawString(G.fonts, "z");
1462         }
1463 }
1464
1465         
1466 static void draw_view_icon(void)
1467 {
1468         BIFIconID icon;
1469         
1470         if(G.vd->view==7) icon= ICON_AXIS_TOP;
1471         else if(G.vd->view==1) icon= ICON_AXIS_FRONT;
1472         else if(G.vd->view==3) icon= ICON_AXIS_SIDE;
1473         else return ;
1474
1475         glEnable(GL_BLEND);
1476         glBlendFunc(GL_SRC_ALPHA,  GL_ONE_MINUS_SRC_ALPHA); 
1477         
1478         BIF_icon_draw(5.0, 5.0, icon);
1479         
1480         glDisable(GL_BLEND);
1481 }
1482
1483 static void draw_viewport_name(ScrArea *sa)
1484 {
1485         char *name = NULL;
1486         char *printable = NULL;
1487         
1488         switch(G.vd->view) {
1489                 case 1:
1490                         if (G.vd->persp & V3D_PERSP_DO_3D_PERSP)
1491                                 name = (G.vd->flag2 & V3D_OPP_DIRECTION_NAME) ? "Back Persp" : "Front Persp";
1492                         else
1493                                 name = (G.vd->flag2 & V3D_OPP_DIRECTION_NAME) ? "Back Ortho" : "Front Ortho";
1494                         break;
1495                 case 3:
1496                         if (G.vd->persp & V3D_PERSP_DO_3D_PERSP)
1497                                 name = (G.vd->flag2 & V3D_OPP_DIRECTION_NAME) ? "Left Persp" : "Right Persp";
1498                         else
1499                                 name = (G.vd->flag2 & V3D_OPP_DIRECTION_NAME) ? "Left Ortho" : "Right Ortho";
1500                         break;
1501                 case 7:
1502                         if (G.vd->persp & V3D_PERSP_DO_3D_PERSP)
1503                                 name = (G.vd->flag2 & V3D_OPP_DIRECTION_NAME) ? "Bottom Persp" : "Top Persp";
1504                         else
1505                                 name = (G.vd->flag2 & V3D_OPP_DIRECTION_NAME) ? "Bottom Ortho" : "Top Ortho";
1506                         break;
1507                 default:
1508                         if(G.vd->persp==V3D_PERSP_USE_THE_CAMERA) {
1509                                 if (G.vd->camera->type == OB_CAMERA) {
1510                                         Camera *cam;
1511                                         cam = G.vd->camera->data;
1512                                         name = (cam->type != CAM_ORTHO) ? "Camera Persp" : "Camera Ortho";
1513                                 } else {
1514                                         name = "Object as Camera";
1515                                 }
1516                         } else { 
1517                                 name = (G.vd->persp & V3D_PERSP_DO_3D_PERSP) ? "User Persp" : "User Ortho";
1518                         }
1519         }
1520         
1521         if (G.vd->localview) {
1522                 printable = malloc(strlen(name) + strlen(" (Local)_")); /* '_' gives space for '\0' */
1523                 strcpy(printable, name);
1524                 strcat(printable, " (Local)");
1525         } else {
1526                 printable = name;
1527         }
1528
1529         if (printable) {
1530                 BIF_ThemeColor(TH_TEXT_HI);
1531                 glRasterPos2i(10,  sa->winy-20);
1532                 BMF_DrawString(G.fonts, printable);
1533         }
1534
1535         if (G.vd->localview) {
1536                 free(printable);
1537         }
1538 }
1539
1540 /* ******************* view3d space & buttons ************** */
1541
1542
1543 /* temporal struct for storing transform properties */
1544 typedef struct {
1545         float ob_eul[4];        // used for quat too....
1546         float ob_scale[3]; // need temp space due to linked values
1547         float ob_dims[3];
1548         short link_scale;
1549         float ve_median[5];
1550         int curdef;
1551         float *defweightp;
1552 } TransformProperties;
1553
1554 /* is used for both read and write... */
1555 static void v3d_editvertex_buts(uiBlock *block, Object *ob, float lim)
1556 {
1557         EditMesh *em = G.editMesh;
1558         EditVert *eve, *evedef=NULL;
1559         EditEdge *eed;
1560         MDeformVert *dvert=NULL;
1561         TransformProperties *tfp= G.vd->properties_storage;
1562         float median[5];
1563         int tot, totw, totweight, totedge;
1564         char defstr[320];
1565         
1566         median[0]= median[1]= median[2]= median[3]= median[4]= 0.0;
1567         tot= totw= totweight= totedge= 0;
1568         defstr[0]= 0;
1569
1570         if(ob->type==OB_MESH) {         
1571                 eve= em->verts.first;
1572                 while(eve) {
1573                         if(eve->f & 1) {
1574                                 evedef= eve;
1575                                 tot++;
1576                                 VecAddf(median, median, eve->co);
1577                         }
1578                         eve= eve->next;
1579                 }
1580                 eed= em->edges.first;
1581                 while(eed) {
1582                         if((eed->f & SELECT)) {
1583                                 totedge++;
1584                                 median[3]+= eed->crease;
1585                         }
1586                         eed= eed->next;
1587                 }
1588
1589                 /* check for defgroups */
1590                 if(evedef)
1591                         dvert= CustomData_em_get(&em->vdata, evedef->data, CD_MDEFORMVERT);
1592                 if(tot==1 && dvert && dvert->totweight) {
1593                         bDeformGroup *dg;
1594                         int i, max=1, init=1;
1595                         char str[320];
1596                         
1597                         for (i=0; i<dvert->totweight; i++){
1598                                 dg = BLI_findlink (&ob->defbase, dvert->dw[i].def_nr);
1599                                 if(dg) {
1600                                         max+= snprintf(str, sizeof(str), "%s %%x%d|", dg->name, dvert->dw[i].def_nr); 
1601                                         if(max<320) strcat(defstr, str);
1602                                 }
1603                                 else printf("oh no!\n");
1604                                 if(tfp->curdef==dvert->dw[i].def_nr) {
1605                                         init= 0;
1606                                         tfp->defweightp= &dvert->dw[i].weight;
1607                                 }
1608                         }
1609                         
1610                         if(init) {      // needs new initialized 
1611                                 tfp->curdef= dvert->dw[0].def_nr;
1612                                 tfp->defweightp= &dvert->dw[0].weight;
1613                         }
1614                 }
1615         }
1616         else if(ob->type==OB_CURVE || ob->type==OB_SURF) {
1617                 extern ListBase editNurb; /* editcurve.c */
1618                 Nurb *nu;
1619                 BPoint *bp;
1620                 BezTriple *bezt;
1621                 int a;
1622                 
1623                 nu= editNurb.first;
1624                 while(nu) {
1625                         if((nu->type & 7)==CU_BEZIER) {
1626                                 bezt= nu->bezt;
1627                                 a= nu->pntsu;
1628                                 while(a--) {
1629                                         if(bezt->f2 & 1) {
1630                                                 VecAddf(median, median, bezt->vec[1]);
1631                                                 tot++;
1632                                                 median[4]+= bezt->weight;
1633                                                 totweight++;
1634                                         }
1635                                         else {
1636                                                 if(bezt->f1 & 1) {
1637                                                         VecAddf(median, median, bezt->vec[0]);
1638                                                         tot++;
1639                                                 }
1640                                                 if(bezt->f3 & 1) {
1641                                                         VecAddf(median, median, bezt->vec[2]);
1642                                                         tot++;
1643                                                 }
1644                                         }
1645                                         bezt++;
1646                                 }
1647                         }
1648                         else {
1649                                 bp= nu->bp;
1650                                 a= nu->pntsu*nu->pntsv;
1651                                 while(a--) {
1652                                         if(bp->f1 & 1) {
1653                                                 VecAddf(median, median, bp->vec);
1654                                                 median[3]+= bp->vec[3];
1655                                                 totw++;
1656                                                 tot++;
1657                                                 median[4]+= bp->weight;
1658                                                 totweight++;
1659                                         }
1660                                         bp++;
1661                                 }
1662                         }
1663                         nu= nu->next;
1664                 }
1665         }
1666         else if(ob->type==OB_LATTICE) {
1667                 BPoint *bp;
1668                 int a;
1669                 
1670                 a= editLatt->pntsu*editLatt->pntsv*editLatt->pntsw;
1671                 bp= editLatt->def;
1672                 while(a--) {
1673                         if(bp->f1 & SELECT) {
1674                                 VecAddf(median, median, bp->vec);
1675                                 tot++;
1676                                 median[4]+= bp->weight;
1677                                 totweight++;
1678                         }
1679                         bp++;
1680                 }
1681         }
1682         
1683         if(tot==0) return;
1684
1685         median[0] /= (float)tot;
1686         median[1] /= (float)tot;
1687         median[2] /= (float)tot;
1688         if(totedge) median[3] /= (float)totedge;
1689         else if(totw) median[3] /= (float)totw;
1690         if(totweight) median[4] /= (float)totweight;
1691         
1692         if(G.vd->flag & V3D_GLOBAL_STATS)
1693                 Mat4MulVecfl(ob->obmat, median);
1694         
1695         if(block) {     // buttons
1696         
1697                 uiBlockBeginAlign(block);
1698                 if((ob->parent) && (ob->partype == PARBONE)) {
1699                         uiDefButBitS(block, TOG, V3D_GLOBAL_STATS, REDRAWVIEW3D, "Global",              160, 135, 70, 19, &G.vd->flag, 0, 0, 0, 0, "Displays global values");
1700                         uiDefButBitS(block, TOGN, V3D_GLOBAL_STATS, REDRAWVIEW3D, "Local",              230, 135, 70, 19, &G.vd->flag, 0, 0, 0, 0, "Displays local values");
1701                 }
1702                 else {
1703                         uiDefButBitS(block, TOG, V3D_GLOBAL_STATS, REDRAWVIEW3D, "Global",              160, 150, 70, 19, &G.vd->flag, 0, 0, 0, 0, "Displays global values");
1704                         uiDefButBitS(block, TOGN, V3D_GLOBAL_STATS, REDRAWVIEW3D, "Local",              230, 150, 70, 19, &G.vd->flag, 0, 0, 0, 0, "Displays local values");
1705                 }
1706
1707                 memcpy(tfp->ve_median, median, sizeof(tfp->ve_median));
1708                 
1709                 uiBlockBeginAlign(block);
1710                 if(tot==1) {
1711                         uiDefButF(block, NUM, B_OBJECTPANELMEDIAN, "Vertex X:", 10, 110, 290, 19, &(tfp->ve_median[0]), -lim, lim, 10, 3, "");
1712                         uiDefButF(block, NUM, B_OBJECTPANELMEDIAN, "Vertex Y:", 10, 90, 290, 19, &(tfp->ve_median[1]), -lim, lim, 10, 3, "");
1713                         uiDefButF(block, NUM, B_OBJECTPANELMEDIAN, "Vertex Z:", 10, 70, 290, 19, &(tfp->ve_median[2]), -lim, lim, 10, 3, "");
1714                         if(totw==1)
1715                                 uiDefButF(block, NUM, B_OBJECTPANELMEDIAN, "Vertex W:", 10, 50, 290, 19, &(tfp->ve_median[3]), 0.01, 100.0, 10, 3, "");
1716                         uiBlockEndAlign(block);
1717         
1718                         if(defstr[0]) {
1719                                 uiDefBut(block, LABEL, 1, "Vertex Deform Groups",               10, 40, 290, 20, NULL, 0.0, 0.0, 0, 0, "");
1720
1721                                 uiBlockBeginAlign(block);
1722                                 uiDefButF(block, NUM, B_NOP, "Weight:",                 10, 20, 150, 19, tfp->defweightp, 0.0f, 1.0f, 10, 3, "Weight value");
1723                                 uiDefButI(block, MENU, REDRAWVIEW3D, defstr,    160, 20, 140, 19, &tfp->curdef, 0.0, 0.0, 0, 0, "Current Vertex Group");
1724                                 uiBlockEndAlign(block);
1725                         }
1726                         else if(totweight)
1727                                 uiDefButF(block, NUM, B_OBJECTPANELMEDIAN, "Weight:",   10, 20, 290, 19, &(tfp->ve_median[4]), 0.0, 1.0, 10, 3, "");
1728
1729                 }
1730                 else {
1731                         uiDefButF(block, NUM, B_OBJECTPANELMEDIAN, "Median X:", 10, 110, 290, 19, &(tfp->ve_median[0]), -lim, lim, 10, 3, "");
1732                         uiDefButF(block, NUM, B_OBJECTPANELMEDIAN, "Median Y:", 10, 90, 290, 19, &(tfp->ve_median[1]), -lim, lim, 10, 3, "");
1733                         uiDefButF(block, NUM, B_OBJECTPANELMEDIAN, "Median Z:", 10, 70, 290, 19, &(tfp->ve_median[2]), -lim, lim, 10, 3, "");
1734                         if(totw==tot)
1735                                 uiDefButF(block, NUM, B_OBJECTPANELMEDIAN, "Median W:", 10, 50, 290, 19, &(tfp->ve_median[3]), 0.01, 100.0, 10, 3, "");
1736                         uiBlockEndAlign(block);
1737                         if(totweight)
1738                                 uiDefButF(block, NUM, B_OBJECTPANELMEDIAN, "Weight:",   10, 20, 290, 19, &(tfp->ve_median[4]), 0.0, 1.0, 10, 3, "Weight is used for SoftBody Goal");
1739                 }
1740                 
1741                 if(totedge==1)
1742                         uiDefButF(block, NUM, B_OBJECTPANELMEDIAN, "Crease W:", 10, 30, 290, 19, &(tfp->ve_median[3]), 0.0, 1.0, 10, 3, "");
1743                 else if(totedge>1)
1744                         uiDefButF(block, NUM, B_OBJECTPANELMEDIAN, "Median Crease W:",  10, 30, 290, 19, &(tfp->ve_median[3]), 0.0, 1.0, 10, 3, "");
1745                 
1746         }
1747         else {  // apply
1748                 
1749                 if(G.vd->flag & V3D_GLOBAL_STATS) {
1750                         Mat4Invert(ob->imat, ob->obmat);
1751                         Mat4MulVecfl(ob->imat, median);
1752                         Mat4MulVecfl(ob->imat, tfp->ve_median);
1753                 }
1754                 VecSubf(median, tfp->ve_median, median);
1755                 median[3]= tfp->ve_median[3]-median[3];
1756                 median[4]= tfp->ve_median[4]-median[4];
1757                 
1758                 if(ob->type==OB_MESH) {
1759                         
1760                         eve= em->verts.first;
1761                         while(eve) {
1762                                 if(eve->f & 1) {
1763                                         VecAddf(eve->co, eve->co, median);
1764                                 }
1765                                 eve= eve->next;
1766                         }
1767                         
1768                         for(eed= em->edges.first; eed; eed= eed->next) {
1769                                 if(eed->f & SELECT) {
1770                                         /* ensure the median can be set to zero or one */
1771                                         if(tfp->ve_median[3]==0.0f) eed->crease= 0.0f;
1772                                         else if(tfp->ve_median[3]==1.0f) eed->crease= 1.0f;
1773                                         else {
1774                                                 eed->crease+= median[3];
1775                                                 CLAMP(eed->crease, 0.0, 1.0);
1776                                         }
1777                                 }
1778                         }
1779                         
1780                         recalc_editnormals();
1781                 }
1782                 else if(ob->type==OB_CURVE || ob->type==OB_SURF) {
1783                         extern ListBase editNurb; /* editcurve.c */
1784                         Nurb *nu;
1785                         BPoint *bp;
1786                         BezTriple *bezt;
1787                         int a;
1788                         
1789                         nu= editNurb.first;
1790                         while(nu) {
1791                                 if((nu->type & 7)==1) {
1792                                         bezt= nu->bezt;
1793                                         a= nu->pntsu;
1794                                         while(a--) {
1795                                                 if(bezt->f2 & 1) {
1796                                                         VecAddf(bezt->vec[0], bezt->vec[0], median);
1797                                                         VecAddf(bezt->vec[1], bezt->vec[1], median);
1798                                                         VecAddf(bezt->vec[2], bezt->vec[2], median);
1799                                                         bezt->weight+= median[4];
1800                                                 }
1801                                                 else {
1802                                                         if(bezt->f1 & 1) {
1803                                                                 VecAddf(bezt->vec[0], bezt->vec[0], median);
1804                                                         }
1805                                                         if(bezt->f3 & 1) {
1806                                                                 VecAddf(bezt->vec[2], bezt->vec[2], median);
1807                                                         }
1808                                                 }
1809                                                 bezt++;
1810                                         }
1811                                 }
1812                                 else {
1813                                         bp= nu->bp;
1814                                         a= nu->pntsu*nu->pntsv;
1815                                         while(a--) {
1816                                                 if(bp->f1 & 1) {
1817                                                         VecAddf(bp->vec, bp->vec, median);
1818                                                         bp->vec[3]+= median[3];
1819                                                         bp->weight+= median[4];
1820                                                 }
1821                                                 bp++;
1822                                         }
1823                                 }
1824                                 test2DNurb(nu);
1825                                 testhandlesNurb(nu); /* test for bezier too */
1826
1827                                 nu= nu->next;
1828                         }
1829                 }
1830                 else if(ob->type==OB_LATTICE) {
1831                         BPoint *bp;
1832                         int a;
1833                         
1834                         a= editLatt->pntsu*editLatt->pntsv*editLatt->pntsw;
1835                         bp= editLatt->def;
1836                         while(a--) {
1837                                 if(bp->f1 & SELECT) {
1838                                         VecAddf(bp->vec, bp->vec, median);
1839                                         bp->weight+= median[4];
1840                                 }
1841                                 bp++;
1842                         }
1843                 }
1844                 
1845                 BIF_undo_push("Transform properties");
1846         }
1847 }
1848
1849 /* assumes armature active */
1850 static void validate_bonebutton_cb(void *bonev, void *namev)
1851 {
1852         Object *ob= OBACT;
1853         
1854         if(ob && ob->type==OB_ARMATURE) {
1855                 Bone *bone= bonev;
1856                 char oldname[32], newname[32];
1857                 
1858                 /* need to be on the stack */
1859                 BLI_strncpy(newname, bone->name, 32);
1860                 BLI_strncpy(oldname, (char *)namev, 32);
1861                 /* restore */
1862                 BLI_strncpy(bone->name, oldname, 32);
1863                 
1864                 armature_bone_rename(ob->data, oldname, newname); // editarmature.c
1865                 allqueue(REDRAWALL, 0);
1866         }
1867 }
1868
1869 static void v3d_posearmature_buts(uiBlock *block, Object *ob, float lim)
1870 {
1871         uiBut *but;
1872         bArmature *arm;
1873         bPoseChannel *pchan;
1874         Bone *bone= NULL;
1875         TransformProperties *tfp= G.vd->properties_storage;
1876
1877         arm = get_armature(OBACT);
1878         if (!arm || !ob->pose) return;
1879
1880         for(pchan= ob->pose->chanbase.first; pchan; pchan= pchan->next) {
1881                 bone = pchan->bone;
1882                 if(bone && (bone->flag & BONE_ACTIVE) && (bone->layer & arm->layer))
1883                         break;
1884         }
1885         if (!pchan || !bone) return;
1886
1887         if((ob->parent) && (ob->partype == PARBONE))
1888                 but= uiDefBut (block, TEX, B_DIFF, "Bone:",                             160, 130, 140, 19, bone->name, 1, 31, 0, 0, "");
1889         else
1890                 but= uiDefBut(block, TEX, B_DIFF, "Bone:",                              160, 140, 140, 19, bone->name, 1, 31, 0, 0, "");
1891         uiButSetFunc(but, validate_bonebutton_cb, bone, NULL);
1892         
1893         QuatToEul(pchan->quat, tfp->ob_eul);
1894         tfp->ob_eul[0]*= 180.0/M_PI;
1895         tfp->ob_eul[1]*= 180.0/M_PI;
1896         tfp->ob_eul[2]*= 180.0/M_PI;
1897         
1898         uiBlockBeginAlign(block);
1899         uiDefIconButBitS(block, ICONTOG, OB_LOCK_LOCX, REDRAWVIEW3D, ICON_UNLOCKED,     10,140,20,19, &(pchan->protectflag), 0, 0, 0, 0, "Protects this value from being Transformed");
1900         uiDefButF(block, NUM, B_ARMATUREPANEL2, "LocX:",        30, 140, 120, 19, pchan->loc, -lim, lim, 100, 3, "");
1901         uiDefIconButBitS(block, ICONTOG, OB_LOCK_LOCY, REDRAWVIEW3D, ICON_UNLOCKED,     10,120,20,19, &(pchan->protectflag), 0, 0, 0, 0, "Protects this value from being Transformed");
1902         uiDefButF(block, NUM, B_ARMATUREPANEL2, "LocY:",        30, 120, 120, 19, pchan->loc+1, -lim, lim, 100, 3, "");
1903         uiDefIconButBitS(block, ICONTOG, OB_LOCK_LOCZ, REDRAWVIEW3D, ICON_UNLOCKED,     10,100,20,19, &(pchan->protectflag), 0, 0, 0, 0, "Protects this value from being Transformed");
1904         uiDefButF(block, NUM, B_ARMATUREPANEL2, "LocZ:",        30, 100, 120, 19, pchan->loc+2, -lim, lim, 100, 3, "");
1905
1906         uiBlockBeginAlign(block);
1907         uiDefIconButBitS(block, ICONTOG, OB_LOCK_ROTX, REDRAWVIEW3D, ICON_UNLOCKED,     10,70,20,19, &(pchan->protectflag), 0, 0, 0, 0, "Protects this value from being Transformed");
1908         uiDefButF(block, NUM, B_ARMATUREPANEL3, "RotX:",        30, 70, 120, 19, tfp->ob_eul, -1000.0, 1000.0, 100, 3, "");
1909         uiDefIconButBitS(block, ICONTOG, OB_LOCK_ROTY, REDRAWVIEW3D, ICON_UNLOCKED,     10,50,20,19, &(pchan->protectflag), 0, 0, 0, 0, "Protects this value from being Transformed");
1910         uiDefButF(block, NUM, B_ARMATUREPANEL3, "RotY:",        30, 50, 120, 19, tfp->ob_eul+1, -1000.0, 1000.0, 100, 3, "");
1911         uiDefIconButBitS(block, ICONTOG, OB_LOCK_ROTZ, REDRAWVIEW3D, ICON_UNLOCKED,     10,30,20,19, &(pchan->protectflag), 0, 0, 0, 0, "Protects this value from being Transformed");
1912         uiDefButF(block, NUM, B_ARMATUREPANEL3, "RotZ:",        30, 30, 120, 19, tfp->ob_eul+2, -1000.0, 1000.0, 100, 3, "");
1913         
1914         uiBlockBeginAlign(block);
1915         uiDefIconButBitS(block, ICONTOG, OB_LOCK_SCALEX, REDRAWVIEW3D, ICON_UNLOCKED,   160,70,20,19, &(pchan->protectflag), 0, 0, 0, 0, "Protects this value from being Transformed");
1916         uiDefButF(block, NUM, B_ARMATUREPANEL2, "ScaleX:",      180, 70, 120, 19, pchan->size, -lim, lim, 10, 3, "");
1917         uiDefIconButBitS(block, ICONTOG, OB_LOCK_SCALEY, REDRAWVIEW3D, ICON_UNLOCKED,   160,50,20,19, &(pchan->protectflag), 0, 0, 0, 0, "Protects this value from being Transformed");
1918         uiDefButF(block, NUM, B_ARMATUREPANEL2, "ScaleY:",      180, 50, 120, 19, pchan->size+1, -lim, lim, 10, 3, "");
1919         uiDefIconButBitS(block, ICONTOG, OB_LOCK_SCALEZ, REDRAWVIEW3D, ICON_UNLOCKED,   160,30,20,19, &(pchan->protectflag), 0, 0, 0, 0, "Protects this value from being Transformed");
1920         uiDefButF(block, NUM, B_ARMATUREPANEL2, "ScaleZ:",      180, 30, 120, 19, pchan->size+2, -lim, lim, 10, 3, "");
1921         uiBlockEndAlign(block);
1922 }
1923
1924 static void v3d_editarmature_buts(uiBlock *block, Object *ob, float lim)
1925 {
1926         bArmature *arm= G.obedit->data;
1927         EditBone *ebone;
1928         uiBut *but;
1929         TransformProperties *tfp= G.vd->properties_storage;
1930         
1931         ebone= G.edbo.first;
1932
1933         for (ebone = G.edbo.first; ebone; ebone=ebone->next){
1934                 if ((ebone->flag & BONE_ACTIVE) && (ebone->layer & arm->layer))
1935                         break;
1936         }
1937
1938         if (!ebone)
1939                 return;
1940         
1941         if((ob->parent) && (ob->partype == PARBONE))
1942                 but= uiDefBut(block, TEX, B_DIFF, "Bone:", 160, 130, 140, 19, ebone->name, 1, 31, 0, 0, "");
1943         else
1944                 but= uiDefBut(block, TEX, B_DIFF, "Bone:",                      160, 150, 140, 19, ebone->name, 1, 31, 0, 0, "");
1945         uiButSetFunc(but, validate_editbonebutton_cb, ebone, NULL);
1946
1947         uiBlockBeginAlign(block);
1948         uiDefButF(block, NUM, B_ARMATUREPANEL1, "RootX:",       10, 70, 140, 19, ebone->head, -lim, lim, 10, 3, "");
1949         uiDefButF(block, NUM, B_ARMATUREPANEL1, "RootY:",       10, 50, 140, 19, ebone->head+1, -lim, lim, 10, 3, "");
1950         uiDefButF(block, NUM, B_ARMATUREPANEL1, "RootZ:",       10, 30, 140, 19, ebone->head+2, -lim, lim, 10, 3, "");
1951         uiBlockBeginAlign(block);
1952         uiDefButF(block, NUM, B_ARMATUREPANEL1, "TipX:",        160, 70, 140, 19, ebone->tail, -lim, lim, 10, 3, "");
1953         uiDefButF(block, NUM, B_ARMATUREPANEL1, "TipY:",        160, 50, 140, 19, ebone->tail+1, -lim, lim, 10, 3, "");
1954         uiDefButF(block, NUM, B_ARMATUREPANEL1, "TipZ:",        160, 30, 140, 19, ebone->tail+2, -lim, lim, 10, 3, "");
1955         uiBlockEndAlign(block);
1956         
1957         tfp->ob_eul[0]= 180.0*ebone->roll/M_PI;
1958         uiDefButF(block, NUM, B_ARMATUREPANEL1, "Roll:",        10, 100, 140, 19, tfp->ob_eul, -lim, lim, 1000, 3, "");
1959
1960         uiBlockBeginAlign(block);
1961         uiDefButF(block, NUM, B_ARMATUREPANEL1, "TipRadius:",   10, 150, 140, 19, &ebone->rad_tail, 0, lim, 10, 3, "");
1962         if (ebone->parent && ebone->flag & BONE_CONNECTED )
1963                 uiDefButF(block, NUM, B_ARMATUREPANEL1, "HeadRadius:",  10, 130, 140, 19, &ebone->parent->rad_tail, 0, lim, 10, 3, "");
1964         else
1965                 uiDefButF(block, NUM, B_ARMATUREPANEL1, "HeadRadius:",  10, 130, 140, 19, &ebone->rad_head, 0, lim, 10, 3, "");
1966         uiBlockEndAlign(block);
1967 }
1968
1969 static void v3d_editmetaball_buts(uiBlock *block, Object *ob, float lim)
1970 {
1971         extern MetaElem *lastelem;
1972
1973         if(lastelem) {
1974                 uiBlockBeginAlign(block);
1975                 uiDefButF(block, NUM, B_RECALCMBALL, "LocX:", 10, 70, 140, 19, &lastelem->x, -lim, lim, 100, 3, "");
1976                 uiDefButF(block, NUM, B_RECALCMBALL, "LocY:", 10, 50, 140, 19, &lastelem->y, -lim, lim, 100, 3, "");
1977                 uiDefButF(block, NUM, B_RECALCMBALL, "LocZ:", 10, 30, 140, 19, &lastelem->z, -lim, lim, 100, 3, "");
1978
1979                 uiBlockBeginAlign(block);
1980                 if(lastelem->type!=MB_BALL)
1981                         uiDefButF(block, NUM, B_RECALCMBALL, "dx:", 160, 70, 140, 19, &lastelem->expx, 0, lim, 100, 3, "");
1982                 if((lastelem->type!=MB_BALL) && (lastelem->type!=MB_TUBE))
1983                         uiDefButF(block, NUM, B_RECALCMBALL, "dy:", 160, 50, 140, 19, &lastelem->expy, 0, lim, 100, 3, "");
1984                 if((lastelem->type==MB_ELIPSOID) || (lastelem->type==MB_CUBE))
1985                         uiDefButF(block, NUM, B_RECALCMBALL, "dz:", 160, 30, 140, 19, &lastelem->expz, 0, lim, 100, 3, "");
1986
1987                 uiBlockEndAlign(block); 
1988
1989                 uiBlockBeginAlign(block);
1990                 uiDefButF(block, NUM, B_RECALCMBALL, "Radius:", 10, 120, 140, 19, &lastelem->rad, 0, lim, 100, 3, "Size of the active metaball");
1991                 uiDefButF(block, NUM, B_RECALCMBALL, "Stiffness:", 10, 100, 140, 19, &lastelem->s, 0, 10, 100, 3, "Stiffness of the active metaball");
1992                 uiBlockEndAlign(block);
1993                 
1994                 uiDefButS(block, MENU, B_RECALCMBALL, "Type%t|Ball%x0|Tube%x4|Plane%x5|Elipsoid%x6|Cube%x7", 160, 120, 140, 19, &lastelem->type, 0.0, 0.0, 0, 0, "Set active element type");
1995                 
1996         }
1997 }
1998
1999 void do_viewbuts(unsigned short event)
2000 {
2001         BoundBox *bb;
2002         View3D *vd;
2003         Object *ob= OBACT;
2004         TransformProperties *tfp= G.vd->properties_storage;
2005         
2006         vd= G.vd;
2007         if(vd==NULL) return;
2008
2009         switch(event) {
2010                 
2011         case B_OBJECTPANEL:
2012                 DAG_object_flush_update(G.scene, ob, OB_RECALC_OB);
2013                 allqueue(REDRAWVIEW3D, 1);
2014                 break;
2015                 
2016         case B_OBJECTPANELROT:
2017                 if(ob) {
2018                         ob->rot[0]= M_PI*tfp->ob_eul[0]/180.0;
2019                         ob->rot[1]= M_PI*tfp->ob_eul[1]/180.0;
2020                         ob->rot[2]= M_PI*tfp->ob_eul[2]/180.0;
2021                         DAG_object_flush_update(G.scene, ob, OB_RECALC_OB);
2022                         allqueue(REDRAWVIEW3D, 1);
2023                 }
2024                 break;
2025
2026         case B_OBJECTPANELSCALE:
2027                 if(ob) {
2028
2029                         /* link scale; figure out which axis changed */
2030                         if (tfp->link_scale) {
2031                                 float ratio, tmp, max = 0.0;
2032                                 int axis;
2033                                 
2034                                 axis = 0;
2035                                 max = fabs(tfp->ob_scale[0] - ob->size[0]);
2036                                 tmp = fabs(tfp->ob_scale[1] - ob->size[1]);
2037                                 if (tmp > max) {
2038                                         axis = 1;
2039                                         max = tmp;
2040                                 }
2041                                 tmp = fabs(tfp->ob_scale[2] - ob->size[2]);
2042                                 if (tmp > max) {
2043                                         axis = 2;
2044                                         max = tmp;
2045                                 }
2046                         
2047                                 if (ob->size[axis] != tfp->ob_scale[axis]) {
2048                                         if (fabs(ob->size[axis]) > FLT_EPSILON) {
2049                                                 ratio = tfp->ob_scale[axis] / ob->size[axis];
2050                                                 ob->size[0] *= ratio;
2051                                                 ob->size[1] *= ratio;
2052                                                 ob->size[2] *= ratio;
2053                                         }
2054                                 }
2055                         }
2056                         else {
2057                                 VECCOPY(ob->size, tfp->ob_scale);
2058                                 
2059                         }
2060                         DAG_object_flush_update(G.scene, ob, OB_RECALC_OB);
2061                         allqueue(REDRAWVIEW3D, 1);
2062                 }
2063                 break;
2064
2065         case B_OBJECTPANELDIMS:
2066                 bb= object_get_boundbox(ob);
2067                 if(bb) {
2068                         float old_dims[3], scale[3], ratio, len[3];
2069                         int axis;
2070
2071                         Mat4ToSize(ob->obmat, scale);
2072
2073                         len[0] = bb->vec[4][0] - bb->vec[0][0];
2074                         len[1] = bb->vec[2][1] - bb->vec[0][1];
2075                         len[2] = bb->vec[1][2] - bb->vec[0][2];
2076
2077                         old_dims[0] = fabs(scale[0]) * len[0];
2078                         old_dims[1] = fabs(scale[1]) * len[1];
2079                         old_dims[2] = fabs(scale[2]) * len[2];
2080
2081                         /* for each axis changed */
2082                         for (axis = 0; axis<3; axis++) {
2083                                 if (fabs(old_dims[axis] - tfp->ob_dims[axis]) > 0.0001) {
2084                                         if (old_dims[axis] > 0.0) {
2085                                                 ratio = tfp->ob_dims[axis] / old_dims[axis]; 
2086                                                 if (tfp->link_scale) {
2087                                                         ob->size[0] *= ratio;
2088                                                         ob->size[1] *= ratio;
2089                                                         ob->size[2] *= ratio;
2090                                                         break;
2091                                                 }
2092                                                 else {
2093                                                         ob->size[axis] *= ratio;
2094                                                 }
2095                                         }
2096                                         else {
2097                                                 if (len[axis] > 0) {
2098                                                         ob->size[axis] = tfp->ob_dims[axis] / len[axis];
2099                                                 }
2100                                         }
2101                                 }
2102                         }
2103                         
2104                         /* prevent multiple B_OBJECTPANELDIMS events to keep scaling, cycling with TAB on buttons can cause that */
2105                         VECCOPY(tfp->ob_dims, old_dims);
2106                         
2107                         DAG_object_flush_update(G.scene, ob, OB_RECALC_OB);
2108                         allqueue(REDRAWVIEW3D, 1);
2109                 }
2110                 break;
2111         
2112         case B_OBJECTPANELMEDIAN:
2113                 if(ob) {
2114                         v3d_editvertex_buts(NULL, ob, 1.0);
2115                         DAG_object_flush_update(G.scene, ob, OB_RECALC_DATA);
2116                         allqueue(REDRAWVIEW3D, 1);
2117                 }
2118                 break;
2119                 
2120                 /* note; this case also used for parbone */
2121         case B_OBJECTPANELPARENT:
2122                 if(ob) {
2123                         if(ob->id.lib || test_parent_loop(ob->parent, ob) ) 
2124                                 ob->parent= NULL;
2125                         else {
2126                                 DAG_scene_sort(G.scene);
2127                                 DAG_object_flush_update(G.scene, ob, OB_RECALC_OB);
2128                         }
2129                         allqueue(REDRAWVIEW3D, 1);
2130                         allqueue(REDRAWBUTSOBJECT, 0);
2131                 }
2132                 break;
2133                 
2134         case B_ARMATUREPANEL1:
2135                 {
2136                         bArmature *arm= G.obedit->data;
2137                         EditBone *ebone, *child;
2138                         
2139                         for (ebone = G.edbo.first; ebone; ebone=ebone->next){
2140                                 if ((ebone->flag & BONE_ACTIVE) && (ebone->layer & arm->layer))
2141                                         break;
2142                         }
2143                         if (ebone) {
2144                                 ebone->roll= M_PI*tfp->ob_eul[0]/180.0;
2145                                 //      Update our parent
2146                                 if (ebone->parent && ebone->flag & BONE_CONNECTED){
2147                                         VECCOPY (ebone->parent->tail, ebone->head);
2148                                 }
2149                         
2150                                 //      Update our children if necessary
2151                                 for (child = G.edbo.first; child; child=child->next){
2152                                         if (child->parent == ebone && (child->flag & BONE_CONNECTED)){
2153                                                 VECCOPY (child->head, ebone->tail);
2154                                         }
2155                                 }
2156                                 if(arm->flag & ARM_MIRROR_EDIT) {
2157                                         EditBone *eboflip= armature_bone_get_mirrored(ebone);
2158                                         if(eboflip) {
2159                                                 eboflip->roll= -ebone->roll;
2160                                                 eboflip->head[0]= -ebone->head[0];
2161                                                 eboflip->tail[0]= -ebone->tail[0];
2162                                                 
2163                                                 //      Update our parent
2164                                                 if (eboflip->parent && eboflip->flag & BONE_CONNECTED){
2165                                                         VECCOPY (eboflip->parent->tail, eboflip->head);
2166                                                 }
2167                                                 
2168                                                 //      Update our children if necessary
2169                                                 for (child = G.edbo.first; child; child=child->next){
2170                                                         if (child->parent == eboflip && (child->flag & BONE_CONNECTED)){
2171                                                                 VECCOPY (child->head, eboflip->tail);
2172                                                         }
2173                                                 }
2174                                         }
2175                                 }
2176                                 
2177                                 allqueue(REDRAWVIEW3D, 1);
2178                         }
2179                 }
2180                 break;
2181         case B_ARMATUREPANEL3:  // rotate button on channel
2182                 {
2183                         bArmature *arm;
2184                         bPoseChannel *pchan;
2185                         Bone *bone;
2186                         float eul[3];
2187                         
2188                         arm = get_armature(OBACT);
2189                         if (!arm || !ob->pose) return;
2190                                 
2191                         for(pchan= ob->pose->chanbase.first; pchan; pchan= pchan->next) {
2192                                 bone = pchan->bone;
2193                                 if(bone && (bone->flag & BONE_ACTIVE) && (bone->layer & arm->layer))
2194                                         break;
2195                         }
2196                         if (!pchan) return;
2197                         
2198                         /* make a copy to eul[3], to allow TAB on buttons to work */
2199                         eul[0]= M_PI*tfp->ob_eul[0]/180.0;
2200                         eul[1]= M_PI*tfp->ob_eul[1]/180.0;
2201                         eul[2]= M_PI*tfp->ob_eul[2]/180.0;
2202                         EulToQuat(eul, pchan->quat);
2203                 }
2204                 /* no break, pass on */
2205         case B_ARMATUREPANEL2:
2206                 {
2207                         ob->pose->flag |= (POSE_LOCKED|POSE_DO_UNLOCK);
2208                         DAG_object_flush_update(G.scene, ob, OB_RECALC_DATA);
2209                         allqueue(REDRAWVIEW3D, 1);
2210                 }
2211                 break;
2212         }
2213 }
2214
2215
2216 static void view3d_panel_object(short cntrl)    // VIEW3D_HANDLER_OBJECT
2217 {
2218         uiBlock *block;
2219         uiBut *bt;
2220         Object *ob= OBACT;
2221         TransformProperties *tfp;
2222         float lim;
2223         static char hexcol[128];
2224         
2225         if(ob==NULL) return;
2226
2227         /* make sure we got storage */
2228         if(G.vd->properties_storage==NULL)
2229                 G.vd->properties_storage= MEM_callocN(sizeof(TransformProperties), "TransformProperties");
2230         tfp= G.vd->properties_storage;
2231         
2232         block= uiNewBlock(&curarea->uiblocks, "view3d_panel_object", UI_EMBOSS, UI_HELV, curarea->win);
2233         uiPanelControl(UI_PNL_SOLID | UI_PNL_CLOSE | cntrl);
2234         uiSetPanelHandler(VIEW3D_HANDLER_OBJECT);  // for close and esc
2235
2236         if(!uiNewPanel(curarea, block, "Transform Properties", "View3d", 10, 230, 318, 204))
2237                 return;
2238
2239         uiSetButLock(object_data_is_libdata(ob), ERROR_LIBDATA_MESSAGE);
2240         
2241         if(G.f & (G_VERTEXPAINT|G_TEXTUREPAINT|G_WEIGHTPAINT)) {
2242                 uiBlockSetFlag(block, UI_BLOCK_FRONTBUFFER);    // force old style frontbuffer draw
2243         }
2244         else {
2245                 bt= uiDefBut(block, TEX, B_IDNAME, "OB: ",      10,180,140,20, ob->id.name+2, 0.0, 21.0, 0, 0, "");
2246 #ifdef WITH_VERSE
2247                 if(ob->vnode) uiButSetFunc(bt, test_and_send_idbutton_cb, ob, ob->id.name);
2248                 else uiButSetFunc(bt, test_idbutton_cb, ob->id.name, NULL);
2249 #else
2250                 uiButSetFunc(bt, test_idbutton_cb, ob->id.name, NULL);
2251 #endif
2252
2253                 uiBlockBeginAlign(block);
2254                 uiDefIDPoinBut(block, test_obpoin_but, ID_OB, B_OBJECTPANELPARENT, "Par:", 160, 180, 140, 20, &ob->parent, "Parent Object"); 
2255                 if((ob->parent) && (ob->partype == PARBONE)) {
2256                         bt= uiDefBut(block, TEX, B_OBJECTPANELPARENT, "ParBone:", 160, 160, 140, 20, ob->parsubstr, 0, 30, 0, 0, "");
2257                         uiButSetCompleteFunc(bt, autocomplete_bone, (void *)ob->parent);
2258                 }
2259                 else {
2260                         strcpy(ob->parsubstr, "");
2261                 }
2262                 uiBlockEndAlign(block);
2263         }
2264
2265         lim= 10000.0f*MAX2(1.0, G.vd->grid);
2266
2267         if(ob==G.obedit) {
2268                 if(ob->type==OB_ARMATURE) v3d_editarmature_buts(block, ob, lim);
2269                 if(ob->type==OB_MBALL) v3d_editmetaball_buts(block, ob, lim);
2270                 else v3d_editvertex_buts(block, ob, lim);
2271         }
2272         else if(ob->flag & OB_POSEMODE) {
2273                 v3d_posearmature_buts(block, ob, lim);
2274         }
2275         else if(G.f & G_WEIGHTPAINT) {
2276                 uiNewPanelTitle(block, "Weight Paint Properties");
2277                 weight_paint_buttons(block);
2278         }
2279         else if(G.f & (G_VERTEXPAINT|G_TEXTUREPAINT)) {
2280                 extern VPaint Gvp;         /* from vpaint */
2281                 static float hsv[3], old[3];    // used as temp mem for picker
2282                 float *rgb= NULL;
2283                 ToolSettings *settings= G.scene->toolsettings;
2284
2285                 if(G.f & G_VERTEXPAINT) rgb= &Gvp.r;
2286                 else if(settings->imapaint.brush) rgb= settings->imapaint.brush->rgb;
2287                 
2288                 uiNewPanelTitle(block, "Paint Properties");
2289                 if (rgb)
2290                         /* 'f' is for floating panel */
2291                         uiBlockPickerButtons(block, rgb, hsv, old, hexcol, 'f', REDRAWBUTSEDIT);
2292         }
2293         else if(G.f & G_SCULPTMODE) {
2294                 uiNewPanelTitle(block, "Sculpt Properties");
2295                 sculptmode_draw_interface_tools(block,10,150);
2296         } else {
2297                 BoundBox *bb = NULL;
2298
2299                 uiBlockBeginAlign(block);
2300                 uiDefIconButBitS(block, ICONTOG, OB_LOCK_LOCX, REDRAWVIEW3D, ICON_UNLOCKED,     10,150,20,19, &(ob->protectflag), 0, 0, 0, 0, "Protects this value from being Transformed");
2301                 uiDefButF(block, NUM, B_OBJECTPANEL, "LocX:",           30, 150, 120, 19, &(ob->loc[0]), -lim, lim, 100, 3, "");
2302                 uiDefIconButBitS(block, ICONTOG, OB_LOCK_LOCY, REDRAWVIEW3D, ICON_UNLOCKED,     10,130,20,19, &(ob->protectflag), 0, 0, 0, 0, "Protects this value from being Transformed");
2303                 uiDefButF(block, NUM, B_OBJECTPANEL, "LocY:",           30, 130, 120, 19, &(ob->loc[1]), -lim, lim, 100, 3, "");
2304                 uiDefIconButBitS(block, ICONTOG, OB_LOCK_LOCZ, REDRAWVIEW3D, ICON_UNLOCKED,     10,110,20,19, &(ob->protectflag), 0, 0, 0, 0, "Protects this value from being Transformed");
2305                 uiDefButF(block, NUM, B_OBJECTPANEL, "LocZ:",           30, 110, 120, 19, &(ob->loc[2]), -lim, lim, 100, 3, "");
2306                 
2307                 tfp->ob_eul[0]= 180.0*ob->rot[0]/M_PI;
2308                 tfp->ob_eul[1]= 180.0*ob->rot[1]/M_PI;
2309                 tfp->ob_eul[2]= 180.0*ob->rot[2]/M_PI;
2310                 
2311                 uiBlockBeginAlign(block);
2312                 if ((ob->parent) && (ob->partype == PARBONE)) {
2313                         uiDefIconButBitS(block, ICONTOG, OB_LOCK_ROTX, REDRAWVIEW3D, ICON_UNLOCKED,     160,130,20,19, &(ob->protectflag), 0, 0, 0, 0, "Protects this value from being Transformed");
2314                         uiDefButF(block, NUM, B_OBJECTPANELROT, "RotX:",        180, 130, 120, 19, &(tfp->ob_eul[0]), -lim, lim, 1000, 3, "");
2315                         uiDefIconButBitS(block, ICONTOG, OB_LOCK_ROTY, REDRAWVIEW3D, ICON_UNLOCKED,     160,110,20,19, &(ob->protectflag), 0, 0, 0, 0, "Protects this value from being Transformed");
2316                         uiDefButF(block, NUM, B_OBJECTPANELROT, "RotY:",        180, 110, 120, 19, &(tfp->ob_eul[1]), -lim, lim, 1000, 3, "");
2317                         uiDefIconButBitS(block, ICONTOG, OB_LOCK_ROTZ, REDRAWVIEW3D, ICON_UNLOCKED,     160,90,20,19, &(ob->protectflag), 0, 0, 0, 0, "Protects this value from being Transformed");
2318                         uiDefButF(block, NUM, B_OBJECTPANELROT, "RotZ:",        180, 90, 120, 19, &(tfp->ob_eul[2]), -lim, lim, 1000, 3, "");
2319
2320                 }
2321                 else {
2322                         uiDefIconButBitS(block, ICONTOG, OB_LOCK_ROTX, REDRAWVIEW3D, ICON_UNLOCKED,     160,150,20,19, &(ob->protectflag), 0, 0, 0, 0, "Protects this value from being Transformed");
2323                         uiDefButF(block, NUM, B_OBJECTPANELROT, "RotX:",        180, 150, 120, 19, &(tfp->ob_eul[0]), -lim, lim, 1000, 3, "");
2324                         uiDefIconButBitS(block, ICONTOG, OB_LOCK_ROTY, REDRAWVIEW3D, ICON_UNLOCKED,     160,130,20,19, &(ob->protectflag), 0, 0, 0, 0, "Protects this value from being Transformed");
2325                         uiDefButF(block, NUM, B_OBJECTPANELROT, "RotY:",        180, 130, 120, 19, &(tfp->ob_eul[1]), -lim, lim, 1000, 3, "");
2326                         uiDefIconButBitS(block, ICONTOG, OB_LOCK_ROTZ, REDRAWVIEW3D, ICON_UNLOCKED,     160,110,20,19, &(ob->protectflag), 0, 0, 0, 0, "Protects this value from being Transformed");
2327                         uiDefButF(block, NUM, B_OBJECTPANELROT, "RotZ:",        180, 110, 120, 19, &(tfp->ob_eul[2]), -lim, lim, 1000, 3, "");
2328                 }
2329
2330                 tfp->ob_scale[0]= ob->size[0];
2331                 tfp->ob_scale[1]= ob->size[1];
2332                 tfp->ob_scale[2]= ob->size[2];
2333
2334                 uiBlockBeginAlign(block);
2335                 uiDefIconButBitS(block, ICONTOG, OB_LOCK_SCALEX, REDRAWVIEW3D, ICON_UNLOCKED,   10,80,20,19, &(ob->protectflag), 0, 0, 0, 0, "Protects this value from being Transformed");
2336                 uiDefButF(block, NUM, B_OBJECTPANELSCALE, "ScaleX:",            30, 80, 120, 19, &(tfp->ob_scale[0]), -lim, lim, 10, 3, "");
2337                 uiDefIconButBitS(block, ICONTOG, OB_LOCK_SCALEY, REDRAWVIEW3D, ICON_UNLOCKED,   10,60,20,19, &(ob->protectflag), 0, 0, 0, 0, "Protects this value from being Transformed");
2338                 uiDefButF(block, NUM, B_OBJECTPANELSCALE, "ScaleY:",            30, 60, 120, 19, &(tfp->ob_scale[1]), -lim, lim, 10, 3, "");
2339                 uiDefIconButBitS(block, ICONTOG, OB_LOCK_SCALEZ, REDRAWVIEW3D, ICON_UNLOCKED,   10,40,20,19, &(ob->protectflag), 0, 0, 0, 0, "Protects this value from being Transformed");
2340                 uiDefButF(block, NUM, B_OBJECTPANELSCALE, "ScaleZ:",            30, 40, 120, 19, &(tfp->ob_scale[2]), -lim, lim, 10, 3, "");
2341                 uiBlockEndAlign(block);
2342                 
2343                 uiDefButS(block, TOG, REDRAWVIEW3D, "Link Scale",               10, 10, 140, 19, &(tfp->link_scale), 0, 1, 0, 0, "Scale values vary proportionally in all directions");
2344
2345                 bb= object_get_boundbox(ob);
2346                 if (bb) {
2347                         float scale[3];
2348
2349                         Mat4ToSize(ob->obmat, scale);
2350
2351                         tfp->ob_dims[0] = fabs(scale[0]) * (bb->vec[4][0] - bb->vec[0][0]);
2352                         tfp->ob_dims[1] = fabs(scale[1]) * (bb->vec[2][1] - bb->vec[0][1]);
2353                         tfp->ob_dims[2] = fabs(scale[2]) * (bb->vec[1][2] - bb->vec[0][2]);
2354
2355                         uiBlockBeginAlign(block);
2356                         if ((ob->parent) && (ob->partype == PARBONE)) {
2357                                 uiDefButF(block, NUM, B_OBJECTPANELDIMS, "DimX:",               160, 60, 140, 19, &(tfp->ob_dims[0]), 0.0, lim, 10, 3, "Manipulate bounding box size");
2358                                 uiDefButF(block, NUM, B_OBJECTPANELDIMS, "DimY:",               160, 40, 140, 19, &(tfp->ob_dims[1]), 0.0, lim, 10, 3, "Manipulate bounding box size");
2359                                 uiDefButF(block, NUM, B_OBJECTPANELDIMS, "DimZ:",               160, 20, 140, 19, &(tfp->ob_dims[2]), 0.0, lim, 10, 3, "Manipulate bounding box size");
2360
2361                         }
2362                         else {
2363                                 uiDefButF(block, NUM, B_OBJECTPANELDIMS, "DimX:",               160, 80, 140, 19, &(tfp->ob_dims[0]), 0.0, lim, 10, 3, "Manipulate bounding box size");
2364                                 uiDefButF(block, NUM, B_OBJECTPANELDIMS, "DimY:",               160, 60, 140, 19, &(tfp->ob_dims[1]), 0.0, lim, 10, 3, "Manipulate bounding box size");
2365                                 uiDefButF(block, NUM, B_OBJECTPANELDIMS, "DimZ:",               160, 40, 140, 19, &(tfp->ob_dims[2]), 0.0, lim, 10, 3, "Manipulate bounding box size");
2366                         }
2367
2368                         uiBlockEndAlign(block);
2369                 }
2370         }
2371         uiClearButLock();
2372 }
2373
2374 static void view3d_panel_background(short cntrl)        // VIEW3D_HANDLER_BACKGROUND
2375 {
2376         uiBlock *block;
2377         View3D *vd;
2378         
2379         vd= G.vd;
2380
2381         block= uiNewBlock(&curarea->uiblocks, "view3d_panel_background", UI_EMBOSS, UI_HELV, curarea->win);
2382         uiPanelControl(UI_PNL_SOLID | UI_PNL_CLOSE  | cntrl);
2383         uiSetPanelHandler(VIEW3D_HANDLER_BACKGROUND);  // for close and esc
2384         if(uiNewPanel(curarea, block, "Background Image", "View3d", 340, 10, 318, 204)==0) return;
2385
2386         if(G.f & G_VERTEXPAINT || G.f & G_WEIGHTPAINT || G.f & G_TEXTUREPAINT) {
2387                 uiBlockSetFlag(block, UI_BLOCK_FRONTBUFFER);    // force old style frontbuffer draw
2388         }
2389         
2390         if(vd->flag & V3D_DISPBGPIC) {
2391                 if(vd->bgpic==NULL) {
2392                         vd->bgpic= MEM_callocN(sizeof(BGpic), "bgpic");
2393                         vd->bgpic->size= 5.0;
2394                         vd->bgpic->blend= 0.5;
2395                         vd->bgpic->iuser.fie_ima= 2;
2396                         vd->bgpic->iuser.ok= 1;
2397                 }
2398         }
2399         
2400         if(!(vd->flag & V3D_DISPBGPIC)) {
2401                 uiDefButBitS(block, TOG, V3D_DISPBGPIC, B_REDR, "Use Background Image", 10, 180, 150, 20, &vd->flag, 0, 0, 0, 0, "Display an image in the background of this 3D View");
2402                 uiDefBut(block, LABEL, 1, " ",  160, 180, 150, 20, NULL, 0.0, 0.0, 0, 0, "");
2403         }
2404         else {
2405                 uiBlockBeginAlign(block);
2406                 uiDefButBitS(block, TOG, V3D_DISPBGPIC, B_REDR, "Use", 10, 225, 50, 20, &vd->flag, 0, 0, 0, 0, "Display an image in the background of this 3D View");
2407                 uiDefButF(block, NUMSLI, B_REDR, "Blend:",      60, 225, 150, 20, &vd->bgpic->blend, 0.0,1.0, 0, 0, "Set the transparency of the background image");
2408                 uiDefButF(block, NUM, B_REDR, "Size:",          210, 225, 100, 20, &vd->bgpic->size, 0.1, 250.0*vd->grid, 100, 0, "Set the size (width) of the background image");
2409
2410                 uiDefButF(block, NUM, B_REDR, "X Offset:",      10, 205, 150, 20, &vd->bgpic->xof, -250.0*vd->grid,250.0*vd->grid, 10, 2, "Set the horizontal offset of the background image");
2411                 uiDefButF(block, NUM, B_REDR, "Y Offset:",      160, 205, 150, 20, &vd->bgpic->yof, -250.0*vd->grid,250.0*vd->grid, 10, 2, "Set the vertical offset of the background image");
2412                 
2413                 uiblock_image_panel(block, &vd->bgpic->ima, &vd->bgpic->iuser, B_REDR, B_REDR);
2414         }
2415 }
2416
2417
2418 static void view3d_panel_properties(short cntrl)        // VIEW3D_HANDLER_SETTINGS
2419 {
2420         uiBlock *block;
2421         View3D *vd;
2422         float *curs;
2423         
2424         vd= G.vd;
2425
2426         block= uiNewBlock(&curarea->uiblocks, "view3d_panel_properties", UI_EMBOSS, UI_HELV, curarea->win);
2427         uiPanelControl(UI_PNL_SOLID | UI_PNL_CLOSE  | cntrl);
2428         uiSetPanelHandler(VIEW3D_HANDLER_PROPERTIES);  // for close and esc
2429         if(uiNewPanel(curarea, block, "View Properties", "View3d", 340, 30, 318, 254)==0) return;
2430
2431         /* to force height */
2432         uiNewPanelHeight(block, 264);
2433
2434         if(G.f & (G_VERTEXPAINT|G_FACESELECT|G_TEXTUREPAINT|G_WEIGHTPAINT)) {
2435                 uiBlockSetFlag(block, UI_BLOCK_FRONTBUFFER);    // force old style frontbuffer draw
2436         }
2437
2438         uiDefBut(block, LABEL, 1, "Grid:",                                      10, 220, 150, 19, NULL, 0.0, 0.0, 0, 0, "");
2439         uiBlockBeginAlign(block);
2440         uiDefButF(block, NUM, REDRAWVIEW3D, "Spacing:",         10, 200, 140, 19, &vd->grid, 0.001, 100.0, 10, 0, "Set the distance between grid lines");
2441         uiDefButS(block, NUM, REDRAWVIEW3D, "Lines:",           10, 180, 140, 19, &vd->gridlines, 0.0, 100.0, 100, 0, "Set the number of grid lines in perspective view");
2442         uiDefButS(block, NUM, REDRAWVIEW3D, "Divisions:",               10, 160, 140, 19, &vd->gridsubdiv, 0.0, 100.0, 100, 0, "Set the number of grid lines");
2443         uiBlockEndAlign(block);
2444
2445         uiDefBut(block, LABEL, 1, "3D Display:",                                                        160, 220, 150, 19, NULL, 0.0, 0.0, 0, 0, "");
2446         uiDefButBitS(block, TOG, V3D_SHOW_FLOOR, REDRAWVIEW3D, "Grid Floor",160, 200, 150, 19, &vd->gridflag, 0, 0, 0, 0, "Show the grid floor in free camera mode");
2447         uiDefButBitS(block, TOG, V3D_SHOW_X, REDRAWVIEW3D, "X Axis",            160, 176, 48, 19, &vd->gridflag, 0, 0, 0, 0, "Show the X Axis line");
2448         uiDefButBitS(block, TOG, V3D_SHOW_Y, REDRAWVIEW3D, "Y Axis",            212, 176, 48, 19, &vd->gridflag, 0, 0, 0, 0, "Show the Y Axis line");
2449         uiDefButBitS(block, TOG, V3D_SHOW_Z, REDRAWVIEW3D, "Z Axis",            262, 176, 48, 19, &vd->gridflag, 0, 0, 0, 0, "Show the Z Axis line");
2450
2451         uiDefBut(block, LABEL, 1, "View Camera:",                       10, 140, 140, 19, NULL, 0.0, 0.0, 0, 0, "");
2452         
2453         uiDefButF(block, NUM, REDRAWVIEW3D, "Lens:",            10, 120, 140, 19, &vd->lens, 10.0, 120.0, 100, 0, "The lens angle in perspective view");
2454         uiBlockBeginAlign(block);
2455         uiDefButF(block, NUM, REDRAWVIEW3D, "Clip Start:",      10, 96, 140, 19, &vd->near, vd->grid/100.0, 100.0, 10, 0, "Set the beginning of the range in which 3D objects are displayed (perspective view)");
2456         uiDefButF(block, NUM, REDRAWVIEW3D, "Clip End:",        10, 76, 140, 19, &vd->far, 1.0, 10000.0*vd->grid, 100, 0, "Set the end of the range in which 3D objects are displayed (perspective view)");
2457         uiBlockEndAlign(block);
2458
2459         uiDefBut(block, LABEL, 1, "3D Cursor:",                         160, 150, 140, 19, NULL, 0.0, 0.0, 0, 0, "");
2460
2461         uiBlockBeginAlign(block);
2462         curs= give_cursor();
2463         uiDefButF(block, NUM, REDRAWVIEW3D, "X:",                       160, 130, 150, 22, curs, -10000.0*vd->grid, 10000.0*vd->grid, 10, 0, "X co-ordinate of the 3D cursor");
2464         uiDefButF(block, NUM, REDRAWVIEW3D, "Y:",                       160, 108, 150, 22, curs+1, -10000.0*vd->grid, 10000.0*vd->grid, 10, 0, "Y co-ordinate of the 3D cursor");
2465         uiDefButF(block, NUM, REDRAWVIEW3D, "Z:",                       160, 86, 150, 22, curs+2, -10000.0*vd->grid, 10000.0*vd->grid, 10, 0, "Z co-ordinate of the 3D cursor");
2466         uiBlockEndAlign(block);
2467
2468         uiDefBut(block, LABEL, 1, "Display:",                           10, 50, 150, 19, NULL, 0.0, 0.0, 0, 0, "");
2469         
2470         uiBlockBeginAlign(block);
2471         uiDefButBitS(block, TOG, V3D_SELECT_OUTLINE, REDRAWVIEW3D, "Outline Selected", 10, 30, 140, 19, &vd->flag, 0, 0, 0, 0, "Highlight selected objects with an outline, in Solid, Shaded or Textured viewport shading modes");
2472         uiDefButBitS(block, TOG, V3D_DRAW_CENTERS, REDRAWVIEW3D, "All Object Centers", 10, 10, 140, 19, &vd->flag, 0, 0, 0, 0, "Draw the center points on all objects");
2473         uiDefButBitS(block, TOGN, V3D_HIDE_HELPLINES, REDRAWVIEW3D, "Relationship Lines", 10, -10, 140, 19, &vd->flag, 0, 0, 0, 0, "Draw dashed lines indicating Parent, Constraint, or Hook relationships");
2474         uiBlockEndAlign(block);
2475
2476         uiDefBut(block, LABEL, 1, "View Locking:",                              160, 50, 150, 19, NULL, 0.0, 0.0, 0, 0, "");
2477         uiBlockBeginAlign(block);
2478         uiDefIDPoinBut(block, test_obpoin_but, ID_OB, REDRAWVIEW3D, "Object:", 160, 30, 140, 19, &vd->ob_centre, "Lock view to center to this Object"); 
2479         uiDefBut(block, TEX, REDRAWVIEW3D, "Bone:",                                             160, 10, 140, 19, vd->ob_centre_bone, 1, 31, 0, 0, "If view locked to Object, use this Bone to lock to view to");
2480
2481 }
2482
2483 static void view3d_panel_preview(ScrArea *sa, short cntrl)      // VIEW3D_HANDLER_PREVIEW
2484 {
2485         uiBlock *block;
2486         View3D *v3d= sa->spacedata.first;
2487         int ofsx, ofsy;
2488         
2489         block= uiNewBlock(&sa->uiblocks, "view3d_panel_preview", UI_EMBOSS, UI_HELV, sa->win);
2490         uiPanelControl(UI_PNL_SOLID | UI_PNL_CLOSE | UI_PNL_SCALE | cntrl);
2491         uiSetPanelHandler(VIEW3D_HANDLER_PREVIEW);  // for close and esc
2492         
2493         ofsx= -150+(sa->winx/2)/v3d->blockscale;
2494         ofsy= -100+(sa->winy/2)/v3d->blockscale;
2495         if(uiNewPanel(sa, block, "Preview", "View3d", ofsx, ofsy, 300, 200)==0) return;
2496
2497         uiBlockSetDrawExtraFunc(block, BIF_view3d_previewdraw);
2498         
2499         if(G.scene->recalc & SCE_PRV_CHANGED) {
2500                 G.scene->recalc &= ~SCE_PRV_CHANGED;
2501                 //printf("found recalc\n");
2502                 BIF_view3d_previewrender_free(sa->spacedata.first);
2503                 BIF_preview_changed(0);
2504         }
2505 }
2506
2507
2508 static void view3d_blockhandlers(ScrArea *sa)
2509 {
2510         View3D *v3d= sa->spacedata.first;
2511         short a;
2512         
2513         /* warning; blocks need to be freed each time, handlers dont remove */
2514         uiFreeBlocksWin(&sa->uiblocks, sa->win);
2515         
2516         /*uv face-sel and wp mode when mixed with wire leave depth enabled causing
2517         models to draw over the UI */
2518         glDisable(GL_DEPTH_TEST); 
2519         
2520         for(a=0; a<SPACE_MAXHANDLER; a+=2) {
2521         
2522                 switch(v3d->blockhandler[a]) {
2523
2524                 case VIEW3D_HANDLER_PROPERTIES:
2525                         view3d_panel_properties(v3d->blockhandler[a+1]);
2526                         break;
2527                 case VIEW3D_HANDLER_BACKGROUND:
2528                         view3d_panel_background(v3d->blockhandler[a+1]);
2529                         break;
2530                 case VIEW3D_HANDLER_OBJECT:
2531                         view3d_panel_object(v3d->blockhandler[a+1]);
2532                         break;
2533                 case VIEW3D_HANDLER_PREVIEW:
2534                         view3d_panel_preview(sa, v3d->blockhandler[a+1]);
2535                         break;                  
2536                 }
2537                 /* clear action value for event */
2538                 v3d->blockhandler[a+1]= 0;
2539         }
2540         uiDrawBlocksPanels(sa, 0);
2541
2542 }
2543
2544 /* ****************** View3d afterdraw *************** */
2545
2546 typedef struct View3DAfter {
2547         struct View3DAfter *next, *prev;
2548         struct Base *base;
2549         int type;
2550 } View3DAfter;
2551
2552 /* temp storage of Objects that need to be drawn as last */
2553 void add_view3d_after(View3D *v3d, Base *base, int type)
2554 {
2555         View3DAfter *v3da= MEM_callocN(sizeof(View3DAfter), "View 3d after");
2556
2557         BLI_addtail(&v3d->afterdraw, v3da);
2558         v3da->base= base;
2559         v3da->type= type;
2560 }
2561
2562 /* clears zbuffer and draws it over */
2563 static void view3d_draw_xray(View3D *v3d, int flag)
2564 {
2565         View3DAfter *v3da, *next;
2566         int doit= 0;
2567         
2568         for(v3da= v3d->afterdraw.first; v3da; v3da= v3da->next)
2569                 if(v3da->type==V3D_XRAY) doit= 1;
2570         
2571         if(doit) {
2572                 if(v3d->zbuf) glClear(GL_DEPTH_BUFFER_BIT);
2573                 v3d->xray= TRUE;
2574                 
2575                 for(v3da= v3d->afterdraw.first; v3da; v3da= next) {
2576                         next= v3da->next;
2577                         if(v3da->type==V3D_XRAY) {
2578                                 draw_object(v3da->base, flag);
2579                                 BLI_remlink(&v3d->afterdraw, v3da);
2580                                 MEM_freeN(v3da);
2581                         }
2582                 }
2583                 v3d->xray= FALSE;
2584         }
2585 }
2586
2587 /* disables write in zbuffer and draws it over */
2588 static void view3d_draw_transp(View3D *v3d, int flag)
2589 {
2590         View3DAfter *v3da, *next;
2591
2592         glDepthMask(0);
2593         v3d->transp= TRUE;
2594                 
2595         for(v3da= v3d->afterdraw.first; v3da; v3da= next) {
2596                 next= v3da->next;
2597                 if(v3da->type==V3D_TRANSP) {
2598                         draw_object(v3da->base, flag);
2599                         BLI_remlink(&v3d->afterdraw, v3da);
2600                         MEM_freeN(v3da);
2601                 }
2602         }
2603         v3d->transp= FALSE;
2604
2605         glDepthMask(1);
2606
2607 }
2608
2609 /* *********************** */
2610
2611 /*
2612         In most cases call draw_dupli_objects,
2613         draw_dupli_objects_color was added because when drawing set dupli's
2614         we need to force the color
2615 */
2616 static void draw_dupli_objects_color(View3D *v3d, Base *base, int color)
2617 {       
2618         ListBase *lb;
2619         DupliObject *dob;
2620         Base tbase;
2621         BoundBox *bb= NULL;
2622         GLuint displist=0;
2623         short transflag, use_displist= -1;      /* -1 is initialize */
2624         char dt, dtx;
2625         
2626         if (base->object->restrictflag & OB_RESTRICT_VIEW) return;
2627         
2628         /* test if we can do a displist */
2629         if(base->object->transflag & OB_DUPLIGROUP)
2630                 use_displist= 0;
2631         
2632         tbase.flag= OB_FROMDUPLI|base->flag;
2633         lb= object_duplilist(G.scene, base->object);
2634
2635         for(dob= lb->first; dob; dob= dob->next) {
2636                 if(dob->no_draw);
2637                 else {
2638                         tbase.object= dob->ob;
2639                         
2640                         /* extra service: draw the duplicator in drawtype of parent */
2641                         dt= tbase.object->dt; tbase.object->dt= base->object->dt;
2642                         dtx= tbase.object->dtx; tbase.object->dtx= base->object->dtx;
2643                         
2644                         /* negative scale flag has to propagate */
2645                         transflag= tbase.object->transflag;
2646                         if(base->object->transflag & OB_NEG_SCALE)
2647                                 tbase.object->transflag ^= OB_NEG_SCALE;
2648                         
2649                         BIF_ThemeColorBlend(color, TH_BACK, 0.5);
2650                         
2651                         /* generate displist, test for new object */
2652                         if(use_displist==1 && dob->prev && dob->prev->ob!=dob->ob) {
2653                                 use_displist= -1;
2654                                 glDeleteLists(displist, 1);
2655                         }
2656                         /* generate displist */
2657                         if(use_displist == -1) {
2658                                 
2659                                 /* lamp drawing messes with matrices, could be handled smarter... but this works */
2660                                 if(dob->ob->type==OB_LAMP)
2661                                         use_displist= 0;
2662                                 else {
2663                                         /* disable boundbox check for list creation */
2664                                         object_boundbox_flag(dob->ob, OB_BB_DISABLED, 1);
2665                                         /* need this for next part of code */
2666                                         bb= object_get_boundbox(dob->ob);
2667                                         
2668                                         Mat4One(dob->ob->obmat);        /* obmat gets restored */
2669                                         
2670                                         displist= glGenLists(1);
2671                                         glNewList(displist, GL_COMPILE);
2672                                         draw_object(&tbase, DRAW_CONSTCOLOR);
2673                                         glEndList();
2674                                         
2675                                         use_displist= 1;
2676                                         object_boundbox_flag(dob->ob, OB_BB_DISABLED, 0);
2677                                 }
2678                         }
2679                         if(use_displist) {
2680                                 mymultmatrix(dob->mat);
2681                                 if(boundbox_clip(dob->mat, bb))
2682                                    glCallList(displist);
2683                                 myloadmatrix(G.vd->viewmat);
2684                         }
2685                         else {
2686                                 Mat4CpyMat4(dob->ob->obmat, dob->mat);
2687                                 draw_object(&tbase, DRAW_CONSTCOLOR);
2688                         }
2689                         
2690                         tbase.object->dt= dt;
2691                         tbase.object->dtx= dtx;
2692                         tbase.object->transflag= transflag;
2693                 }
2694         }
2695         
2696         /* Transp afterdraw disabled, afterdraw only stores base pointers, and duplis can be same obj */
2697         
2698         free_object_duplilist(lb);      /* does restore */
2699         
2700         if(use_displist)
2701                 glDeleteLists(displist, 1);
2702 }
2703
2704 static void draw_dupli_objects(View3D *v3d, Base *base)
2705 {
2706         /* define the color here so draw_dupli_objects_color can be called
2707          * from the set loop */
2708         
2709         int color= (base->flag & SELECT)?TH_SELECT:TH_WIRE;
2710         /* debug */
2711         if(base->object->dup_group && base->object->dup_group->id.us<1)
2712                 color= TH_REDALERT;
2713         
2714         draw_dupli_objects_color(v3d, base, color);
2715 }
2716
2717 void view3d_update_depths(View3D *v3d)
2718 {
2719         /* Create storage for, and, if necessary, copy depth buffer */
2720         if(!v3d->depths) v3d->depths= MEM_callocN(sizeof(ViewDepths),"ViewDepths");
2721         if(v3d->depths) {
2722                 ViewDepths *d= v3d->depths;
2723                 if(d->w != v3d->area->winx ||
2724                    d->h != v3d->area->winy ||
2725                    !d->depths) {
2726                         d->w= v3d->area->winx;
2727                         d->h= v3d->area->winy;
2728                         if(d->depths)
2729                                 MEM_freeN(d->depths);
2730                         d->depths= MEM_mallocN(sizeof(float)*d->w*d->h,"View depths");
2731                         d->damaged= 1;
2732                 }
2733                 
2734                 if(d->damaged) {
2735                         glReadPixels(v3d->area->winrct.xmin,v3d->area->winrct.ymin,d->w,d->h,
2736                                      GL_DEPTH_COMPONENT,GL_FLOAT, d->depths);
2737                         
2738                         glGetDoublev(GL_DEPTH_RANGE,d->depth_range);
2739                         
2740                         d->damaged= 0;
2741                 }
2742         }
2743 }
2744
2745 void drawview3dspace(ScrArea *sa, void *spacedata)
2746 {
2747         View3D *v3d= spacedata;
2748         Base *base;
2749         Object *ob;
2750         Scene *sce;
2751         char retopo, sculpt;
2752         Object *obact = OBACT;
2753         
2754         /* update all objects, ipos, matrices, displists, etc. Flags set by depgraph or manual, 
2755            no layer check here, gets correct flushed */
2756         /* sets first, we allow per definition current scene to have dependencies on sets */
2757         if(G.scene->set) {
2758                 for(SETLOOPER(G.scene->set, base))
2759                         object_handle_update(base->object);   // bke_object.h
2760         }
2761         for(base= G.scene->base.first; base; base= base->next)
2762                 object_handle_update(base->object);   // bke_object.h
2763         
2764         setwinmatrixview3d(sa->winx, sa->winy, NULL);   /* 0= no pick rect */
2765         setviewmatrixview3d();  /* note: calls where_is_object for camera... */
2766
2767         Mat4MulMat4(v3d->persmat, v3d->viewmat, sa->winmat);
2768         Mat4Invert(v3d->persinv, v3d->persmat);
2769         Mat4Invert(v3d->viewinv, v3d->viewmat);
2770
2771         /* calculate pixelsize factor once, is used for lamps and obcenters */
2772         {
2773                 float len1, len2, vec[3];
2774
2775                 VECCOPY(vec, v3d->persinv[0]);
2776                 len1= Normalize(vec);
2777                 VECCOPY(vec, v3d->persinv[1]);
2778                 len2= Normalize(vec);
2779                 
2780                 v3d->pixsize= 2.0f*(len1>len2?len1:len2);
2781                 
2782                 /* correct for window size */
2783                 if(sa->winx > sa->winy) v3d->pixsize/= (float)sa->winx;
2784                 else v3d->pixsize/= (float)sa->winy;
2785         }
2786         
2787         if(v3d->drawtype > OB_WIRE) {
2788                 if(G.f & G_SIMULATION)
2789                         glClearColor(0.0, 0.0, 0.0, 0.0); 
2790                 else {
2791                         float col[3];
2792                         BIF_GetThemeColor3fv(TH_BACK, col);
2793                         glClearColor(col[0], col[1], col[2], 0.0); 
2794                 }
2795                 glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
2796                 
2797                 glLoadIdentity();
2798         }
2799         else {
2800                 float col[3];
2801                 BIF_GetThemeColor3fv(TH_BACK, col);
2802                 glClearColor(col[0], col[1], col[2], 0.0);
2803                 glClear(GL_COLOR_BUFFER_BIT);
2804         }
2805         
2806         myloadmatrix(v3d->viewmat);
2807         persp(PERSP_STORE);  // store correct view for persp(PERSP_VIEW) calls
2808
2809         if(v3d->flag & V3D_CLIPPING)
2810                 view3d_draw_clipping(v3d);
2811         
2812         /* set zbuffer after we draw clipping region */
2813         if(v3d->drawtype > OB_WIRE) {
2814                 v3d->zbuf= TRUE;
2815                 glEnable(GL_DEPTH_TEST);
2816         }
2817         
2818         // needs to be done always, gridview is adjusted in drawgrid() now
2819         v3d->gridview= v3d->grid;
2820         
2821         if(v3d->view==0 || v3d->persp!=0) {
2822                 drawfloor();
2823                 if(v3d->persp==2) {
2824                         if(G.scene->world) {
2825                                 if(G.scene->world->mode & WO_STARS) {
2826                                         RE_make_stars(NULL, star_stuff_init_func, star_stuff_vertex_func,
2827                                                                   star_stuff_term_func);
2828                                 }
2829                         }
2830                         if(v3d->flag & V3D_DISPBGPIC) draw_bgpic();
2831                 }
2832         }
2833         else {
2834                 drawgrid();
2835
2836                 if(v3d->flag & V3D_DISPBGPIC) {
2837                         draw_bgpic();
2838                 }
2839         }
2840         
2841         if(v3d->flag & V3D_CLIPPING)
2842                 view3d_set_clipping(v3d);
2843         
2844         /* draw set first */
2845         if(G.scene->set) {
2846                 for(SETLOOPER(G.scene->set, base)) {
2847                         
2848                         if(v3d->lay & base->lay) {
2849                                 
2850                                 BIF_ThemeColorBlend(TH_WIRE, TH_BACK, 0.6f);
2851                                 draw_object(base, DRAW_CONSTCOLOR);
2852
2853                                 if(base->object->transflag & OB_DUPLI) {
2854                                         draw_dupli_objects_color(v3d, base, TH_WIRE);
2855                                 }
2856                         }
2857                 }
2858
2859                 /* Transp and X-ray afterdraw stuff */
2860                 view3d_draw_xray(v3d, DRAW_CONSTCOLOR); // clears zbuffer if it is used!
2861                 view3d_draw_transp(v3d, DRAW_CONSTCOLOR);
2862         }
2863         
2864         /* then draw not selected and the duplis, but skip editmode object */
2865         for(base= G.scene->base.first; base; base= base->next) {
2866                 if(v3d->lay & base->lay) {
2867                         
2868                         /* dupli drawing */
2869                         if(base->object->transflag & OB_DUPLI) {
2870                                 draw_dupli_objects(v3d, base);
2871                         }
2872                         if((base->flag & SELECT)==0) {
2873                                 if(base->object!=G.obedit) draw_object(base, 0);
2874                         }
2875                 }
2876         }
2877
2878         retopo= retopo_mesh_check() || retopo_curve_check();
2879         sculpt= (G.f & G_SCULPTMODE) && !G.obedit;
2880         if(retopo)
2881                 view3d_update_depths(v3d);
2882
2883         /* draw selected and editmode */
2884         for(base= G.scene->base.first; base; base= base->next) {
2885                 if(v3d->lay & base->lay) {
2886                         if (base->object==G.obedit || ( base->flag & SELECT) ) 
2887                                 draw_object(base, 0);
2888                 }
2889         }
2890
2891         if(!retopo && sculpt && !(obact && (obact->dtx & OB_DRAWXRAY)))
2892                 view3d_update_depths(v3d);
2893
2894         if(G.moving) {
2895                 BIF_drawConstraint();
2896                 if(G.obedit) BIF_drawPropCircle();      // only editmode has proportional edit
2897                 BIF_drawSnap();
2898         }
2899
2900         if(G.scene->radio) RAD_drawall(v3d->drawtype>=OB_SOLID);
2901         
2902         /* Transp and X-ray afterdraw stuff */
2903         view3d_draw_xray(v3d, 0);       // clears zbuffer if it is used!
2904         view3d_draw_transp(v3d, 0);
2905         
2906         if(!retopo && sculpt && (obact && (OBACT->dtx & OB_DRAWXRAY)))
2907                 view3d_update_depths(v3d);
2908         
2909         if(v3d->flag & V3D_CLIPPING)
2910                 view3d_clr_clipping();
2911         
2912         BIF_draw_manipulator(sa);
2913                 
2914         if(v3d->zbuf) {
2915                 v3d->zbuf= FALSE;
2916                 glDisable(GL_DEPTH_TEST);
2917         }
2918
2919         persp(PERSP_WIN);  // set ortho
2920
2921         /* Draw Sculpt Mode brush */
2922         if(!G.obedit && (G.f & G_SCULPTMODE) && area_is_active_area(v3d->area) && sculpt_session()) {
2923                 PropsetData *pd= sculpt_session()->propset;
2924                 short r1=100, r2=100, r3=100;
2925                 short mouse[2];
2926
2927                 if(sculpt_data()->flags & SCULPT_INPUT_SMOOTH)
2928                         sculpt_stroke_draw();
2929
2930                 if(pd) {
2931                         if(pd->mode == PropsetSize) {
2932                                 r1= sculptmode_brush()->size;
2933                                 r2= pd->origsize;
2934                                 r3= r1;
2935                         } else if(pd->mode == PropsetStrength) {
2936                                 r1= 200 - sculptmode_brush()->strength * 2;
2937                                 r2= 200;
2938                                 r3= 200;
2939                         } else if(pd->mode == PropsetTexRot) {
2940                                 r1= r2= 200;
2941                                 r3= 200;
2942                         }
2943                 
2944                         /* Draw brush with texture */
2945                         glEnable(GL_BLEND);
2946                         glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2947
2948                         glBindTexture(GL_TEXTURE_2D, pd->tex);
2949
2950                         glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
2951                         glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
2952                         
2953                         glPushMatrix();
2954                         glTranslatef(pd->origloc[0], pd->origloc[1], 0);
2955                         glRotatef(tex_angle(), 0, 0, 1);
2956
2957                         glEnable(GL_TEXTURE_2D);
2958                         glBegin(GL_QUADS);
2959                         glColor4f(0,0,0,1);
2960                         glTexCoord2f(0,0);
2961                         glVertex2f(-r3, -r3);
2962                         glTexCoord2f(1,0);
2963                         glVertex2f(r3, -r3);
2964                         glTexCoord2f(1,1);
2965                         glVertex2f(r3, r3);
2966                         glTexCoord2f(0,1);
2967                         glVertex2f(-r3, r3);
2968                         glEnd();
2969                         glDisable(GL_TEXTURE_2D);
2970                         
2971                         glPopMatrix();
2972
2973                         if(r1 != r2)
2974                                 fdrawXORcirc(pd->origloc[0], pd->origloc[1], r1);
2975                         fdrawXORcirc(pd->origloc[0], pd->origloc[1], r2);
2976                         
2977                         if(pd->mode == PropsetTexRot) {
2978                                 const float ang= pd->origtexrot * (M_PI/180.0f);
2979                                 getmouseco_areawin(mouse);
2980                                 sdrawXORline(pd->origloc[0], pd->origloc[1],
2981                                              pd->origloc[0]+200*cos(ang), pd->origloc[1]+200*sin(ang));
2982                                 sdrawXORline(pd->origloc[0], pd->origloc[1], mouse[0], mouse[1]);
2983                         }
2984                 }
2985                 else if(sculpt_data()->flags & SCULPT_DRAW_BRUSH) {
2986                         short csc[2], car[2];
2987                         getmouseco_sc(csc);
2988                         getmouseco_areawin(car);
2989                         if(csc[0] > v3d->area->winrct.xmin && 
2990                            csc[1] > v3d->area->winrct.ymin &&
2991                            csc[0] < v3d->area->winrct.xmax &&
2992                            csc[1] < v3d->area->winrct.ymax)
2993                                 fdrawXORcirc((float)car[0], (float)car[1], sculptmode_brush()->size);
2994                 }
2995         }
2996         retopo_draw_paint_lines();
2997
2998         if(v3d->persp>1) drawviewborder();
2999         if(v3d->flag2 & V3D_FLYMODE) drawviewborder_flymode();
3000         if(!(G.f & G_PLAYANIM)) drawcursor(v3d);
3001         if(U.uiflag & USER_SHOW_ROTVIEWICON)
3002                 draw_view_axis();
3003         else    
3004                 draw_view_icon();
3005         if(U.uiflag & USER_SHOW_VIEWPORTNAME)
3006                 draw_viewport_name(sa);
3007
3008         ob= OBACT;
3009         if(ob && (U.uiflag & USER_DRAWVIEWINFO)) 
3010                 draw_selected_name(ob);
3011         
3012         draw_area_emboss(sa);
3013         
3014         /* it is important to end a view in a transform compatible with buttons */
3015
3016         bwin_scalematrix(sa->win, v3d->blockscale, v3d->blockscale, v3d->blockscale);
3017         view3d_blockhandlers(sa);
3018
3019         sa->win_swap= WIN_BACK_OK;
3020         
3021         if(G.f & G_VERTEXPAINT || G.f & G_WEIGHTPAINT || G.f & G_TEXTUREPAINT) {
3022                 v3d->flag |= V3D_NEEDBACKBUFDRAW;
3023                 addafterqueue(sa->win, BACKBUFDRAW, 1);
3024         }
3025         // test for backbuf select
3026         if(G.obedit && v3d->drawtype>OB_WIRE && (v3d->flag & V3D_ZBUF_SELECT)) {
3027                 extern int afterqtest(short win, unsigned short evt);   //editscreen.c
3028
3029                 v3d->flag |= V3D_NEEDBACKBUFDRAW;
3030                 if(afterqtest(sa->win, BACKBUFDRAW)==0) {
3031                         addafterqueue(sa->win, BACKBUFDRAW, 1);
3032                 }
3033         }
3034
3035         /* run any view3d draw handler script links */
3036         if (sa->scriptlink.totscript)
3037                 BPY_do_spacehandlers(sa, 0, SPACEHANDLER_VIEW3D_DRAW);
3038
3039         /* run scene redraw script links */
3040         if((G.f & G_DOSCRIPTLINKS) && G.scene->scriptlink.totscript &&
3041                         !during_script()) {
3042                 BPY_do_pyscript((ID *)G.scene, SCRIPT_REDRAW);
3043         }
3044         
3045 }
3046
3047
3048 void drawview3d_render(struct View3D *v3d, int winx, int winy)
3049 {
3050         Base *base;
3051         Scene *sce;
3052         float winmat[4][4];
3053         
3054         update_for_newframe_muted();    /* first, since camera can be animated */
3055
3056         setwinmatrixview3d(winx, winy, NULL);
3057         
3058         setviewmatrixview3d();
3059         myloadmatrix(v3d->viewmat);
3060         glMatrixMode(GL_PROJECTION);
3061         mygetmatrix(winmat);
3062         glMatrixMode(GL_MODELVIEW);
3063         Mat4MulMat4(v3d->persmat, v3d->viewmat, winmat);
3064         Mat4Invert(v3d->persinv, v3d->persmat);
3065         Mat4Invert(v3d->viewinv, v3d->viewmat);
3066
3067         free_all_realtime_images();
3068         reshadeall_displist();
3069         
3070         if(v3d->drawtype > OB_WIRE) {
3071                 v3d->zbuf= TRUE;
3072                 glEnable(GL_DEPTH_TEST);
3073         }
3074
3075         if(v3d->flag & V3D_CLIPPING)
3076                 view3d_set_clipping(v3d);
3077
3078         if (v3d->drawtype==OB_TEXTURE && G.scene->world) {
3079                 glClearColor(G.scene->world->horr, G.scene->world->horg, G.scene->world->horb, 0.0); 
3080         } else {
3081                 float col[3];
3082                 BIF_GetThemeColor3fv(TH_BACK, col);
3083                 glClearColor(col[0], col[1], col[2], 0.0); 
3084         }
3085         glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
3086
3087         /* abuse! to make sure it doesnt draw the helpstuff */
3088         G.f |= G_SIMULATION;
3089
3090         /* first draw set */
3091         if(G.scene->set) {
3092         
3093                 for(SETLOOPER(G.scene->set, base)) {
3094                         if(v3d->lay & base->lay) {
3095                                 if ELEM3(base->object->type, OB_LAMP, OB_CAMERA, OB_LATTICE);
3096                                 else {
3097                                         where_is_object(base->object);
3098         
3099                                         BIF_ThemeColorBlend(TH_WIRE, TH_BACK, 0.6f);
3100                                         draw_object(base, DRAW_CONSTCOLOR);
3101         
3102                                         if(base->object->transflag & OB_DUPLI) {
3103                                                 draw_dupli_objects(v3d, base);
3104                                         }
3105                                 }
3106                         }
3107                 }
3108                 
3109                 /* Transp and X-ray afterdraw stuff */
3110                 view3d_draw_xray(v3d, DRAW_CONSTCOLOR); // clears zbuffer if it is used!
3111                 view3d_draw_transp(v3d, DRAW_CONSTCOLOR);
3112         }
3113
3114         /* first not selected and duplis */
3115         base= G.scene->base.first;
3116         while(base) {
3117                 
3118                 if(v3d->lay & base->lay) {
3119                         if ELEM3(base->object->type, OB_LAMP, OB_CAMERA, OB_LATTICE);
3120                         else {
3121         
3122                                 if(base->object->transflag & OB_DUPLI) {
3123                                         draw_dupli_objects(v3d, base);
3124                                 }
3125                                 else if((base->flag & SELECT)==0) {
3126                                         draw_object(base, 0);
3127                                 }
3128                         }
3129                 }
3130                 
3131                 base= base->next;
3132         }
3133
3134         /* draw selected */
3135         base= G.scene->base.first;
3136         while(base) {
3137                 
3138                 if ( ((base)->flag & SELECT) && ((base)->lay & v3d->lay) ) {
3139                         if ELEM3(base->object->type, OB_LAMP, OB_CAMERA, OB_LATTICE);
3140                         else draw_object(base, 0);
3141                 }
3142                 
3143                 base= base->next;
3144         }
3145
3146         if(G.scene->radio) RAD_drawall(v3d->drawtype>=OB_SOLID);
3147
3148         /* Transp and X-ray afterdraw stuff */
3149         view3d_draw_xray(v3d, 0);       // clears zbuffer if it is used!
3150         view3d_draw_transp(v3d, 0);
3151         
3152         if(v3d->flag & V3D_CLIPPING)
3153                 view3d_clr_clipping();
3154         
3155         if(v3d->zbuf) {
3156                 v3d->zbuf= FALSE;
3157                 glDisable(GL_DEPTH_TEST);
3158         }
3159         
3160         G.f &= ~G_SIMULATION;
3161
3162         glFlush();
3163
3164         glLoadIdentity();
3165
3166         free_all_realtime_images();
3167 }
3168
3169
3170 double tottime = 0.0;