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