]> de.git.xonotic.org Git - xonotic/netradiant.git/blob - radiant/xywindow.cpp
Q3map2:
[xonotic/netradiant.git] / radiant / xywindow.cpp
1 /*
2    Copyright (C) 1999-2006 Id Software, Inc. and contributors.
3    For a list of contributors, see the accompanying CONTRIBUTORS file.
4
5    This file is part of GtkRadiant.
6
7    GtkRadiant is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 2 of the License, or
10    (at your option) any later version.
11
12    GtkRadiant is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16
17    You should have received a copy of the GNU General Public License
18    along with GtkRadiant; if not, write to the Free Software
19    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
20  */
21
22 //
23 // XY Window
24 //
25 // Leonardo Zide (leo@lokigames.com)
26 //
27
28 #include "xywindow.h"
29
30 #include "debugging/debugging.h"
31
32 #include "ientity.h"
33 #include "igl.h"
34 #include "ibrush.h"
35 #include "iundo.h"
36 #include "iimage.h"
37 #include "ifilesystem.h"
38 #include "os/path.h"
39 #include "image.h"
40 #include "gtkutil/messagebox.h"
41
42 #include <gtk/gtklabel.h>
43 #include <gtk/gtkmenuitem.h>
44
45 #include "generic/callback.h"
46 #include "string/string.h"
47 #include "stream/stringstream.h"
48
49 #include "scenelib.h"
50 #include "eclasslib.h"
51 #include "renderer.h"
52 #include "moduleobserver.h"
53
54 #include "gtkutil/menu.h"
55 #include "gtkutil/container.h"
56 #include "gtkutil/widget.h"
57 #include "gtkutil/glwidget.h"
58 #include "gtkutil/filechooser.h"
59 #include "gtkmisc.h"
60 #include "select.h"
61 #include "csg.h"
62 #include "brushmanip.h"
63 #include "selection.h"
64 #include "entity.h"
65 #include "camwindow.h"
66 #include "texwindow.h"
67 #include "mainframe.h"
68 #include "preferences.h"
69 #include "commands.h"
70 #include "feedback.h"
71 #include "grid.h"
72 #include "windowobservers.h"
73
74 void LoadTextureRGBA( qtexture_t* q, unsigned char* pPixels, int nWidth, int nHeight );
75
76 // d1223m
77 extern bool g_brush_always_caulk;
78
79 //!\todo Rewrite.
80 class ClipPoint
81 {
82 public:
83 Vector3 m_ptClip;        // the 3d point
84 bool m_bSet;
85
86 ClipPoint(){
87         Reset();
88 };
89 void Reset(){
90         m_ptClip[0] = m_ptClip[1] = m_ptClip[2] = 0.0;
91         m_bSet = false;
92 }
93 bool Set(){
94         return m_bSet;
95 }
96 void Set( bool b ){
97         m_bSet = b;
98 }
99 operator Vector3&()
100 {
101         return m_ptClip;
102 };
103
104 /*! Draw clip/path point with rasterized number label */
105 void Draw( int num, float scale );
106 /*! Draw clip/path point with rasterized string label */
107 void Draw( const char *label, float scale );
108 };
109
110 VIEWTYPE g_clip_viewtype;
111 bool g_bSwitch = true;
112 bool g_clip_useCaulk = false;
113 bool g_quick_clipper = false;
114 ClipPoint g_Clip1;
115 ClipPoint g_Clip2;
116 ClipPoint g_Clip3;
117 ClipPoint* g_pMovingClip = 0;
118
119 /* Drawing clip points */
120 void ClipPoint::Draw( int num, float scale ){
121         StringOutputStream label( 4 );
122         label << num;
123         Draw( label.c_str(), scale );
124 }
125
126 void ClipPoint::Draw( const char *label, float scale ){
127         // draw point
128         glPointSize( 4 );
129         glColor3fv( vector3_to_array( g_xywindow_globals.color_clipper ) );
130         glBegin( GL_POINTS );
131         glVertex3fv( vector3_to_array( m_ptClip ) );
132         glEnd();
133         glPointSize( 1 );
134
135         float offset = 2.0f / scale;
136
137         // draw label
138         glRasterPos3f( m_ptClip[0] + offset, m_ptClip[1] + offset, m_ptClip[2] + offset );
139         //glCallLists( GLsizei( strlen( label ) ), GL_UNSIGNED_BYTE, label );   //fails with GCC
140         //glCallLists( GLsizei( strlen( label ) ), GL_UNSIGNED_BYTE, reinterpret_cast<const GLubyte*>( label ) );       //worx
141         GlobalOpenGL().drawString( label );
142 }
143
144 float fDiff( float f1, float f2 ){
145         if ( f1 > f2 ) {
146                 return f1 - f2;
147         }
148         else{
149                 return f2 - f1;
150         }
151 }
152
153 inline double ClipPoint_Intersect( const ClipPoint& clip, const Vector3& point, VIEWTYPE viewtype, float scale ){
154         int nDim1 = ( viewtype == YZ ) ? 1 : 0;
155         int nDim2 = ( viewtype == XY ) ? 1 : 2;
156         double screenDistanceSquared( vector2_length_squared( Vector2( fDiff( clip.m_ptClip[nDim1], point[nDim1] ) * scale, fDiff( clip.m_ptClip[nDim2], point[nDim2] )  * scale ) ) );
157         if ( screenDistanceSquared < 8 * 8 ) {
158                 return screenDistanceSquared;
159         }
160         return FLT_MAX;
161 }
162
163 inline void ClipPoint_testSelect( ClipPoint& clip, const Vector3& point, VIEWTYPE viewtype, float scale, double& bestDistance, ClipPoint*& bestClip ){
164         if ( clip.Set() ) {
165                 double distance = ClipPoint_Intersect( clip, point, viewtype, scale );
166                 if ( distance < bestDistance ) {
167                         bestDistance = distance;
168                         bestClip = &clip;
169                 }
170         }
171 }
172
173 inline ClipPoint* GlobalClipPoints_Find( const Vector3& point, VIEWTYPE viewtype, float scale ){
174         double bestDistance = FLT_MAX;
175         ClipPoint* bestClip = 0;
176         ClipPoint_testSelect( g_Clip1, point, viewtype, scale, bestDistance, bestClip );
177         ClipPoint_testSelect( g_Clip2, point, viewtype, scale, bestDistance, bestClip );
178         ClipPoint_testSelect( g_Clip3, point, viewtype, scale, bestDistance, bestClip );
179         return bestClip;
180 }
181
182 inline void GlobalClipPoints_Draw( float scale ){
183         // Draw clip points
184         if ( g_Clip1.Set() ) {
185                 g_Clip1.Draw( 1, scale );
186         }
187         if ( g_Clip2.Set() ) {
188                 g_Clip2.Draw( 2, scale );
189         }
190         if ( g_Clip3.Set() ) {
191                 g_Clip3.Draw( 3, scale );
192         }
193 }
194
195 inline bool GlobalClipPoints_valid(){
196         return g_Clip1.Set() && g_Clip2.Set();
197 }
198
199 void PlanePointsFromClipPoints( Vector3 planepts[3], const AABB& bounds, int viewtype ){
200         ASSERT_MESSAGE( GlobalClipPoints_valid(), "clipper points not initialised" );
201         planepts[0] = g_Clip1.m_ptClip;
202         planepts[1] = g_Clip2.m_ptClip;
203         planepts[2] = g_Clip3.m_ptClip;
204         Vector3 maxs( vector3_added( bounds.origin, bounds.extents ) );
205         Vector3 mins( vector3_subtracted( bounds.origin, bounds.extents ) );
206         if ( !g_Clip3.Set() ) {
207                 int n = ( viewtype == XY ) ? 2 : ( viewtype == YZ ) ? 0 : 1;
208                 int x = ( n == 0 ) ? 1 : 0;
209                 int y = ( n == 2 ) ? 1 : 2;
210
211                 if ( n == 1 ) { // on viewtype XZ, flip clip points
212                         planepts[0][n] = maxs[n];
213                         planepts[1][n] = maxs[n];
214                         planepts[2][x] = g_Clip1.m_ptClip[x];
215                         planepts[2][y] = g_Clip1.m_ptClip[y];
216                         planepts[2][n] = mins[n];
217                 }
218                 else
219                 {
220                         planepts[0][n] = mins[n];
221                         planepts[1][n] = mins[n];
222                         planepts[2][x] = g_Clip1.m_ptClip[x];
223                         planepts[2][y] = g_Clip1.m_ptClip[y];
224                         planepts[2][n] = maxs[n];
225                 }
226         }
227 }
228
229 void Clip_Update(){
230         Vector3 planepts[3];
231         if ( !GlobalClipPoints_valid() ) {
232                 planepts[0] = Vector3( 0, 0, 0 );
233                 planepts[1] = Vector3( 0, 0, 0 );
234                 planepts[2] = Vector3( 0, 0, 0 );
235                 Scene_BrushSetClipPlane( GlobalSceneGraph(), Plane3( 0, 0, 0, 0 ) );
236         }
237         else
238         {
239                 AABB bounds( Vector3( 0, 0, 0 ), Vector3( 64, 64, 64 ) );
240                 PlanePointsFromClipPoints( planepts, bounds, g_clip_viewtype );
241                 if ( g_bSwitch ) {
242                         std::swap( planepts[0], planepts[1] );
243                 }
244                 Scene_BrushSetClipPlane( GlobalSceneGraph(), plane3_for_points( planepts[0], planepts[1], planepts[2] ) );
245         }
246         ClipperChangeNotify();
247 }
248
249 const char* Clip_getShader(){
250         return g_clip_useCaulk ? "textures/common/caulk" : TextureBrowser_GetSelectedShader( GlobalTextureBrowser() );
251 }
252
253 void Clip(){
254         if ( ClipMode() && GlobalClipPoints_valid() ) {
255                 Vector3 planepts[3];
256                 AABB bounds( Vector3( 0, 0, 0 ), Vector3( 64, 64, 64 ) );
257                 PlanePointsFromClipPoints( planepts, bounds, g_clip_viewtype );
258                 Scene_BrushSplitByPlane( GlobalSceneGraph(), planepts[0], planepts[1], planepts[2], Clip_getShader(), ( !g_bSwitch ) ? eFront : eBack );
259                 g_Clip1.Reset();
260                 g_Clip2.Reset();
261                 g_Clip3.Reset();
262                 Clip_Update();
263                 ClipperChangeNotify();
264                 if( g_quick_clipper ){
265                         g_quick_clipper = false;
266                         ClipperMode();
267                 }
268         }
269 }
270
271 void SplitClip(){
272         if ( ClipMode() && GlobalClipPoints_valid() ) {
273                 Vector3 planepts[3];
274                 AABB bounds( Vector3( 0, 0, 0 ), Vector3( 64, 64, 64 ) );
275                 PlanePointsFromClipPoints( planepts, bounds, g_clip_viewtype );
276                 Scene_BrushSplitByPlane( GlobalSceneGraph(), planepts[0], planepts[1], planepts[2], Clip_getShader(), eFrontAndBack );
277                 g_Clip1.Reset();
278                 g_Clip2.Reset();
279                 g_Clip3.Reset();
280                 Clip_Update();
281                 ClipperChangeNotify();
282                 if( g_quick_clipper ){
283                         g_quick_clipper = false;
284                         ClipperMode();
285                 }
286         }
287 }
288
289 void FlipClip(){
290         g_bSwitch = !g_bSwitch;
291         Clip_Update();
292         ClipperChangeNotify();
293 }
294
295 void OnClipMode( bool enabled ){
296         g_Clip1.Reset();
297         g_Clip2.Reset();
298         g_Clip3.Reset();
299
300         if ( !enabled && g_pMovingClip ) {
301                 g_pMovingClip = 0;
302         }
303
304         Clip_Update();
305         ClipperChangeNotify();
306 }
307
308 bool ClipMode(){
309         return GlobalSelectionSystem().ManipulatorMode() == SelectionSystem::eClip;
310 }
311
312 void NewClipPoint( const Vector3& point ){
313         if ( g_Clip1.Set() == false ) {
314                 g_Clip1.m_ptClip = point;
315                 g_Clip1.Set( true );
316         }
317         else if ( g_Clip2.Set() == false ) {
318                 g_Clip2.m_ptClip = point;
319                 g_Clip2.Set( true );
320         }
321         else if ( g_Clip3.Set() == false ) {
322                 g_Clip3.m_ptClip = point;
323                 g_Clip3.Set( true );
324         }
325         else
326         {
327                 g_Clip1.Reset();
328                 g_Clip2.Reset();
329                 g_Clip3.Reset();
330                 g_Clip1.m_ptClip = point;
331                 g_Clip1.Set( true );
332         }
333
334         Clip_Update();
335         ClipperChangeNotify();
336 }
337
338
339
340 struct xywindow_globals_private_t
341 {
342         bool d_showgrid;
343
344         // these are in the View > Show menu with Show coordinates
345         bool show_names;
346         bool show_coordinates;
347         bool show_angles;
348         bool show_outline;
349         bool show_axis;
350
351         bool d_show_work;
352
353         bool show_blocks;
354         int blockSize;
355
356 //      bool m_bCamXYUpdate;
357         bool m_bChaseMouse;
358         bool m_bSizePaint;
359
360         xywindow_globals_private_t() :
361                 d_showgrid( true ),
362
363                 show_names( false ),
364                 show_coordinates( false ),
365                 show_angles( true ),
366                 show_outline( true ),
367                 show_axis( true ),
368
369                 d_show_work( false ),
370
371                 show_blocks( false ),
372
373 //              m_bCamXYUpdate( true ),
374                 m_bChaseMouse( true ),
375                 m_bSizePaint( true ){
376         }
377
378 };
379
380 xywindow_globals_t g_xywindow_globals;
381 xywindow_globals_private_t g_xywindow_globals_private;
382
383 const unsigned int RAD_NONE =    0x00;
384 const unsigned int RAD_SHIFT =   0x01;
385 const unsigned int RAD_ALT =     0x02;
386 const unsigned int RAD_CONTROL = 0x04;
387 const unsigned int RAD_PRESS   = 0x08;
388 const unsigned int RAD_LBUTTON = 0x10;
389 const unsigned int RAD_MBUTTON = 0x20;
390 const unsigned int RAD_RBUTTON = 0x40;
391
392 inline ButtonIdentifier button_for_flags( unsigned int flags ){
393         if ( flags & RAD_LBUTTON ) {
394                 return c_buttonLeft;
395         }
396         if ( flags & RAD_RBUTTON ) {
397                 return c_buttonRight;
398         }
399         if ( flags & RAD_MBUTTON ) {
400                 return c_buttonMiddle;
401         }
402         return c_buttonInvalid;
403 }
404
405 inline ModifierFlags modifiers_for_flags( unsigned int flags ){
406         ModifierFlags modifiers = c_modifierNone;
407         if ( flags & RAD_SHIFT ) {
408                 modifiers |= c_modifierShift;
409         }
410         if ( flags & RAD_CONTROL ) {
411                 modifiers |= c_modifierControl;
412         }
413         if ( flags & RAD_ALT ) {
414                 modifiers |= c_modifierAlt;
415         }
416         return modifiers;
417 }
418
419 inline unsigned int buttons_for_button_and_modifiers( ButtonIdentifier button, ModifierFlags flags ){
420         unsigned int buttons = 0;
421
422         switch ( button.get() )
423         {
424         case ButtonEnumeration::LEFT: buttons |= RAD_LBUTTON; break;
425         case ButtonEnumeration::MIDDLE: buttons |= RAD_MBUTTON; break;
426         case ButtonEnumeration::RIGHT: buttons |= RAD_RBUTTON; break;
427         }
428
429         if ( bitfield_enabled( flags, c_modifierControl ) ) {
430                 buttons |= RAD_CONTROL;
431         }
432
433         if ( bitfield_enabled( flags, c_modifierShift ) ) {
434                 buttons |= RAD_SHIFT;
435         }
436
437         if ( bitfield_enabled( flags, c_modifierAlt ) ) {
438                 buttons |= RAD_ALT;
439         }
440
441         return buttons;
442 }
443
444 inline unsigned int buttons_for_event_button( GdkEventButton* event ){
445         unsigned int flags = 0;
446
447         switch ( event->button )
448         {
449         case 1: flags |= RAD_LBUTTON; break;
450         case 2: flags |= RAD_MBUTTON; break;
451         case 3: flags |= RAD_RBUTTON; break;
452         }
453
454         if ( ( event->state & GDK_CONTROL_MASK ) != 0 ) {
455                 flags |= RAD_CONTROL;
456         }
457
458         if ( ( event->state & GDK_SHIFT_MASK ) != 0 ) {
459                 flags |= RAD_SHIFT;
460         }
461
462         if ( ( event->state & GDK_MOD1_MASK ) != 0 ) {
463                 flags |= RAD_ALT;
464         }
465
466         return flags;
467 }
468
469 inline unsigned int buttons_for_state( guint state ){
470         unsigned int flags = 0;
471
472         if ( ( state & GDK_BUTTON1_MASK ) != 0 ) {
473                 flags |= RAD_LBUTTON;
474         }
475
476         if ( ( state & GDK_BUTTON2_MASK ) != 0 ) {
477                 flags |= RAD_MBUTTON;
478         }
479
480         if ( ( state & GDK_BUTTON3_MASK ) != 0 ) {
481                 flags |= RAD_RBUTTON;
482         }
483
484         if ( ( state & GDK_CONTROL_MASK ) != 0 ) {
485                 flags |= RAD_CONTROL;
486         }
487
488         if ( ( state & GDK_SHIFT_MASK ) != 0 ) {
489                 flags |= RAD_SHIFT;
490         }
491
492         if ( ( state & GDK_MOD1_MASK ) != 0 ) {
493                 flags |= RAD_ALT;
494         }
495
496         return flags;
497 }
498
499
500 void XYWnd::SetScale( float f ){
501         m_fScale = f;
502         updateProjection();
503         updateModelview();
504         XYWnd_Update( *this );
505 }
506
507 void XYWnd::ZoomIn(){
508         float max_scale = 64;
509         float scale = Scale() * 5.0f / 4.0f;
510         if ( scale > max_scale ) {
511                 if ( Scale() != max_scale ) {
512                         SetScale( max_scale );
513                 }
514         }
515         else
516         {
517                 SetScale( scale );
518         }
519 }
520
521
522 // NOTE: the zoom out factor is 4/5, we could think about customizing it
523 //  we don't go below a zoom factor corresponding to 10% of the max world size
524 //  (this has to be computed against the window size)
525 void XYWnd::ZoomOut(){
526         float min_scale = MIN( Width(), Height() ) / ( 1.1f * ( g_MaxWorldCoord - g_MinWorldCoord ) );
527         float scale = Scale() * 4.0f / 5.0f;
528         if ( scale < min_scale ) {
529                 if ( Scale() != min_scale ) {
530                         SetScale( min_scale );
531                 }
532         }
533         else
534         {
535                 SetScale( scale );
536         }
537 }
538
539 void XYWnd::ZoomInWithMouse( int pointx, int pointy ){
540         float old_scale = Scale();
541         ZoomIn();
542         if ( g_xywindow_globals.m_bZoomInToPointer ) {
543                 float scale_diff = 1.0 / old_scale - 1.0 / Scale();
544                 int nDim1 = ( m_viewType == YZ ) ? 1 : 0;
545                 int nDim2 = ( m_viewType == XY ) ? 1 : 2;
546                 Vector3 origin = GetOrigin();
547                 origin[nDim1] += scale_diff * (pointx - 0.5 * Width());
548                 origin[nDim2] -= scale_diff * (pointy - 0.5 * Height());
549                 SetOrigin( origin );
550         }
551 }
552
553 void XYWnd::FocusOnBounds( AABB& bounds ){
554         SetOrigin( bounds.origin );
555         int nDim1 = ( m_viewType == YZ ) ? 1 : 0;
556         int nDim2 = ( m_viewType == XY ) ? 1 : 2;
557         if( bounds.extents[ nDim1 ] < 128.f )
558                 bounds.extents[ nDim1 ] = 128.f;
559         if( bounds.extents[ nDim2 ] < 128.f )
560                 bounds.extents[ nDim2 ] = 128.f;
561         float scale1 = Width() / ( 3.f * bounds.extents[ nDim1 ] );
562         float scale2 = Height() / ( 3.f * bounds.extents[ nDim2 ] );
563         SetScale( MIN( scale1, scale2 ) );
564
565 }
566
567 VIEWTYPE GlobalXYWnd_getCurrentViewType(){
568         ASSERT_NOTNULL( g_pParentWnd );
569         ASSERT_NOTNULL( g_pParentWnd->ActiveXY() );
570         return g_pParentWnd->ActiveXY()->GetViewType();
571 }
572
573 // =============================================================================
574 // variables
575
576 bool g_bCrossHairs = false;
577
578 GtkMenu* XYWnd::m_mnuDrop = 0;
579
580 // this is disabled, and broken
581 // http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=394
582 #if 0
583 void WXY_Print(){
584         long width, height;
585         width = g_pParentWnd->ActiveXY()->Width();
586         height = g_pParentWnd->ActiveXY()->Height();
587         unsigned char* img;
588         const char* filename;
589
590         filename = file_dialog( GTK_WIDGET( MainFrame_getWindow() ), FALSE, "Save Image", 0, FILTER_BMP );
591         if ( !filename ) {
592                 return;
593         }
594
595         g_pParentWnd->ActiveXY()->MakeCurrent();
596         img = (unsigned char*)malloc( width * height * 3 );
597         glReadPixels( 0,0,width,height,GL_RGB,GL_UNSIGNED_BYTE,img );
598
599         FILE *fp;
600         fp = fopen( filename, "wb" );
601         if ( fp ) {
602                 unsigned short bits;
603                 unsigned long cmap, bfSize;
604
605                 bits = 24;
606                 cmap = 0;
607                 bfSize = 54 + width * height * 3;
608
609                 long byteswritten = 0;
610                 long pixoff = 54 + cmap * 4;
611                 short res = 0;
612                 char m1 = 'B', m2 = 'M';
613                 fwrite( &m1, 1, 1, fp );      byteswritten++; // B
614                 fwrite( &m2, 1, 1, fp );      byteswritten++; // M
615                 fwrite( &bfSize, 4, 1, fp );  byteswritten += 4; // bfSize
616                 fwrite( &res, 2, 1, fp );     byteswritten += 2; // bfReserved1
617                 fwrite( &res, 2, 1, fp );     byteswritten += 2; // bfReserved2
618                 fwrite( &pixoff, 4, 1, fp );  byteswritten += 4; // bfOffBits
619
620                 unsigned long biSize = 40, compress = 0, size = 0;
621                 long pixels = 0;
622                 unsigned short planes = 1;
623                 fwrite( &biSize, 4, 1, fp );  byteswritten += 4; // biSize
624                 fwrite( &width, 4, 1, fp );   byteswritten += 4; // biWidth
625                 fwrite( &height, 4, 1, fp );  byteswritten += 4; // biHeight
626                 fwrite( &planes, 2, 1, fp );  byteswritten += 2; // biPlanes
627                 fwrite( &bits, 2, 1, fp );    byteswritten += 2; // biBitCount
628                 fwrite( &compress, 4, 1, fp ); byteswritten += 4; // biCompression
629                 fwrite( &size, 4, 1, fp );    byteswritten += 4; // biSizeImage
630                 fwrite( &pixels, 4, 1, fp );  byteswritten += 4; // biXPelsPerMeter
631                 fwrite( &pixels, 4, 1, fp );  byteswritten += 4; // biYPelsPerMeter
632                 fwrite( &cmap, 4, 1, fp );    byteswritten += 4; // biClrUsed
633                 fwrite( &cmap, 4, 1, fp );    byteswritten += 4; // biClrImportant
634
635                 unsigned long widthDW = ( ( ( width * 24 ) + 31 ) / 32 * 4 );
636                 long row, row_size = width * 3;
637                 for ( row = 0; row < height; row++ )
638                 {
639                         unsigned char* buf = img + row * row_size;
640
641                         // write a row
642                         int col;
643                         for ( col = 0; col < row_size; col += 3 )
644                         {
645                                 putc( buf[col + 2], fp );
646                                 putc( buf[col + 1], fp );
647                                 putc( buf[col], fp );
648                         }
649                         byteswritten += row_size;
650
651                         unsigned long count;
652                         for ( count = row_size; count < widthDW; count++ )
653                         {
654                                 putc( 0, fp ); // dummy
655                                 byteswritten++;
656                         }
657                 }
658
659                 fclose( fp );
660         }
661
662         free( img );
663 }
664 #endif
665
666
667 #include "timer.h"
668
669 Timer g_chasemouse_timer;
670
671 void XYWnd::ChaseMouse(){
672         float multiplier = g_chasemouse_timer.elapsed_msec() / 10.0f;
673         Scroll( float_to_integer( multiplier * m_chasemouse_delta_x ), float_to_integer( multiplier * -m_chasemouse_delta_y ) );
674
675         //globalOutputStream() << "chasemouse: multiplier=" << multiplier << " x=" << m_chasemouse_delta_x << " y=" << m_chasemouse_delta_y << '\n';
676
677         XY_MouseMoved( m_chasemouse_current_x, m_chasemouse_current_y, getButtonState() );
678         g_chasemouse_timer.start();
679 }
680
681 gboolean xywnd_chasemouse( gpointer data ){
682         reinterpret_cast<XYWnd*>( data )->ChaseMouse();
683         return TRUE;
684 }
685
686 inline const int& min_int( const int& left, const int& right ){
687         return std::min( left, right );
688 }
689
690 bool XYWnd::chaseMouseMotion( int pointx, int pointy ){
691         m_chasemouse_delta_x = 0;
692         m_chasemouse_delta_y = 0;
693
694         if ( g_xywindow_globals_private.m_bChaseMouse && getButtonState() == RAD_LBUTTON ) {
695                 const int epsilon = 16;
696
697                 if ( pointx < epsilon ) {
698                         m_chasemouse_delta_x = std::max( pointx, 0 ) - epsilon;
699                 }
700                 else if ( ( pointx - m_nWidth ) > -epsilon ) {
701                         m_chasemouse_delta_x = min_int( ( pointx - m_nWidth ), 0 ) + epsilon;
702                 }
703
704                 if ( pointy < epsilon ) {
705                         m_chasemouse_delta_y = std::max( pointy, 0 ) - epsilon;
706                 }
707                 else if ( ( pointy - m_nHeight ) > -epsilon ) {
708                         m_chasemouse_delta_y = min_int( ( pointy - m_nHeight ), 0 ) + epsilon;
709                 }
710
711                 if ( m_chasemouse_delta_y != 0 || m_chasemouse_delta_x != 0 ) {
712                         //globalOutputStream() << "chasemouse motion: x=" << pointx << " y=" << pointy << "... ";
713                         m_chasemouse_current_x = pointx;
714                         m_chasemouse_current_y = pointy;
715                         if ( m_chasemouse_handler == 0 ) {
716                                 //globalOutputStream() << "chasemouse timer start... ";
717                                 g_chasemouse_timer.start();
718                                 m_chasemouse_handler = g_idle_add( xywnd_chasemouse, this );
719                         }
720                         return true;
721                 }
722                 else
723                 {
724                         if ( m_chasemouse_handler != 0 ) {
725                                 //globalOutputStream() << "chasemouse cancel\n";
726                                 g_source_remove( m_chasemouse_handler );
727                                 m_chasemouse_handler = 0;
728                         }
729                 }
730         }
731         else
732         {
733                 if ( m_chasemouse_handler != 0 ) {
734                         //globalOutputStream() << "chasemouse cancel\n";
735                         g_source_remove( m_chasemouse_handler );
736                         m_chasemouse_handler = 0;
737                 }
738         }
739         return false;
740 }
741
742 // =============================================================================
743 // XYWnd class
744 Shader* XYWnd::m_state_selected = 0;
745
746 void xy_update_xor_rectangle( XYWnd& self, rect_t area ){
747         if ( GTK_WIDGET_VISIBLE( self.GetWidget() ) ) {
748                 rectangle_t rect = rectangle_from_area( area.min, area.max, self.Width(), self.Height() );
749 //              int nDim1 = ( self.GetViewType() == YZ ) ? 1 : 0;
750 //              int nDim2 = ( self.GetViewType() == XY ) ? 1 : 2;
751 //              rect.x /= self.Scale();
752 //              rect.y /= self.Scale();
753 //              rect.w /= self.Scale();
754 //              rect.h /= self.Scale();
755 //              rect.x += self.GetOrigin()[nDim1];
756 //              rect.y += self.GetOrigin()[nDim2];
757                 self.m_XORRectangle.set( rect );
758         }
759 }
760
761 gboolean xywnd_button_press( GtkWidget* widget, GdkEventButton* event, XYWnd* xywnd ){
762         if ( event->type == GDK_BUTTON_PRESS ) {
763                 gtk_widget_grab_focus( xywnd->GetWidget() );
764
765                 if( !xywnd->Active() ){
766                         g_pParentWnd->SetActiveXY( xywnd );
767                 }
768
769                 xywnd->ButtonState_onMouseDown( buttons_for_event_button( event ) );
770
771                 xywnd->onMouseDown( WindowVector( event->x, event->y ), button_for_button( event->button ), modifiers_for_state( event->state ) );
772         }
773         return FALSE;
774 }
775
776 gboolean xywnd_button_release( GtkWidget* widget, GdkEventButton* event, XYWnd* xywnd ){
777         if ( event->type == GDK_BUTTON_RELEASE ) {
778                 xywnd->XY_MouseUp( static_cast<int>( event->x ), static_cast<int>( event->y ), buttons_for_event_button( event ) );
779
780                 xywnd->ButtonState_onMouseUp( buttons_for_event_button( event ) );
781         }
782         return FALSE;
783 }
784
785 gboolean xywnd_focus_in( GtkWidget* widget, GdkEventFocus* event, XYWnd* xywnd ){
786         if ( event->type == GDK_FOCUS_CHANGE ) {
787                 if ( event->in ) {
788                         if( !xywnd->Active() ){
789                                 g_pParentWnd->SetActiveXY( xywnd );
790                         }
791                 }
792         }
793         return FALSE;
794 }
795
796 void xywnd_motion( gdouble x, gdouble y, guint state, void* data ){
797         if ( reinterpret_cast<XYWnd*>( data )->chaseMouseMotion( static_cast<int>( x ), static_cast<int>( y ) ) ) {
798                 return;
799         }
800         reinterpret_cast<XYWnd*>( data )->XY_MouseMoved( static_cast<int>( x ), static_cast<int>( y ), buttons_for_state( state ) );
801 }
802
803 gboolean xywnd_wheel_scroll( GtkWidget* widget, GdkEventScroll* event, XYWnd* xywnd ){
804         gtk_widget_grab_focus( xywnd->GetWidget() );
805         GtkWindow* window = xywnd->m_parent != 0 ? xywnd->m_parent : MainFrame_getWindow();
806         if( !gtk_window_is_active( window ) )
807                 gtk_window_present( window );
808
809         if( !xywnd->Active() ){
810                 g_pParentWnd->SetActiveXY( xywnd );
811         }
812         if ( event->direction == GDK_SCROLL_UP ) {
813                 xywnd->ZoomInWithMouse( (int)event->x, (int)event->y );
814         }
815         else if ( event->direction == GDK_SCROLL_DOWN ) {
816                 xywnd->ZoomOut();
817         }
818         return FALSE;
819 }
820
821 gboolean xywnd_size_allocate( GtkWidget* widget, GtkAllocation* allocation, XYWnd* xywnd ){
822         xywnd->m_nWidth = allocation->width;
823         xywnd->m_nHeight = allocation->height;
824         xywnd->updateProjection();
825         xywnd->m_window_observer->onSizeChanged( xywnd->Width(), xywnd->Height() );
826         return FALSE;
827 }
828
829 gboolean xywnd_expose( GtkWidget* widget, GdkEventExpose* event, XYWnd* xywnd ){
830         if ( glwidget_make_current( xywnd->GetWidget() ) != FALSE ) {
831                 if ( Map_Valid( g_map ) && ScreenUpdates_Enabled() ) {
832                         GlobalOpenGL_debugAssertNoErrors();
833                         xywnd->XY_Draw();
834                         GlobalOpenGL_debugAssertNoErrors();
835
836                         xywnd->m_XORRectangle.set( rectangle_t() );
837                 }
838                 glwidget_swap_buffers( xywnd->GetWidget() );
839         }
840         return FALSE;
841 }
842
843
844 void XYWnd_CameraMoved( XYWnd& xywnd ){
845 //      if ( g_xywindow_globals_private.m_bCamXYUpdate ) {
846                 //XYWnd_Update( xywnd );
847                 xywnd.UpdateCameraIcon();
848 //      }
849 }
850
851 XYWnd::XYWnd() :
852         m_gl_widget( glwidget_new( FALSE ) ),
853         m_deferredDraw( WidgetQueueDrawCaller( *m_gl_widget ) ),
854         m_deferred_motion( xywnd_motion, this ),
855         m_parent( 0 ),
856         m_window_observer( NewWindowObserver() ),
857         m_XORRectangle( m_gl_widget ),
858         m_chasemouse_handler( 0 ){
859         m_bActive = false;
860         m_buttonstate = 0;
861
862         m_bNewBrushDrag = false;
863         m_move_started = false;
864         m_zoom_started = false;
865
866         m_nWidth = 0;
867         m_nHeight = 0;
868
869         m_vOrigin[0] = 0;
870         m_vOrigin[1] = 20;
871         m_vOrigin[2] = 46;
872         m_fScale = 1;
873         m_viewType = XY;
874
875         m_backgroundActivated = false;
876         m_alpha = 1.0f;
877         m_xmin = 0.0f;
878         m_ymin = 0.0f;
879         m_xmax = 0.0f;
880         m_ymax = 0.0f;
881
882         m_entityCreate = false;
883
884         m_mnuDrop = 0;
885
886         GlobalWindowObservers_add( m_window_observer );
887         GlobalWindowObservers_connectWidget( m_gl_widget );
888
889         m_window_observer->setRectangleDrawCallback( ReferenceCaller1<XYWnd, rect_t, xy_update_xor_rectangle>( *this ) );
890         m_window_observer->setView( m_view );
891
892         gtk_widget_ref( m_gl_widget );
893
894         gtk_widget_set_events( m_gl_widget, GDK_DESTROY | GDK_EXPOSURE_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK | GDK_POINTER_MOTION_MASK | GDK_SCROLL_MASK );
895         GTK_WIDGET_SET_FLAGS( m_gl_widget, GTK_CAN_FOCUS );
896
897         m_sizeHandler = g_signal_connect( G_OBJECT( m_gl_widget ), "size_allocate", G_CALLBACK( xywnd_size_allocate ), this );
898         m_exposeHandler = g_signal_connect( G_OBJECT( m_gl_widget ), "expose_event", G_CALLBACK( xywnd_expose ), this );
899
900         g_signal_connect( G_OBJECT( m_gl_widget ), "button_press_event", G_CALLBACK( xywnd_button_press ), this );
901         g_signal_connect( G_OBJECT( m_gl_widget ), "button_release_event", G_CALLBACK( xywnd_button_release ), this );
902         g_signal_connect( G_OBJECT( m_gl_widget ), "focus_in_event", G_CALLBACK( xywnd_focus_in ), this );      //works only in floating views layout
903         g_signal_connect( G_OBJECT( m_gl_widget ), "motion_notify_event", G_CALLBACK( DeferredMotion::gtk_motion ), &m_deferred_motion );
904
905         g_signal_connect( G_OBJECT( m_gl_widget ), "scroll_event", G_CALLBACK( xywnd_wheel_scroll ), this );
906
907         Map_addValidCallback( g_map, DeferredDrawOnMapValidChangedCaller( m_deferredDraw ) );
908
909         updateProjection();
910         updateModelview();
911
912         AddSceneChangeCallback( ReferenceCaller<XYWnd, &XYWnd_Update>( *this ) );
913         AddCameraMovedCallback( ReferenceCaller<XYWnd, &XYWnd_CameraMoved>( *this ) );
914
915         PressedButtons_connect( g_pressedButtons, m_gl_widget );
916
917         onMouseDown.connectLast( makeSignalHandler3( MouseDownCaller(), *this ) );
918 }
919
920 XYWnd::~XYWnd(){
921         onDestroyed();
922
923         if ( m_mnuDrop != 0 ) {
924                 gtk_widget_destroy( GTK_WIDGET( m_mnuDrop ) );
925                 m_mnuDrop = 0;
926         }
927
928         g_signal_handler_disconnect( G_OBJECT( m_gl_widget ), m_sizeHandler );
929         g_signal_handler_disconnect( G_OBJECT( m_gl_widget ), m_exposeHandler );
930
931         gtk_widget_unref( m_gl_widget );
932
933         m_window_observer->release();
934 }
935
936 void XYWnd::captureStates(){
937         m_state_selected = GlobalShaderCache().capture( "$XY_OVERLAY" );
938 }
939
940 void XYWnd::releaseStates(){
941         GlobalShaderCache().release( "$XY_OVERLAY" );
942 }
943
944 const Vector3& XYWnd::GetOrigin(){
945         return m_vOrigin;
946 }
947
948 void XYWnd::SetOrigin( const Vector3& origin ){
949         m_vOrigin = origin;
950         updateModelview();
951 }
952
953 void XYWnd::Scroll( int x, int y ){
954         int nDim1 = ( m_viewType == YZ ) ? 1 : 0;
955         int nDim2 = ( m_viewType == XY ) ? 1 : 2;
956         m_vOrigin[nDim1] += x / m_fScale;
957         m_vOrigin[nDim2] += y / m_fScale;
958         updateModelview();
959         queueDraw();
960 }
961
962 unsigned int Clipper_buttons(){
963         return RAD_LBUTTON;
964 }
965
966 unsigned int Clipper_quick_buttons(){
967         return RAD_LBUTTON | RAD_CONTROL;
968 }
969
970 void XYWnd::DropClipPoint( int pointx, int pointy ){
971         Vector3 point;
972
973         XY_ToPoint( pointx, pointy, point );
974
975         Vector3 mid;
976         Select_GetMid( mid );
977         g_clip_viewtype = static_cast<VIEWTYPE>( GetViewType() );
978         const int nDim = ( g_clip_viewtype == YZ ) ? 0 : ( ( g_clip_viewtype == XZ ) ? 1 : 2 );
979         point[nDim] = mid[nDim];
980         vector3_snap( point, GetSnapGridSize() );
981         NewClipPoint( point );
982 }
983
984 void XYWnd::Clipper_OnLButtonDown( int x, int y ){
985         Vector3 mousePosition;
986         XY_ToPoint( x, y, mousePosition );
987         g_pMovingClip = GlobalClipPoints_Find( mousePosition, (VIEWTYPE)m_viewType, m_fScale );
988         if ( !g_pMovingClip ) {
989                 DropClipPoint( x, y );
990         }
991 }
992
993 void XYWnd::Clipper_OnLButtonUp( int x, int y ){
994         if ( g_pMovingClip ) {
995                 g_pMovingClip = 0;
996         }
997 }
998
999 void XYWnd::Clipper_OnMouseMoved( int x, int y ){
1000         if ( g_pMovingClip ) {
1001                 XY_ToPoint( x, y, g_pMovingClip->m_ptClip );
1002                 XY_SnapToGrid( g_pMovingClip->m_ptClip );
1003                 Clip_Update();
1004                 ClipperChangeNotify();
1005         }
1006 }
1007
1008 //#include "gtkutil/image.h"
1009
1010 /* is called on every mouse move fraction; ain't good! */
1011 void XYWnd::Clipper_Crosshair_OnMouseMoved( int x, int y ){
1012         Vector3 mousePosition;
1013         XY_ToPoint( x, y, mousePosition );
1014         if ( ClipMode() ) {
1015                 if( GlobalClipPoints_Find( mousePosition, (VIEWTYPE)m_viewType, m_fScale ) != 0 ){
1016                         GdkCursor *cursor;
1017                         cursor = gdk_cursor_new( GDK_CROSSHAIR );
1018                         //cursor = gdk_cursor_new( GDK_FLEUR );
1019                         gdk_window_set_cursor( m_gl_widget->window, cursor );
1020                         gdk_cursor_unref( cursor );
1021                 }
1022                 else{
1023                         GdkCursor *cursor;
1024                         cursor = gdk_cursor_new( GDK_HAND2 );
1025 //                      GdkPixbuf* pixbuf = pixbuf_new_from_file_with_mask( "bitmaps/icon.png" );
1026 //                      cursor = gdk_cursor_new_from_pixbuf( gdk_display_get_default(), pixbuf, 0, 0 );
1027 //                      g_object_unref( pixbuf );
1028                         gdk_window_set_cursor( m_gl_widget->window, cursor );
1029                         gdk_cursor_unref( cursor );
1030
1031                 }
1032         }
1033         else
1034         {
1035                 gdk_window_set_cursor( m_gl_widget->window, 0 );
1036         }
1037 }
1038
1039 void XYWnd::SetCustomPivotOrigin( int pointx, int pointy ){
1040         Vector3 point;
1041         XY_ToPoint( pointx, pointy, point );
1042         VIEWTYPE viewtype = static_cast<VIEWTYPE>( GetViewType() );
1043         const int nDim = ( viewtype == YZ ) ? 0 : ( ( viewtype == XZ ) ? 1 : 2 );
1044         //vector3_snap( point, GetSnapGridSize() );
1045         point[nDim] = 999999;
1046
1047         GlobalSelectionSystem().setCustomPivotOrigin( point );
1048         SceneChangeNotify();
1049 }
1050
1051 unsigned int MoveCamera_buttons(){
1052 //      return RAD_CONTROL | ( g_glwindow_globals.m_nMouseType == ETwoButton ? RAD_RBUTTON : RAD_MBUTTON );
1053         return RAD_CONTROL | RAD_MBUTTON;
1054 }
1055
1056 void XYWnd_PositionCamera( XYWnd* xywnd, int x, int y, CamWnd& camwnd ){
1057         Vector3 origin( Camera_getOrigin( camwnd ) );
1058         xywnd->XY_ToPoint( x, y, origin );
1059         xywnd->XY_SnapToGrid( origin );
1060         Camera_setOrigin( camwnd, origin );
1061 }
1062
1063 unsigned int OrientCamera_buttons(){
1064 //      if ( g_glwindow_globals.m_nMouseType == ETwoButton ) {
1065 //              return RAD_RBUTTON | RAD_SHIFT | RAD_CONTROL;
1066 //      }
1067         return RAD_MBUTTON;
1068 }
1069
1070 void XYWnd_OrientCamera( XYWnd* xywnd, int x, int y, CamWnd& camwnd ){
1071         //globalOutputStream() << Camera_getAngles( camwnd ) << "  b4\n";
1072         Vector3 point = g_vector3_identity;
1073         xywnd->XY_ToPoint( x, y, point );
1074         //xywnd->XY_SnapToGrid( point );
1075         vector3_subtract( point, Camera_getOrigin( camwnd ) );
1076
1077         int n1 = ( xywnd->GetViewType() == XY ) ? 1 : 2;
1078         int n2 = ( xywnd->GetViewType() == YZ ) ? 1 : 0;
1079         int nAngle = ( xywnd->GetViewType() == XY ) ? CAMERA_YAW : CAMERA_PITCH;
1080         if ( point[n1] || point[n2] ) {
1081                 Vector3 angles( Camera_getAngles( camwnd ) );
1082                 angles[nAngle] = static_cast<float>( radians_to_degrees( atan2( point[n1], point[n2] ) ) );
1083                 if( angles[CAMERA_YAW] < 0 )
1084                         angles[CAMERA_YAW] = angles[CAMERA_YAW] + 360;
1085                 if ( nAngle == CAMERA_PITCH ){
1086                         if( fabs( angles[CAMERA_PITCH] ) > 90 ){
1087                                 angles[CAMERA_PITCH] = ( angles[CAMERA_PITCH] > 0 ) ? ( -angles[CAMERA_PITCH] + 180 ) : ( -angles[CAMERA_PITCH] - 180 );
1088                                 if( xywnd->GetViewType() == YZ ){
1089                                         if( angles[CAMERA_YAW] < 180 ){
1090                                                 angles[CAMERA_YAW] = 360 - angles[CAMERA_YAW];
1091                                         }
1092                                 }
1093                                 else if( angles[CAMERA_YAW] < 90 || angles[CAMERA_YAW] > 270 ){
1094                                         angles[CAMERA_YAW] = 180 - angles[CAMERA_YAW];
1095                                 }
1096                         }
1097                         else{
1098                                 if( xywnd->GetViewType() == YZ ){
1099                                         if( angles[CAMERA_YAW] > 180 ){
1100                                                 angles[CAMERA_YAW] = 360 - angles[CAMERA_YAW];
1101                                         }
1102                                 }
1103                                 else if( angles[CAMERA_YAW] > 90 && angles[CAMERA_YAW] < 270 ){
1104                                         angles[CAMERA_YAW] = 180 - angles[CAMERA_YAW];
1105                                 }
1106                         }
1107                 }
1108                 Camera_setAngles( camwnd, angles );
1109         }
1110         //globalOutputStream() << Camera_getAngles( camwnd ) << "\n";
1111 }
1112
1113 unsigned int SetCustomPivotOrigin_buttons(){
1114         return RAD_MBUTTON | RAD_SHIFT;
1115 }
1116
1117 /*
1118    ==============
1119    NewBrushDrag
1120    ==============
1121  */
1122 unsigned int NewBrushDrag_buttons(){
1123         return RAD_LBUTTON;
1124 }
1125
1126 void XYWnd::NewBrushDrag_Begin( int x, int y ){
1127         m_NewBrushDrag = 0;
1128         m_nNewBrushPressx = x;
1129         m_nNewBrushPressy = y;
1130
1131         m_bNewBrushDrag = true;
1132 }
1133
1134 void XYWnd::NewBrushDrag_End( int x, int y ){
1135         if ( m_NewBrushDrag != 0 ) {
1136                 GlobalUndoSystem().finish( "brushDragNew" );
1137         }
1138 }
1139
1140 void XYWnd::NewBrushDrag( int x, int y ){
1141         Vector3 mins, maxs;
1142         XY_ToPoint( m_nNewBrushPressx, m_nNewBrushPressy, mins );
1143         XY_SnapToGrid( mins );
1144         XY_ToPoint( x, y, maxs );
1145         XY_SnapToGrid( maxs );
1146
1147         int nDim = ( m_viewType == XY ) ? 2 : ( m_viewType == YZ ) ? 0 : 1;
1148
1149         mins[nDim] = float_snapped( Select_getWorkZone().d_work_min[nDim], GetSnapGridSize() );
1150         maxs[nDim] = float_snapped( Select_getWorkZone().d_work_max[nDim], GetSnapGridSize() );
1151
1152         if ( maxs[nDim] <= mins[nDim] ) {
1153                 maxs[nDim] = mins[nDim] + GetGridSize();
1154         }
1155
1156         for ( int i = 0 ; i < 3 ; i++ )
1157         {
1158                 if ( mins[i] == maxs[i] ) {
1159                         return; // don't create a degenerate brush
1160                 }
1161                 if ( mins[i] > maxs[i] ) {
1162                         float temp = mins[i];
1163                         mins[i] = maxs[i];
1164                         maxs[i] = temp;
1165                 }
1166         }
1167
1168         if ( m_NewBrushDrag == 0 ) {
1169                 GlobalUndoSystem().start();
1170                 NodeSmartReference node( GlobalBrushCreator().createBrush() );
1171                 Node_getTraversable( Map_FindOrInsertWorldspawn( g_map ) )->insert( node );
1172
1173                 scene::Path brushpath( makeReference( GlobalSceneGraph().root() ) );
1174                 brushpath.push( makeReference( *Map_GetWorldspawn( g_map ) ) );
1175                 brushpath.push( makeReference( node.get() ) );
1176                 selectPath( brushpath, true );
1177
1178                 m_NewBrushDrag = node.get_pointer();
1179         }
1180
1181         // d1223m
1182         //Scene_BrushResize_Selected(GlobalSceneGraph(), aabb_for_minmax(mins, maxs), TextureBrowser_GetSelectedShader(GlobalTextureBrowser()));
1183         Scene_BrushResize_Selected( GlobalSceneGraph(), aabb_for_minmax( mins, maxs ),
1184                                                                 g_brush_always_caulk ?
1185                                                                 "textures/common/caulk" : TextureBrowser_GetSelectedShader( GlobalTextureBrowser() ) );
1186 }
1187
1188 void entitycreate_activated( GtkWidget* item ){
1189         scene::Node* world_node = Map_FindWorldspawn( g_map );
1190         const char* entity_name = gtk_label_get_text( GTK_LABEL( GTK_BIN( item )->child ) );
1191
1192         if ( !( world_node && string_equal( entity_name, "worldspawn" ) ) ) {
1193                 g_pParentWnd->ActiveXY()->OnEntityCreate( entity_name );
1194         }
1195         else {
1196                 GlobalRadiant().m_pfnMessageBox( GTK_WIDGET( MainFrame_getWindow() ), "There's already a worldspawn in your map!"
1197                                                                                                                                                           "",
1198                                                                                  "Info",
1199                                                                                  eMB_OK,
1200                                                                                  eMB_ICONDEFAULT );
1201         }
1202 }
1203
1204 void EntityClassMenu_addItem( GtkMenu* menu, const char* name ){
1205         GtkMenuItem* item = GTK_MENU_ITEM( gtk_menu_item_new_with_label( name ) );
1206         g_signal_connect( G_OBJECT( item ), "activate", G_CALLBACK( entitycreate_activated ), item );
1207         gtk_widget_show( GTK_WIDGET( item ) );
1208         menu_add_item( menu, item );
1209 }
1210
1211 class EntityClassMenuInserter : public EntityClassVisitor
1212 {
1213 typedef std::pair<GtkMenu*, CopiedString> MenuPair;
1214 typedef std::vector<MenuPair> MenuStack;
1215 MenuStack m_stack;
1216 CopiedString m_previous;
1217 public:
1218 EntityClassMenuInserter( GtkMenu* menu ){
1219         m_stack.reserve( 2 );
1220         m_stack.push_back( MenuPair( menu, "" ) );
1221 }
1222 ~EntityClassMenuInserter(){
1223         if ( !string_empty( m_previous.c_str() ) ) {
1224                 addItem( m_previous.c_str(), "" );
1225         }
1226 }
1227 void visit( EntityClass* e ){
1228         ASSERT_MESSAGE( !string_empty( e->name() ), "entity-class has no name" );
1229         if ( !string_empty( m_previous.c_str() ) ) {
1230                 addItem( m_previous.c_str(), e->name() );
1231         }
1232         m_previous = e->name();
1233 }
1234 void pushMenu( const CopiedString& name ){
1235         GtkMenuItem* item = GTK_MENU_ITEM( gtk_menu_item_new_with_label( name.c_str() ) );
1236         gtk_widget_show( GTK_WIDGET( item ) );
1237         container_add_widget( GTK_CONTAINER( m_stack.back().first ), GTK_WIDGET( item ) );
1238
1239         GtkMenu* submenu = GTK_MENU( gtk_menu_new() );
1240         gtk_menu_item_set_submenu( item, GTK_WIDGET( submenu ) );
1241
1242         m_stack.push_back( MenuPair( submenu, name ) );
1243 }
1244 void popMenu(){
1245         m_stack.pop_back();
1246 }
1247 void addItem( const char* name, const char* next ){
1248         const char* underscore = strchr( name, '_' );
1249
1250         if ( underscore != 0 && underscore != name ) {
1251                 bool nextEqual = string_equal_n( name, next, ( underscore + 1 ) - name );
1252                 const char* parent = m_stack.back().second.c_str();
1253
1254                 if ( !string_empty( parent )
1255                          && string_length( parent ) == std::size_t( underscore - name )
1256                          && string_equal_n( name, parent, underscore - name ) ) { // this is a child
1257                 }
1258                 else if ( nextEqual ) {
1259                         if ( m_stack.size() == 2 ) {
1260                                 popMenu();
1261                         }
1262                         pushMenu( CopiedString( StringRange( name, underscore ) ) );
1263                 }
1264                 else if ( m_stack.size() == 2 ) {
1265                         popMenu();
1266                 }
1267         }
1268         else if ( m_stack.size() == 2 ) {
1269                 popMenu();
1270         }
1271
1272         EntityClassMenu_addItem( m_stack.back().first, name );
1273 }
1274 };
1275
1276 void XYWnd::OnContextMenu(){
1277 //      if ( g_xywindow_globals.m_bRightClick == false ) {
1278 //              return;
1279 //      }
1280
1281         if ( m_mnuDrop == 0 ) { // first time, load it up
1282                 GtkMenu* menu = m_mnuDrop = GTK_MENU( gtk_menu_new() );
1283
1284                 EntityClassMenuInserter inserter( menu );
1285                 GlobalEntityClassManager().forEach( inserter );
1286         }
1287
1288         gtk_menu_popup( m_mnuDrop, 0, 0, 0, 0, 1, GDK_CURRENT_TIME );
1289 }
1290
1291 FreezePointer g_xywnd_freezePointer;
1292
1293 unsigned int Move_buttons(){
1294         return RAD_RBUTTON;
1295 }
1296
1297 void XYWnd_moveDelta( int x, int y, unsigned int state, void* data ){
1298         reinterpret_cast<XYWnd*>( data )->EntityCreate_MouseMove( x, y );
1299         reinterpret_cast<XYWnd*>( data )->Scroll( -x, y );
1300 }
1301
1302 gboolean XYWnd_Move_focusOut( GtkWidget* widget, GdkEventFocus* event, XYWnd* xywnd ){
1303         xywnd->Move_End();
1304         return FALSE;
1305 }
1306
1307 void XYWnd::Move_Begin(){
1308         if ( m_move_started ) {
1309                 Move_End();
1310         }
1311         m_move_started = true;
1312         g_xywnd_freezePointer.freeze_pointer( m_parent != 0 ? m_parent : MainFrame_getWindow(), m_gl_widget, XYWnd_moveDelta, this );
1313         m_move_focusOut = g_signal_connect( G_OBJECT( m_gl_widget ), "focus_out_event", G_CALLBACK( XYWnd_Move_focusOut ), this );
1314 }
1315
1316 void XYWnd::Move_End(){
1317         m_move_started = false;
1318         g_xywnd_freezePointer.unfreeze_pointer( m_parent != 0 ? m_parent : MainFrame_getWindow(), false );
1319         g_signal_handler_disconnect( G_OBJECT( m_gl_widget ), m_move_focusOut );
1320 }
1321
1322 unsigned int Zoom_buttons(){
1323         return RAD_RBUTTON | RAD_ALT;
1324 }
1325
1326 int g_dragZoom = 0;
1327 int g_zoom2x = 0;
1328 int g_zoom2y = 0;
1329
1330 void XYWnd_zoomDelta( int x, int y, unsigned int state, void* data ){
1331         if ( y != 0 ) {
1332                 g_dragZoom += y;
1333                 while ( abs( g_dragZoom ) > 8 )
1334                 {
1335                         if ( g_dragZoom > 0 ) {
1336                                 reinterpret_cast<XYWnd*>( data )->ZoomOut();
1337                                 g_dragZoom -= 8;
1338                         }
1339                         else
1340                         {
1341                                 if ( g_xywindow_globals.m_bZoomInToPointer ) {
1342                                         reinterpret_cast<XYWnd*>( data )->ZoomInWithMouse( g_zoom2x, g_zoom2y );
1343                                 }
1344                                 else{
1345                                         reinterpret_cast<XYWnd*>( data )->ZoomIn();
1346                                 }
1347                                 g_dragZoom += 8;
1348                         }
1349                 }
1350         }
1351 }
1352
1353 gboolean XYWnd_Zoom_focusOut( GtkWidget* widget, GdkEventFocus* event, XYWnd* xywnd ){
1354         xywnd->Zoom_End();
1355         return FALSE;
1356 }
1357
1358 void XYWnd::Zoom_Begin( int x, int y ){
1359         if ( m_zoom_started ) {
1360                 Zoom_End();
1361         }
1362         m_zoom_started = true;
1363         g_dragZoom = 0;
1364         g_zoom2x = x;
1365         g_zoom2y = y;
1366         g_xywnd_freezePointer.freeze_pointer( m_parent != 0 ? m_parent : MainFrame_getWindow(), m_gl_widget, XYWnd_zoomDelta, this );
1367         m_zoom_focusOut = g_signal_connect( G_OBJECT( m_gl_widget ), "focus_out_event", G_CALLBACK( XYWnd_Zoom_focusOut ), this );
1368 }
1369
1370 void XYWnd::Zoom_End(){
1371         m_zoom_started = false;
1372         g_xywnd_freezePointer.unfreeze_pointer( m_parent != 0 ? m_parent : MainFrame_getWindow(), false );
1373         g_signal_handler_disconnect( G_OBJECT( m_gl_widget ), m_zoom_focusOut );
1374 }
1375
1376 // makes sure the selected brush or camera is in view
1377 void XYWnd::PositionView( const Vector3& position ){
1378         int nDim1 = ( m_viewType == YZ ) ? 1 : 0;
1379         int nDim2 = ( m_viewType == XY ) ? 1 : 2;
1380
1381         m_vOrigin[nDim1] = position[nDim1];
1382         m_vOrigin[nDim2] = position[nDim2];
1383
1384         updateModelview();
1385
1386         XYWnd_Update( *this );
1387 }
1388
1389 void XYWnd::SetViewType( VIEWTYPE viewType ){
1390         m_viewType = viewType;
1391         updateModelview();
1392
1393         if ( m_parent != 0 ) {
1394                 gtk_window_set_title( m_parent, ViewType_getTitle( m_viewType ) );
1395         }
1396 }
1397
1398
1399 inline WindowVector WindowVector_forInteger( int x, int y ){
1400         return WindowVector( static_cast<float>( x ), static_cast<float>( y ) );
1401 }
1402
1403 void XYWnd::mouseDown( const WindowVector& position, ButtonIdentifier button, ModifierFlags modifiers ){
1404         XY_MouseDown( static_cast<int>( position.x() ), static_cast<int>( position.y() ), buttons_for_button_and_modifiers( button, modifiers ) );
1405 }
1406 void XYWnd::XY_MouseDown( int x, int y, unsigned int buttons ){
1407         if ( buttons == Move_buttons() ) {
1408                 Move_Begin();
1409                 EntityCreate_MouseDown( x, y );
1410         }
1411         else if ( buttons == Zoom_buttons() ) {
1412                 Zoom_Begin( x, y );
1413         }
1414         else if ( ClipMode() && ( buttons == Clipper_buttons() || buttons == Clipper_quick_buttons() ) ) {
1415                 Clipper_OnLButtonDown( x, y );
1416         }
1417         else if ( !ClipMode() && buttons == Clipper_quick_buttons() ) {
1418                 ClipperMode();
1419                 g_quick_clipper = true;
1420                 Clipper_OnLButtonDown( x, y );
1421         }
1422         else if ( buttons == NewBrushDrag_buttons() && GlobalSelectionSystem().countSelected() == 0 ) {
1423                 NewBrushDrag_Begin( x, y );
1424         }
1425         // control mbutton = move camera
1426         else if ( buttons == MoveCamera_buttons() ) {
1427                 XYWnd_PositionCamera( this, x, y, *g_pParentWnd->GetCamWnd() );
1428         }
1429         // mbutton = angle camera
1430         else if ( buttons == OrientCamera_buttons() ) {
1431                 XYWnd_OrientCamera( this, x, y, *g_pParentWnd->GetCamWnd() );
1432         }
1433         else if ( buttons == SetCustomPivotOrigin_buttons() ) {
1434                 SetCustomPivotOrigin( x, y );
1435         }
1436         else
1437         {
1438                 m_window_observer->onMouseDown( WindowVector_forInteger( x, y ), button_for_flags( buttons ), modifiers_for_flags( buttons ) );
1439         }
1440 }
1441
1442 void XYWnd::XY_MouseUp( int x, int y, unsigned int buttons ){
1443         if ( m_move_started ) {
1444                 Move_End();
1445                 EntityCreate_MouseUp( x, y );
1446         }
1447         else if ( m_zoom_started ) {
1448                 Zoom_End();
1449         }
1450         else if ( ClipMode() && ( buttons == Clipper_buttons() || buttons == Clipper_quick_buttons() ) ) {
1451                 Clipper_OnLButtonUp( x, y );
1452         }
1453         else if ( m_bNewBrushDrag ) {
1454                 m_bNewBrushDrag = false;
1455                 NewBrushDrag_End( x, y );
1456                 if ( m_NewBrushDrag == 0 ) {
1457                         //L button w/o created brush = tunnel selection
1458                         m_window_observer->onMouseUp( WindowVector_forInteger( x, y ), button_for_flags( buttons ), modifiers_for_flags( buttons ) );
1459                 }
1460         }
1461         else
1462         {
1463                 m_window_observer->onMouseUp( WindowVector_forInteger( x, y ), button_for_flags( buttons ), modifiers_for_flags( buttons ) );
1464         }
1465 }
1466
1467 void XYWnd::XY_MouseMoved( int x, int y, unsigned int buttons ){
1468         // rbutton = drag xy origin
1469         if ( m_move_started ) {
1470         }
1471         // zoom in/out
1472         else if ( m_zoom_started ) {
1473         }
1474
1475         else if ( ClipMode() && g_pMovingClip != 0 ) {
1476                 Clipper_OnMouseMoved( x, y );
1477         }
1478         // lbutton without selection = drag new brush
1479         else if ( m_bNewBrushDrag ) {
1480                 NewBrushDrag( x, y );
1481         }
1482
1483         // control mbutton = move camera
1484         else if ( buttons == MoveCamera_buttons() ) {
1485                 XYWnd_PositionCamera( this, x, y, *g_pParentWnd->GetCamWnd() );
1486         }
1487
1488         // mbutton = angle camera
1489         else if ( buttons == OrientCamera_buttons() ) {
1490                 XYWnd_OrientCamera( this, x, y, *g_pParentWnd->GetCamWnd() );
1491         }
1492
1493         else if ( buttons == SetCustomPivotOrigin_buttons() ) {
1494                 SetCustomPivotOrigin( x, y );
1495         }
1496
1497         else
1498         {
1499                 m_window_observer->onMouseMotion( WindowVector_forInteger( x, y ), modifiers_for_flags( buttons ) );
1500
1501                 m_mousePosition[0] = m_mousePosition[1] = m_mousePosition[2] = 0.0;
1502                 XY_ToPoint( x, y, m_mousePosition );
1503                 XY_SnapToGrid( m_mousePosition );
1504
1505                 StringOutputStream status( 64 );
1506                 status << "x:: " << FloatFormat( m_mousePosition[0], 6, 1 )
1507                            << "  y:: " << FloatFormat( m_mousePosition[1], 6, 1 )
1508                            << "  z:: " << FloatFormat( m_mousePosition[2], 6, 1 );
1509                 g_pParentWnd->SetStatusText( g_pParentWnd->m_position_status, status.c_str() );
1510
1511                 if ( g_bCrossHairs ) {
1512                         XYWnd_Update( *this );
1513                 }
1514
1515                 Clipper_Crosshair_OnMouseMoved( x, y );
1516         }
1517 }
1518
1519 void XYWnd::EntityCreate_MouseDown( int x, int y ){
1520         m_entityCreate = true;
1521         m_entityCreate_x = x;
1522         m_entityCreate_y = y;
1523 }
1524
1525 void XYWnd::EntityCreate_MouseMove( int x, int y ){
1526         if ( m_entityCreate && ( m_entityCreate_x != x || m_entityCreate_y != y ) ) {
1527                 m_entityCreate = false;
1528         }
1529 }
1530
1531 void XYWnd::EntityCreate_MouseUp( int x, int y ){
1532         if ( m_entityCreate ) {
1533                 m_entityCreate = false;
1534                 OnContextMenu();
1535         }
1536 }
1537
1538 inline float screen_normalised( int pos, unsigned int size ){
1539         return ( ( 2.0f * pos ) / size ) - 1.0f;
1540 }
1541
1542 inline float normalised_to_world( float normalised, float world_origin, float normalised2world_scale ){
1543         return world_origin + normalised * normalised2world_scale;
1544 }
1545
1546
1547 // TTimo: watch it, this doesn't init one of the 3 coords
1548 void XYWnd::XY_ToPoint( int x, int y, Vector3& point ){
1549         float normalised2world_scale_x = m_nWidth / 2 / m_fScale;
1550         float normalised2world_scale_y = m_nHeight / 2 / m_fScale;
1551         if ( m_viewType == XY ) {
1552                 point[0] = normalised_to_world( screen_normalised( x, m_nWidth ), m_vOrigin[0], normalised2world_scale_x );
1553                 point[1] = normalised_to_world( -screen_normalised( y, m_nHeight ), m_vOrigin[1], normalised2world_scale_y );
1554         }
1555         else if ( m_viewType == YZ ) {
1556                 point[1] = normalised_to_world( screen_normalised( x, m_nWidth ), m_vOrigin[1], normalised2world_scale_x );
1557                 point[2] = normalised_to_world( -screen_normalised( y, m_nHeight ), m_vOrigin[2], normalised2world_scale_y );
1558         }
1559         else
1560         {
1561                 point[0] = normalised_to_world( screen_normalised( x, m_nWidth ), m_vOrigin[0], normalised2world_scale_x );
1562                 point[2] = normalised_to_world( -screen_normalised( y, m_nHeight ), m_vOrigin[2], normalised2world_scale_y );
1563         }
1564 }
1565
1566 void XYWnd::XY_SnapToGrid( Vector3& point ){
1567         if ( m_viewType == XY ) {
1568                 point[0] = float_snapped( point[0], GetSnapGridSize() );
1569                 point[1] = float_snapped( point[1], GetSnapGridSize() );
1570         }
1571         else if ( m_viewType == YZ ) {
1572                 point[1] = float_snapped( point[1], GetSnapGridSize() );
1573                 point[2] = float_snapped( point[2], GetSnapGridSize() );
1574         }
1575         else
1576         {
1577                 point[0] = float_snapped( point[0], GetSnapGridSize() );
1578                 point[2] = float_snapped( point[2], GetSnapGridSize() );
1579         }
1580 }
1581
1582 void XYWnd::XY_LoadBackgroundImage( const char *name ){
1583         const char* relative = path_make_relative( name, GlobalFileSystem().findRoot( name ) );
1584         if ( relative == name ) {
1585                 globalOutputStream() << "WARNING: could not extract the relative path, using full path instead\n";
1586         }
1587
1588         char fileNameWithoutExt[512];
1589         strncpy( fileNameWithoutExt, relative, sizeof( fileNameWithoutExt ) - 1 );
1590         fileNameWithoutExt[512 - 1] = '\0';
1591         fileNameWithoutExt[strlen( fileNameWithoutExt ) - 4] = '\0';
1592
1593         Image *image = QERApp_LoadImage( 0, fileNameWithoutExt );
1594         if ( !image ) {
1595                 globalOutputStream() << "Could not load texture " << fileNameWithoutExt << "\n";
1596                 return;
1597         }
1598         g_pParentWnd->ActiveXY()->m_tex = (qtexture_t*)malloc( sizeof( qtexture_t ) );
1599         LoadTextureRGBA( g_pParentWnd->ActiveXY()->XYWnd::m_tex, image->getRGBAPixels(), image->getWidth(), image->getHeight() );
1600         globalOutputStream() << "Loaded background texture " << relative << "\n";
1601         g_pParentWnd->ActiveXY()->m_backgroundActivated = true;
1602
1603         int m_ix, m_iy;
1604         switch ( g_pParentWnd->ActiveXY()->m_viewType )
1605         {
1606         case XY:
1607                 m_ix = 0;
1608                 m_iy = 1;
1609                 break;
1610         case XZ:
1611                 m_ix = 0;
1612                 m_iy = 2;
1613                 break;
1614         case YZ:
1615                 m_ix = 1;
1616                 m_iy = 2;
1617                 break;
1618         }
1619
1620         Vector3 min, max;
1621         Select_GetBounds( min, max );
1622         g_pParentWnd->ActiveXY()->m_xmin = min[m_ix];
1623         g_pParentWnd->ActiveXY()->m_ymin = min[m_iy];
1624         g_pParentWnd->ActiveXY()->m_xmax = max[m_ix];
1625         g_pParentWnd->ActiveXY()->m_ymax = max[m_iy];
1626 }
1627
1628 void XYWnd::XY_DisableBackground( void ){
1629         g_pParentWnd->ActiveXY()->m_backgroundActivated = false;
1630         if ( g_pParentWnd->ActiveXY()->m_tex ) {
1631                 free( g_pParentWnd->ActiveXY()->m_tex );
1632         }
1633         g_pParentWnd->ActiveXY()->m_tex = NULL;
1634 }
1635
1636 void WXY_BackgroundSelect( void ){
1637         bool brushesSelected = Scene_countSelectedBrushes( GlobalSceneGraph() ) != 0;
1638         if ( !brushesSelected ) {
1639                 gtk_MessageBox( 0, "You have to select some brushes to get the bounding box for.\n",
1640                                                 "No selection", eMB_OK, eMB_ICONERROR );
1641                 return;
1642         }
1643
1644         const char *filename = file_dialog( GTK_WIDGET( MainFrame_getWindow() ), TRUE, "Background Image", NULL, NULL );
1645         g_pParentWnd->ActiveXY()->XY_DisableBackground();
1646         if ( filename ) {
1647                 g_pParentWnd->ActiveXY()->XY_LoadBackgroundImage( filename );
1648         }
1649 }
1650
1651 /*
1652    ============================================================================
1653
1654    DRAWING
1655
1656    ============================================================================
1657  */
1658
1659 /*
1660    ==============
1661    XY_DrawGrid
1662    ==============
1663  */
1664
1665 double two_to_the_power( int power ){
1666         return pow( 2.0f, power );
1667 }
1668
1669 void XYWnd::XY_DrawAxis( void ){
1670         if ( g_xywindow_globals_private.show_axis ) {
1671                 const char g_AxisName[3] = { 'X', 'Y', 'Z' };
1672                 const int nDim1 = ( m_viewType == YZ ) ? 1 : 0;
1673                 const int nDim2 = ( m_viewType == XY ) ? 1 : 2;
1674                 const int w = ( m_nWidth / 2 / m_fScale );
1675                 const int h = ( m_nHeight / 2 / m_fScale );
1676
1677                 Vector3 colourX = ( m_viewType == YZ ) ? g_xywindow_globals.AxisColorY : g_xywindow_globals.AxisColorX;
1678                 Vector3 colourY = ( m_viewType == XY ) ? g_xywindow_globals.AxisColorY : g_xywindow_globals.AxisColorZ;
1679                 if( !Active() ){
1680                         float grayX = vector3_dot( colourX, Vector3( 0.2989, 0.5870, 0.1140 ) );
1681                         float grayY = vector3_dot( colourY, Vector3( 0.2989, 0.5870, 0.1140 ) );
1682                         colourX[0] = colourX[1] = colourX[2] = grayX;
1683                         colourY[0] = colourY[1] = colourY[2] = grayY;
1684                 }
1685
1686                 // draw two lines with corresponding axis colors to highlight current view
1687                 // horizontal line: nDim1 color
1688                 glLineWidth( 2 );
1689                 glBegin( GL_LINES );
1690                 glColor3fv( vector3_to_array( colourX ) );
1691                 glVertex2f( m_vOrigin[nDim1] - w + 40 / m_fScale, m_vOrigin[nDim2] + h - 45 / m_fScale );
1692                 glVertex2f( m_vOrigin[nDim1] - w + 65 / m_fScale, m_vOrigin[nDim2] + h - 45 / m_fScale );
1693                 glVertex2f( 0, 0 );
1694                 glVertex2f( 32 / m_fScale, 0 );
1695                 glColor3fv( vector3_to_array( colourY ) );
1696                 glVertex2f( m_vOrigin[nDim1] - w + 40 / m_fScale, m_vOrigin[nDim2] + h - 45 / m_fScale );
1697                 glVertex2f( m_vOrigin[nDim1] - w + 40 / m_fScale, m_vOrigin[nDim2] + h - 20 / m_fScale );
1698                 glVertex2f( 0, 0 );
1699                 glVertex2f( 0, 32 / m_fScale );
1700                 glEnd();
1701                 glLineWidth( 1 );
1702                 // now print axis symbols
1703                 glColor3fv( vector3_to_array( colourX ) );
1704                 glRasterPos2f( m_vOrigin[nDim1] - w + 55 / m_fScale, m_vOrigin[nDim2] + h - 55 / m_fScale );
1705                 GlobalOpenGL().drawChar( g_AxisName[nDim1] );
1706                 glRasterPos2f( 28 / m_fScale, -10 / m_fScale );
1707                 GlobalOpenGL().drawChar( g_AxisName[nDim1] );
1708                 glColor3fv( vector3_to_array( colourY ) );
1709                 glRasterPos2f( m_vOrigin[nDim1] - w + 25 / m_fScale, m_vOrigin[nDim2] + h - 30 / m_fScale );
1710                 GlobalOpenGL().drawChar( g_AxisName[nDim2] );
1711                 glRasterPos2f( -10 / m_fScale, 28 / m_fScale );
1712                 GlobalOpenGL().drawChar( g_AxisName[nDim2] );
1713         }
1714 }
1715
1716 void XYWnd::RenderActive( void ){
1717         if ( glwidget_make_current( m_gl_widget ) != FALSE ) {
1718                 if ( Map_Valid( g_map ) && ScreenUpdates_Enabled() ) {
1719                         GlobalOpenGL_debugAssertNoErrors();
1720                         glDrawBuffer( GL_FRONT );
1721
1722                         if ( g_xywindow_globals_private.show_outline ) {
1723                                 glMatrixMode( GL_PROJECTION );
1724                                 glLoadIdentity();
1725                                 glOrtho( 0, m_nWidth, 0, m_nHeight, 0, 1 );
1726
1727                                 glMatrixMode( GL_MODELVIEW );
1728                                 glLoadIdentity();
1729
1730                                 if( !Active() ){ //sorta erase
1731                                         glColor3fv( vector3_to_array( g_xywindow_globals.color_gridmajor ) );
1732                                 }
1733                                 // four view mode doesn't colorize
1734                                 else if ( g_pParentWnd->CurrentStyle() == MainFrame::eSplit ) {
1735                                         glColor3fv( vector3_to_array( g_xywindow_globals.color_viewname ) );
1736                                 }
1737                                 else
1738                                 {
1739                                         switch ( m_viewType )
1740                                         {
1741                                         case YZ:
1742                                                 glColor3fv( vector3_to_array( g_xywindow_globals.AxisColorX ) );
1743                                                 break;
1744                                         case XZ:
1745                                                 glColor3fv( vector3_to_array( g_xywindow_globals.AxisColorY ) );
1746                                                 break;
1747                                         case XY:
1748                                                 glColor3fv( vector3_to_array( g_xywindow_globals.AxisColorZ ) );
1749                                                 break;
1750                                         }
1751                                 }
1752                                 glBegin( GL_LINE_LOOP );
1753                                 glVertex2f( 0.5, 0.5 );
1754                                 glVertex2f( m_nWidth - 0.5, 1 );
1755                                 glVertex2f( m_nWidth - 0.5, m_nHeight - 0.5 );
1756                                 glVertex2f( 0.5, m_nHeight - 0.5 );
1757                                 glEnd();
1758                         }
1759                         // we do this part (the old way) only if show_axis is disabled
1760                         if ( !g_xywindow_globals_private.show_axis ) {
1761                                 glMatrixMode( GL_PROJECTION );
1762                                 glLoadIdentity();
1763                                 glOrtho( 0, m_nWidth, 0, m_nHeight, 0, 1 );
1764
1765                                 glMatrixMode( GL_MODELVIEW );
1766                                 glLoadIdentity();
1767
1768                                 if ( Active() ) {
1769                                         glColor3fv( vector3_to_array( g_xywindow_globals.color_viewname ) );
1770                                 }
1771                                 else{
1772                                         glColor4fv( vector4_to_array( Vector4( g_xywindow_globals.color_gridtext, 1.0f ) ) );
1773                                 }
1774
1775                                 glDisable( GL_BLEND );
1776                                 glRasterPos2f( 35, m_nHeight - 20 );
1777
1778                                 GlobalOpenGL().drawString( ViewType_getTitle( m_viewType ) );
1779                         }
1780                         else{
1781                                 // clear
1782                                 glViewport( 0, 0, m_nWidth, m_nHeight );
1783                                 // set up viewpoint
1784                                 glMatrixMode( GL_PROJECTION );
1785                                 glLoadMatrixf( reinterpret_cast<const float*>( &m_projection ) );
1786
1787                                 glMatrixMode( GL_MODELVIEW );
1788                                 glLoadIdentity();
1789                                 glScalef( m_fScale, m_fScale, 1 );
1790                                 int nDim1 = ( m_viewType == YZ ) ? 1 : 0;
1791                                 int nDim2 = ( m_viewType == XY ) ? 1 : 2;
1792                                 glTranslatef( -m_vOrigin[nDim1], -m_vOrigin[nDim2], 0 );
1793
1794                                 glDisable( GL_LINE_STIPPLE );
1795                                 glDisableClientState( GL_TEXTURE_COORD_ARRAY );
1796                                 glDisableClientState( GL_NORMAL_ARRAY );
1797                                 glDisableClientState( GL_COLOR_ARRAY );
1798                                 glDisable( GL_TEXTURE_2D );
1799                                 glDisable( GL_LIGHTING );
1800                                 glDisable( GL_COLOR_MATERIAL );
1801                                 glDisable( GL_DEPTH_TEST );
1802                                 glDisable( GL_TEXTURE_1D );
1803                                 glDisable( GL_BLEND );
1804
1805                                 XYWnd::XY_DrawAxis();
1806                         }
1807
1808                         glDrawBuffer( GL_BACK );
1809                         GlobalOpenGL_debugAssertNoErrors();
1810                         glwidget_make_current( m_gl_widget );
1811                 }
1812         }
1813 }
1814
1815 void XYWnd::XY_DrawBackground( void ){
1816         glPushAttrib( GL_ALL_ATTRIB_BITS );
1817
1818         glEnable( GL_TEXTURE_2D );
1819         glEnable( GL_BLEND );
1820         glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA );
1821         glTexEnvf( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE );
1822         glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP );
1823         glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP );
1824
1825         glPolygonMode( GL_FRONT, GL_FILL );
1826
1827         glBindTexture( GL_TEXTURE_2D, m_tex->texture_number );
1828         glBegin( GL_QUADS );
1829
1830         glColor4f( 1.0, 1.0, 1.0, m_alpha );
1831         glTexCoord2f( 0.0, 1.0 );
1832         glVertex2f( m_xmin, m_ymin );
1833
1834         glTexCoord2f( 1.0, 1.0 );
1835         glVertex2f( m_xmax, m_ymin );
1836
1837         glTexCoord2f( 1.0, 0.0 );
1838         glVertex2f( m_xmax, m_ymax );
1839
1840         glTexCoord2f( 0.0, 0.0 );
1841         glVertex2f( m_xmin, m_ymax );
1842
1843         glEnd();
1844         glBindTexture( GL_TEXTURE_2D, 0 );
1845
1846         glPopAttrib();
1847 }
1848
1849 void XYWnd::XY_DrawGrid( void ) {
1850         float x, y, xb, xe, yb, ye;
1851         float w, h, a;
1852         char text[32];
1853         float step, minor_step, stepx, stepy;
1854         step = minor_step = stepx = stepy = GetGridSize();
1855
1856         int minor_power = Grid_getPower();
1857         int mask;
1858
1859         while ( ( minor_step * m_fScale ) <= 4.0f ) { // make sure minor grid spacing is at least 4 pixels on the screen
1860                 ++minor_power;
1861                 minor_step *= 2;
1862         }
1863         int power = minor_power;
1864         while ( ( power % 3 ) != 0 || ( step * m_fScale ) <= 32.0f ) { // make sure major grid spacing is at least 32 pixels on the screen
1865                 ++power;
1866                 step = float(two_to_the_power( power ) );
1867         }
1868         mask = ( 1 << ( power - minor_power ) ) - 1;
1869         while ( ( stepx * m_fScale ) <= 32.0f ) // text step x must be at least 32
1870                 stepx *= 2;
1871         while ( ( stepy * m_fScale ) <= 32.0f ) // text step y must be at least 32
1872                 stepy *= 2;
1873
1874         a = ( ( GetSnapGridSize() > 0.0f ) ? 1.0f : 0.3f );
1875
1876         glDisable( GL_TEXTURE_2D );
1877         glDisable( GL_TEXTURE_1D );
1878         glDisable( GL_DEPTH_TEST );
1879         glDisable( GL_BLEND );
1880         glLineWidth( 1 );
1881
1882         w = ( m_nWidth / 2 / m_fScale );
1883         h = ( m_nHeight / 2 / m_fScale );
1884
1885         const int nDim1 = ( m_viewType == YZ ) ? 1 : 0;
1886         const int nDim2 = ( m_viewType == XY ) ? 1 : 2;
1887
1888         xb = m_vOrigin[nDim1] - w;
1889         if ( xb < region_mins[nDim1] ) {
1890                 xb = region_mins[nDim1];
1891         }
1892         xb = step * floor( xb / step );
1893
1894         xe = m_vOrigin[nDim1] + w;
1895         if ( xe > region_maxs[nDim1] ) {
1896                 xe = region_maxs[nDim1];
1897         }
1898         xe = step * ceil( xe / step );
1899
1900         yb = m_vOrigin[nDim2] - h;
1901         if ( yb < region_mins[nDim2] ) {
1902                 yb = region_mins[nDim2];
1903         }
1904         yb = step * floor( yb / step );
1905
1906         ye = m_vOrigin[nDim2] + h;
1907         if ( ye > region_maxs[nDim2] ) {
1908                 ye = region_maxs[nDim2];
1909         }
1910         ye = step * ceil( ye / step );
1911
1912 #define COLORS_DIFFER( a,b ) \
1913         ( ( a )[0] != ( b )[0] || \
1914           ( a )[1] != ( b )[1] || \
1915           ( a )[2] != ( b )[2] )
1916
1917         // djbob
1918         // draw minor blocks
1919         if ( g_xywindow_globals_private.d_showgrid || a < 1.0f ) {
1920                 if ( a < 1.0f ) {
1921                         glEnable( GL_BLEND );
1922                 }
1923
1924                 if ( COLORS_DIFFER( g_xywindow_globals.color_gridminor, g_xywindow_globals.color_gridback ) ) {
1925                         glColor4fv( vector4_to_array( Vector4( g_xywindow_globals.color_gridminor, a ) ) );
1926
1927                         glBegin( GL_LINES );
1928                         int i = 0;
1929                         for ( x = xb ; x < xe ; x += minor_step, ++i ) {
1930                                 if ( ( i & mask ) != 0 ) {
1931                                         glVertex2f( x, yb );
1932                                         glVertex2f( x, ye );
1933                                 }
1934                         }
1935                         i = 0;
1936                         for ( y = yb ; y < ye ; y += minor_step, ++i ) {
1937                                 if ( ( i & mask ) != 0 ) {
1938                                         glVertex2f( xb, y );
1939                                         glVertex2f( xe, y );
1940                                 }
1941                         }
1942                         glEnd();
1943                 }
1944
1945                 // draw major blocks
1946                 if ( COLORS_DIFFER( g_xywindow_globals.color_gridmajor, g_xywindow_globals.color_gridminor ) ) {
1947                         glColor4fv( vector4_to_array( Vector4( g_xywindow_globals.color_gridmajor, a ) ) );
1948
1949                         glBegin( GL_LINES );
1950                         for ( x = xb ; x <= xe ; x += step ) {
1951                                 glVertex2f( x, yb );
1952                                 glVertex2f( x, ye );
1953                         }
1954                         for ( y = yb ; y <= ye ; y += step ) {
1955                                 glVertex2f( xb, y );
1956                                 glVertex2f( xe, y );
1957                         }
1958                         glEnd();
1959                 }
1960
1961                 if ( a < 1.0f ) {
1962                         glDisable( GL_BLEND );
1963                 }
1964         }
1965
1966         // draw coordinate text if needed
1967         if ( g_xywindow_globals_private.show_coordinates ) {
1968                 glColor4fv( vector4_to_array( Vector4( g_xywindow_globals.color_gridtext, 1.0f ) ) );
1969                 float offx = m_vOrigin[nDim2] + h - ( 4 + GlobalOpenGL().m_font->getPixelAscent() ) / m_fScale;
1970                 float offy = m_vOrigin[nDim1] - w +  4                                            / m_fScale;
1971                 for ( x = xb - fmod( xb, stepx ); x <= xe ; x += stepx ) {
1972                         glRasterPos2f( x, offx );
1973                         sprintf( text, "%g", x );
1974                         GlobalOpenGL().drawString( text );
1975                 }
1976                 for ( y = yb - fmod( yb, stepy ); y <= ye ; y += stepy ) {
1977                         glRasterPos2f( offy, y );
1978                         sprintf( text, "%g", y );
1979                         GlobalOpenGL().drawString( text );
1980                 }
1981
1982         }
1983         // we do this part (the old way) only if show_axis is disabled
1984         if ( !g_xywindow_globals_private.show_axis ) {
1985                 if ( Active() ) {
1986                         glColor3fv( vector3_to_array( g_xywindow_globals.color_viewname ) );
1987                 }
1988                 else{
1989                         glColor4fv( vector4_to_array( Vector4( g_xywindow_globals.color_gridtext, 1.0f ) ) );
1990                 }
1991
1992                 glRasterPos2f( m_vOrigin[nDim1] - w + 35 / m_fScale, m_vOrigin[nDim2] + h - 20 / m_fScale );
1993
1994                 GlobalOpenGL().drawString( ViewType_getTitle( m_viewType ) );
1995         }
1996
1997         XYWnd::XY_DrawAxis();
1998
1999         // show current work zone?
2000         // the work zone is used to place dropped points and brushes
2001         if ( g_xywindow_globals_private.d_show_work ) {
2002                 glColor4f( 1.0f, 0.0f, 0.0f, 1.0f );
2003                 glBegin( GL_LINES );
2004                 glVertex2f( xb, Select_getWorkZone().d_work_min[nDim2] );
2005                 glVertex2f( xe, Select_getWorkZone().d_work_min[nDim2] );
2006                 glVertex2f( xb, Select_getWorkZone().d_work_max[nDim2] );
2007                 glVertex2f( xe, Select_getWorkZone().d_work_max[nDim2] );
2008                 glVertex2f( Select_getWorkZone().d_work_min[nDim1], yb );
2009                 glVertex2f( Select_getWorkZone().d_work_min[nDim1], ye );
2010                 glVertex2f( Select_getWorkZone().d_work_max[nDim1], yb );
2011                 glVertex2f( Select_getWorkZone().d_work_max[nDim1], ye );
2012                 glEnd();
2013         }
2014 }
2015
2016 /*
2017    ==============
2018    XY_DrawBlockGrid
2019    ==============
2020  */
2021 void XYWnd::XY_DrawBlockGrid(){
2022         if ( Map_FindWorldspawn( g_map ) == 0 ) {
2023                 return;
2024         }
2025         const char *value = Node_getEntity( *Map_GetWorldspawn( g_map ) )->getKeyValue( "_blocksize" );
2026         if ( strlen( value ) ) {
2027                 sscanf( value, "%i", &g_xywindow_globals_private.blockSize );
2028         }
2029
2030         if ( !g_xywindow_globals_private.blockSize || g_xywindow_globals_private.blockSize > 65536 || g_xywindow_globals_private.blockSize < 1024 ) {
2031                 // don't use custom blocksize if it is less than the default, or greater than the maximum world coordinate
2032                 g_xywindow_globals_private.blockSize = 1024;
2033         }
2034
2035         float x, y, xb, xe, yb, ye;
2036         float w, h;
2037         char text[32];
2038
2039         glDisable( GL_TEXTURE_2D );
2040         glDisable( GL_TEXTURE_1D );
2041         glDisable( GL_DEPTH_TEST );
2042         glDisable( GL_BLEND );
2043
2044         w = ( m_nWidth / 2 / m_fScale );
2045         h = ( m_nHeight / 2 / m_fScale );
2046
2047         int nDim1 = ( m_viewType == YZ ) ? 1 : 0;
2048         int nDim2 = ( m_viewType == XY ) ? 1 : 2;
2049
2050         xb = m_vOrigin[nDim1] - w;
2051         if ( xb < region_mins[nDim1] ) {
2052                 xb = region_mins[nDim1];
2053         }
2054         xb = static_cast<float>( g_xywindow_globals_private.blockSize * floor( xb / g_xywindow_globals_private.blockSize ) );
2055
2056         xe = m_vOrigin[nDim1] + w;
2057         if ( xe > region_maxs[nDim1] ) {
2058                 xe = region_maxs[nDim1];
2059         }
2060         xe = static_cast<float>( g_xywindow_globals_private.blockSize * ceil( xe / g_xywindow_globals_private.blockSize ) );
2061
2062         yb = m_vOrigin[nDim2] - h;
2063         if ( yb < region_mins[nDim2] ) {
2064                 yb = region_mins[nDim2];
2065         }
2066         yb = static_cast<float>( g_xywindow_globals_private.blockSize * floor( yb / g_xywindow_globals_private.blockSize ) );
2067
2068         ye = m_vOrigin[nDim2] + h;
2069         if ( ye > region_maxs[nDim2] ) {
2070                 ye = region_maxs[nDim2];
2071         }
2072         ye = static_cast<float>( g_xywindow_globals_private.blockSize * ceil( ye / g_xywindow_globals_private.blockSize ) );
2073
2074         // draw major blocks
2075
2076         glColor3fv( vector3_to_array( g_xywindow_globals.color_gridblock ) );
2077         glLineWidth( 2 );
2078
2079         glBegin( GL_LINES );
2080
2081         for ( x = xb ; x <= xe ; x += g_xywindow_globals_private.blockSize )
2082         {
2083                 glVertex2f( x, yb );
2084                 glVertex2f( x, ye );
2085         }
2086
2087         if ( m_viewType == XY ) {
2088                 for ( y = yb ; y <= ye ; y += g_xywindow_globals_private.blockSize )
2089                 {
2090                         glVertex2f( xb, y );
2091                         glVertex2f( xe, y );
2092                 }
2093         }
2094
2095         glEnd();
2096         glLineWidth( 1 );
2097
2098         // draw coordinate text if needed
2099
2100         if ( m_viewType == XY && m_fScale > .1 ) {
2101                 for ( x = xb ; x < xe ; x += g_xywindow_globals_private.blockSize )
2102                         for ( y = yb ; y < ye ; y += g_xywindow_globals_private.blockSize )
2103                         {
2104                                 glRasterPos2f( x + ( g_xywindow_globals_private.blockSize / 2 ), y + ( g_xywindow_globals_private.blockSize / 2 ) );
2105                                 sprintf( text, "%i,%i",(int)floor( x / g_xywindow_globals_private.blockSize ), (int)floor( y / g_xywindow_globals_private.blockSize ) );
2106                                 GlobalOpenGL().drawString( text );
2107                         }
2108         }
2109
2110         glColor4f( 0, 0, 0, 0 );
2111 }
2112
2113 void XYWnd::DrawCameraIcon( const Vector3& origin, const Vector3& angles ){
2114         Cam.fov = 48 / m_fScale;
2115         Cam.box = 16 / m_fScale;
2116 //      globalOutputStream() << "pitch " << angles[CAMERA_PITCH] << "   yaw " << angles[CAMERA_YAW] << "\n";
2117
2118         if ( m_viewType == XY ) {
2119                 Cam.x = origin[0];
2120                 Cam.y = origin[1];
2121                 Cam.a = degrees_to_radians( angles[CAMERA_YAW] );
2122         }
2123         else if ( m_viewType == YZ ) {
2124                 Cam.x = origin[1];
2125                 Cam.y = origin[2];
2126                 Cam.a = degrees_to_radians( ( angles[CAMERA_YAW] > 180 ) ? ( 180.0f - angles[CAMERA_PITCH] ) : angles[CAMERA_PITCH] );
2127         }
2128         else
2129         {
2130                 Cam.x = origin[0];
2131                 Cam.y = origin[2];
2132                 Cam.a = degrees_to_radians( ( angles[CAMERA_YAW] < 270 && angles[CAMERA_YAW] > 90 ) ? ( 180.0f - angles[CAMERA_PITCH] ) : angles[CAMERA_PITCH] );
2133         }
2134
2135         //glColor3f( 0.0, 0.0, 1.0 );
2136         glColor3f( 1.0, 1.0, 1.0 );
2137         glBegin( GL_LINE_STRIP );
2138         glVertex3f( Cam.x - Cam.box,Cam.y,0 );
2139         glVertex3f( Cam.x,Cam.y + ( Cam.box / 2 ),0 );
2140         glVertex3f( Cam.x + Cam.box,Cam.y,0 );
2141         glVertex3f( Cam.x,Cam.y - ( Cam.box / 2 ),0 );
2142         glVertex3f( Cam.x - Cam.box,Cam.y,0 );
2143         glVertex3f( Cam.x + Cam.box,Cam.y,0 );
2144         glEnd();
2145
2146         glBegin( GL_LINE_STRIP );
2147         glVertex3f( Cam.x + static_cast<float>( Cam.fov * cos( Cam.a + c_pi / 4 ) ), Cam.y + static_cast<float>( Cam.fov * sin( Cam.a + c_pi / 4 ) ), 0 );
2148         glVertex3f( Cam.x, Cam.y, 0 );
2149         glVertex3f( Cam.x + static_cast<float>( Cam.fov * cos( Cam.a - c_pi / 4 ) ), Cam.y + static_cast<float>( Cam.fov * sin( Cam.a - c_pi / 4 ) ), 0 );
2150         glEnd();
2151
2152 }
2153
2154 void XYWnd::UpdateCameraIcon( void ){
2155         if ( glwidget_make_current( m_gl_widget ) != FALSE ) {
2156                 if ( Map_Valid( g_map ) && ScreenUpdates_Enabled() ) {
2157                         GlobalOpenGL_debugAssertNoErrors();
2158                         glDrawBuffer( GL_FRONT );
2159                         {
2160                                 // clear
2161                                 glViewport( 0, 0, m_nWidth, m_nHeight );
2162                                 // set up viewpoint
2163                                 glMatrixMode( GL_PROJECTION );
2164                                 glLoadMatrixf( reinterpret_cast<const float*>( &m_projection ) );
2165
2166                                 glMatrixMode( GL_MODELVIEW );
2167                                 glLoadIdentity();
2168                                 glScalef( m_fScale, m_fScale, 1 );
2169                                 int nDim1 = ( m_viewType == YZ ) ? 1 : 0;
2170                                 int nDim2 = ( m_viewType == XY ) ? 1 : 2;
2171                                 glTranslatef( -m_vOrigin[nDim1], -m_vOrigin[nDim2], 0 );
2172
2173                                 glDisable( GL_LINE_STIPPLE );
2174                                 glDisableClientState( GL_TEXTURE_COORD_ARRAY );
2175                                 glDisableClientState( GL_NORMAL_ARRAY );
2176                                 glDisableClientState( GL_COLOR_ARRAY );
2177                                 glDisable( GL_TEXTURE_2D );
2178                                 glDisable( GL_LIGHTING );
2179                                 glDisable( GL_COLOR_MATERIAL );
2180                                 glDisable( GL_DEPTH_TEST );
2181                                 glDisable( GL_TEXTURE_1D );
2182
2183                                 glEnable( GL_BLEND );
2184                                 glBlendFunc( GL_ONE_MINUS_DST_COLOR, GL_ZERO );
2185
2186                                 //glColor3f( 0.0, 0.0, 1.0 );
2187                                 glColor3f( 1.0, 1.0, 1.0 );
2188                                 glBegin( GL_LINE_STRIP );
2189                                 glVertex3f( Cam.x - Cam.box,Cam.y,0 );
2190                                 glVertex3f( Cam.x,Cam.y + ( Cam.box / 2 ),0 );
2191                                 glVertex3f( Cam.x + Cam.box,Cam.y,0 );
2192                                 glVertex3f( Cam.x,Cam.y - ( Cam.box / 2 ),0 );
2193                                 glVertex3f( Cam.x - Cam.box,Cam.y,0 );
2194                                 glVertex3f( Cam.x + Cam.box,Cam.y,0 );
2195                                 glEnd();
2196
2197                                 glBegin( GL_LINE_STRIP );
2198                                 glVertex3f( Cam.x + static_cast<float>( Cam.fov * cos( Cam.a + c_pi / 4 ) ), Cam.y + static_cast<float>( Cam.fov * sin( Cam.a + c_pi / 4 ) ), 0 );
2199                                 glVertex3f( Cam.x, Cam.y, 0 );
2200                                 glVertex3f( Cam.x + static_cast<float>( Cam.fov * cos( Cam.a - c_pi / 4 ) ), Cam.y + static_cast<float>( Cam.fov * sin( Cam.a - c_pi / 4 ) ), 0 );
2201                                 glEnd();
2202
2203                                 XYWnd::DrawCameraIcon( Camera_getOrigin( *g_pParentWnd->GetCamWnd() ), Camera_getAngles( *g_pParentWnd->GetCamWnd() ) );
2204
2205                                 glDisable( GL_BLEND );
2206                                 glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA );
2207                         }
2208
2209                         glDrawBuffer( GL_BACK );
2210                         GlobalOpenGL_debugAssertNoErrors();
2211                         glwidget_make_current( m_gl_widget );
2212                 }
2213         }
2214 }
2215
2216
2217 float Betwixt( float f1, float f2 ){
2218         if ( f1 > f2 ) {
2219                 return f2 + ( ( f1 - f2 ) / 2 );
2220         }
2221         else{
2222                 return f1 + ( ( f2 - f1 ) / 2 );
2223         }
2224 }
2225
2226
2227 // can be greatly simplified but per usual i am in a hurry
2228 // which is not an excuse, just a fact
2229 void XYWnd::PaintSizeInfo( int nDim1, int nDim2, Vector3& vMinBounds, Vector3& vMaxBounds ){
2230         if ( vector3_equal( vMinBounds, vMaxBounds ) ) {
2231                 return;
2232         }
2233         const char* g_pDimStrings[] = {"x:", "y:", "z:"};
2234         typedef const char* OrgStrings[2];
2235         const OrgStrings g_pOrgStrings[] = { { "x:", "y:", }, { "x:", "z:", }, { "y:", "z:", } };
2236
2237         Vector3 vSize( vector3_subtracted( vMaxBounds, vMinBounds ) );
2238
2239         glColor3f( g_xywindow_globals.color_selbrushes[0] * .65f,
2240                            g_xywindow_globals.color_selbrushes[1] * .65f,
2241                            g_xywindow_globals.color_selbrushes[2] * .65f );
2242
2243         StringOutputStream dimensions( 16 );
2244
2245         if ( m_viewType == XY ) {
2246                 glBegin( GL_LINES );
2247
2248                 glVertex3f( vMinBounds[nDim1], vMinBounds[nDim2] - 6.0f  / m_fScale, 0.0f );
2249                 glVertex3f( vMinBounds[nDim1], vMinBounds[nDim2] - 10.0f / m_fScale, 0.0f );
2250
2251                 glVertex3f( vMinBounds[nDim1], vMinBounds[nDim2] - 10.0f  / m_fScale, 0.0f );
2252                 glVertex3f( vMaxBounds[nDim1], vMinBounds[nDim2] - 10.0f  / m_fScale, 0.0f );
2253
2254                 glVertex3f( vMaxBounds[nDim1], vMinBounds[nDim2] - 6.0f  / m_fScale, 0.0f );
2255                 glVertex3f( vMaxBounds[nDim1], vMinBounds[nDim2] - 10.0f / m_fScale, 0.0f );
2256
2257
2258                 glVertex3f( vMaxBounds[nDim1] + 6.0f  / m_fScale, vMinBounds[nDim2], 0.0f );
2259                 glVertex3f( vMaxBounds[nDim1] + 10.0f  / m_fScale, vMinBounds[nDim2], 0.0f );
2260
2261                 glVertex3f( vMaxBounds[nDim1] + 10.0f  / m_fScale, vMinBounds[nDim2], 0.0f );
2262                 glVertex3f( vMaxBounds[nDim1] + 10.0f  / m_fScale, vMaxBounds[nDim2], 0.0f );
2263
2264                 glVertex3f( vMaxBounds[nDim1] + 6.0f  / m_fScale, vMaxBounds[nDim2], 0.0f );
2265                 glVertex3f( vMaxBounds[nDim1] + 10.0f  / m_fScale, vMaxBounds[nDim2], 0.0f );
2266
2267                 glEnd();
2268
2269                 glRasterPos3f( Betwixt( vMinBounds[nDim1], vMaxBounds[nDim1] ),  vMinBounds[nDim2] - 20.0f  / m_fScale, 0.0f );
2270                 dimensions << g_pDimStrings[nDim1] << vSize[nDim1];
2271                 GlobalOpenGL().drawString( dimensions.c_str() );
2272                 dimensions.clear();
2273
2274                 glRasterPos3f( vMaxBounds[nDim1] + 16.0f  / m_fScale, Betwixt( vMinBounds[nDim2], vMaxBounds[nDim2] ), 0.0f );
2275                 dimensions << g_pDimStrings[nDim2] << vSize[nDim2];
2276                 GlobalOpenGL().drawString( dimensions.c_str() );
2277                 dimensions.clear();
2278
2279                 glRasterPos3f( vMinBounds[nDim1] + 4, vMaxBounds[nDim2] + 8 / m_fScale, 0.0f );
2280                 dimensions << "(" << g_pOrgStrings[0][0] << vMinBounds[nDim1] << "  " << g_pOrgStrings[0][1] << vMaxBounds[nDim2] << ")";
2281                 GlobalOpenGL().drawString( dimensions.c_str() );
2282         }
2283         else if ( m_viewType == XZ ) {
2284                 glBegin( GL_LINES );
2285
2286                 glVertex3f( vMinBounds[nDim1], 0, vMinBounds[nDim2] - 6.0f  / m_fScale );
2287                 glVertex3f( vMinBounds[nDim1], 0, vMinBounds[nDim2] - 10.0f / m_fScale );
2288
2289                 glVertex3f( vMinBounds[nDim1], 0,vMinBounds[nDim2] - 10.0f  / m_fScale );
2290                 glVertex3f( vMaxBounds[nDim1], 0,vMinBounds[nDim2] - 10.0f  / m_fScale );
2291
2292                 glVertex3f( vMaxBounds[nDim1], 0,vMinBounds[nDim2] - 6.0f  / m_fScale );
2293                 glVertex3f( vMaxBounds[nDim1], 0,vMinBounds[nDim2] - 10.0f / m_fScale );
2294
2295
2296                 glVertex3f( vMaxBounds[nDim1] + 6.0f  / m_fScale, 0,vMinBounds[nDim2] );
2297                 glVertex3f( vMaxBounds[nDim1] + 10.0f  / m_fScale, 0,vMinBounds[nDim2] );
2298
2299                 glVertex3f( vMaxBounds[nDim1] + 10.0f  / m_fScale, 0,vMinBounds[nDim2] );
2300                 glVertex3f( vMaxBounds[nDim1] + 10.0f  / m_fScale, 0,vMaxBounds[nDim2] );
2301
2302                 glVertex3f( vMaxBounds[nDim1] + 6.0f  / m_fScale, 0,vMaxBounds[nDim2] );
2303                 glVertex3f( vMaxBounds[nDim1] + 10.0f  / m_fScale, 0,vMaxBounds[nDim2] );
2304
2305                 glEnd();
2306
2307                 glRasterPos3f( Betwixt( vMinBounds[nDim1], vMaxBounds[nDim1] ), 0, vMinBounds[nDim2] - 20.0f  / m_fScale );
2308                 dimensions << g_pDimStrings[nDim1] << vSize[nDim1];
2309                 GlobalOpenGL().drawString( dimensions.c_str() );
2310                 dimensions.clear();
2311
2312                 glRasterPos3f( vMaxBounds[nDim1] + 16.0f  / m_fScale, 0, Betwixt( vMinBounds[nDim2], vMaxBounds[nDim2] ) );
2313                 dimensions << g_pDimStrings[nDim2] << vSize[nDim2];
2314                 GlobalOpenGL().drawString( dimensions.c_str() );
2315                 dimensions.clear();
2316
2317                 glRasterPos3f( vMinBounds[nDim1] + 4, 0, vMaxBounds[nDim2] + 8 / m_fScale );
2318                 dimensions << "(" << g_pOrgStrings[1][0] << vMinBounds[nDim1] << "  " << g_pOrgStrings[1][1] << vMaxBounds[nDim2] << ")";
2319                 GlobalOpenGL().drawString( dimensions.c_str() );
2320         }
2321         else
2322         {
2323                 glBegin( GL_LINES );
2324
2325                 glVertex3f( 0, vMinBounds[nDim1], vMinBounds[nDim2] - 6.0f  / m_fScale );
2326                 glVertex3f( 0, vMinBounds[nDim1], vMinBounds[nDim2] - 10.0f / m_fScale );
2327
2328                 glVertex3f( 0, vMinBounds[nDim1], vMinBounds[nDim2] - 10.0f  / m_fScale );
2329                 glVertex3f( 0, vMaxBounds[nDim1], vMinBounds[nDim2] - 10.0f  / m_fScale );
2330
2331                 glVertex3f( 0, vMaxBounds[nDim1], vMinBounds[nDim2] - 6.0f  / m_fScale );
2332                 glVertex3f( 0, vMaxBounds[nDim1], vMinBounds[nDim2] - 10.0f / m_fScale );
2333
2334
2335                 glVertex3f( 0, vMaxBounds[nDim1] + 6.0f  / m_fScale, vMinBounds[nDim2] );
2336                 glVertex3f( 0, vMaxBounds[nDim1] + 10.0f  / m_fScale, vMinBounds[nDim2] );
2337
2338                 glVertex3f( 0, vMaxBounds[nDim1] + 10.0f  / m_fScale, vMinBounds[nDim2] );
2339                 glVertex3f( 0, vMaxBounds[nDim1] + 10.0f  / m_fScale, vMaxBounds[nDim2] );
2340
2341                 glVertex3f( 0, vMaxBounds[nDim1] + 6.0f  / m_fScale, vMaxBounds[nDim2] );
2342                 glVertex3f( 0, vMaxBounds[nDim1] + 10.0f  / m_fScale, vMaxBounds[nDim2] );
2343
2344                 glEnd();
2345
2346                 glRasterPos3f( 0, Betwixt( vMinBounds[nDim1], vMaxBounds[nDim1] ),  vMinBounds[nDim2] - 20.0f  / m_fScale );
2347                 dimensions << g_pDimStrings[nDim1] << vSize[nDim1];
2348                 GlobalOpenGL().drawString( dimensions.c_str() );
2349                 dimensions.clear();
2350
2351                 glRasterPos3f( 0, vMaxBounds[nDim1] + 16.0f  / m_fScale, Betwixt( vMinBounds[nDim2], vMaxBounds[nDim2] ) );
2352                 dimensions << g_pDimStrings[nDim2] << vSize[nDim2];
2353                 GlobalOpenGL().drawString( dimensions.c_str() );
2354                 dimensions.clear();
2355
2356                 glRasterPos3f( 0, vMinBounds[nDim1] + 4.0f, vMaxBounds[nDim2] + 8 / m_fScale );
2357                 dimensions << "(" << g_pOrgStrings[2][0] << vMinBounds[nDim1] << "  " << g_pOrgStrings[2][1] << vMaxBounds[nDim2] << ")";
2358                 GlobalOpenGL().drawString( dimensions.c_str() );
2359         }
2360 }
2361
2362 class XYRenderer : public Renderer
2363 {
2364 struct state_type
2365 {
2366         state_type() :
2367                 m_highlight( 0 ),
2368                 m_state( 0 ){
2369         }
2370         unsigned int m_highlight;
2371         Shader* m_state;
2372 };
2373 public:
2374 XYRenderer( RenderStateFlags globalstate, Shader* selected ) :
2375         m_globalstate( globalstate ),
2376         m_state_selected( selected ){
2377         ASSERT_NOTNULL( selected );
2378         m_state_stack.push_back( state_type() );
2379 }
2380
2381 void SetState( Shader* state, EStyle style ){
2382         ASSERT_NOTNULL( state );
2383         if ( style == eWireframeOnly ) {
2384                 m_state_stack.back().m_state = state;
2385         }
2386 }
2387 const EStyle getStyle() const {
2388         return eWireframeOnly;
2389 }
2390 void PushState(){
2391         m_state_stack.push_back( m_state_stack.back() );
2392 }
2393 void PopState(){
2394         ASSERT_MESSAGE( !m_state_stack.empty(), "popping empty stack" );
2395         m_state_stack.pop_back();
2396 }
2397 void Highlight( EHighlightMode mode, bool bEnable = true ){
2398         ( bEnable )
2399         ? m_state_stack.back().m_highlight |= mode
2400                                                                                   : m_state_stack.back().m_highlight &= ~mode;
2401 }
2402 void addRenderable( const OpenGLRenderable& renderable, const Matrix4& localToWorld ){
2403         if ( m_state_stack.back().m_highlight & ePrimitive ) {
2404                 m_state_selected->addRenderable( renderable, localToWorld );
2405         }
2406         else
2407         {
2408                 m_state_stack.back().m_state->addRenderable( renderable, localToWorld );
2409         }
2410 }
2411
2412 void render( const Matrix4& modelview, const Matrix4& projection ){
2413         GlobalShaderCache().render( m_globalstate, modelview, projection );
2414 }
2415 private:
2416 std::vector<state_type> m_state_stack;
2417 RenderStateFlags m_globalstate;
2418 Shader* m_state_selected;
2419 };
2420
2421 void XYWnd::updateProjection(){
2422         m_projection[0] = 1.0f / static_cast<float>( m_nWidth / 2 );
2423         m_projection[5] = 1.0f / static_cast<float>( m_nHeight / 2 );
2424         m_projection[10] = 1.0f / ( g_MaxWorldCoord * m_fScale );
2425
2426         m_projection[12] = 0.0f;
2427         m_projection[13] = 0.0f;
2428         m_projection[14] = -1.0f;
2429
2430         m_projection[1] =
2431                 m_projection[2] =
2432                         m_projection[3] =
2433
2434                                 m_projection[4] =
2435                                         m_projection[6] =
2436                                                 m_projection[7] =
2437
2438                                                         m_projection[8] =
2439                                                                 m_projection[9] =
2440                                                                         m_projection[11] = 0.0f;
2441
2442         m_projection[15] = 1.0f;
2443
2444         m_view.Construct( m_projection, m_modelview, m_nWidth, m_nHeight );
2445 }
2446
2447 // note: modelview matrix must have a uniform scale, otherwise strange things happen when rendering the rotation manipulator.
2448 void XYWnd::updateModelview(){
2449         int nDim1 = ( m_viewType == YZ ) ? 1 : 0;
2450         int nDim2 = ( m_viewType == XY ) ? 1 : 2;
2451
2452         // translation
2453         m_modelview[12] = -m_vOrigin[nDim1] * m_fScale;
2454         m_modelview[13] = -m_vOrigin[nDim2] * m_fScale;
2455         m_modelview[14] = g_MaxWorldCoord * m_fScale;
2456
2457         // axis base
2458         switch ( m_viewType )
2459         {
2460         case XY:
2461                 m_modelview[0]  =  m_fScale;
2462                 m_modelview[1]  =  0;
2463                 m_modelview[2]  =  0;
2464
2465                 m_modelview[4]  =  0;
2466                 m_modelview[5]  =  m_fScale;
2467                 m_modelview[6]  =  0;
2468
2469                 m_modelview[8]  =  0;
2470                 m_modelview[9]  =  0;
2471                 m_modelview[10] = -m_fScale;
2472                 break;
2473         case XZ:
2474                 m_modelview[0]  =  m_fScale;
2475                 m_modelview[1]  =  0;
2476                 m_modelview[2]  =  0;
2477
2478                 m_modelview[4]  =  0;
2479                 m_modelview[5]  =  0;
2480                 m_modelview[6]  =  m_fScale;
2481
2482                 m_modelview[8]  =  0;
2483                 m_modelview[9]  =  m_fScale;
2484                 m_modelview[10] =  0;
2485                 break;
2486         case YZ:
2487                 m_modelview[0]  =  0;
2488                 m_modelview[1]  =  0;
2489                 m_modelview[2]  = -m_fScale;
2490
2491                 m_modelview[4]  =  m_fScale;
2492                 m_modelview[5]  =  0;
2493                 m_modelview[6]  =  0;
2494
2495                 m_modelview[8]  =  0;
2496                 m_modelview[9]  =  m_fScale;
2497                 m_modelview[10] =  0;
2498                 break;
2499         }
2500
2501         m_modelview[3] = m_modelview[7] = m_modelview[11] = 0;
2502         m_modelview[15] = 1;
2503
2504         m_view.Construct( m_projection, m_modelview, m_nWidth, m_nHeight );
2505 }
2506
2507 /*
2508    ==============
2509    XY_Draw
2510    ==============
2511  */
2512
2513 //#define DBG_SCENEDUMP
2514
2515 void XYWnd::XY_Draw(){
2516         //
2517         // clear
2518         //
2519         glViewport( 0, 0, m_nWidth, m_nHeight );
2520         glClearColor( g_xywindow_globals.color_gridback[0],
2521                                   g_xywindow_globals.color_gridback[1],
2522                                   g_xywindow_globals.color_gridback[2],0 );
2523
2524         glClear( GL_COLOR_BUFFER_BIT );
2525
2526         //
2527         // set up viewpoint
2528         //
2529
2530         glMatrixMode( GL_PROJECTION );
2531         glLoadMatrixf( reinterpret_cast<const float*>( &m_projection ) );
2532
2533         glMatrixMode( GL_MODELVIEW );
2534         glLoadIdentity();
2535         glScalef( m_fScale, m_fScale, 1 );
2536         int nDim1 = ( m_viewType == YZ ) ? 1 : 0;
2537         int nDim2 = ( m_viewType == XY ) ? 1 : 2;
2538         glTranslatef( -m_vOrigin[nDim1], -m_vOrigin[nDim2], 0 );
2539
2540         glDisable( GL_LINE_STIPPLE );
2541         glLineWidth( 1 );
2542         glDisableClientState( GL_TEXTURE_COORD_ARRAY );
2543         glDisableClientState( GL_NORMAL_ARRAY );
2544         glDisableClientState( GL_COLOR_ARRAY );
2545         glDisable( GL_TEXTURE_2D );
2546         glDisable( GL_LIGHTING );
2547         glDisable( GL_COLOR_MATERIAL );
2548         glDisable( GL_DEPTH_TEST );
2549
2550         if ( m_backgroundActivated ) {
2551                 XY_DrawBackground();
2552         }
2553         XY_DrawGrid();
2554
2555         if ( g_xywindow_globals_private.show_blocks ) {
2556                 XY_DrawBlockGrid();
2557         }
2558
2559         glLoadMatrixf( reinterpret_cast<const float*>( &m_modelview ) );
2560
2561         unsigned int globalstate = RENDER_COLOURARRAY | RENDER_COLOURWRITE | RENDER_POLYGONSMOOTH | RENDER_LINESMOOTH;
2562         if ( !g_xywindow_globals.m_bNoStipple ) {
2563                 globalstate |= RENDER_LINESTIPPLE;
2564         }
2565
2566         {
2567                 XYRenderer renderer( globalstate, m_state_selected );
2568
2569                 Scene_Render( renderer, m_view );
2570
2571                 GlobalOpenGL_debugAssertNoErrors();
2572                 renderer.render( m_modelview, m_projection );
2573                 GlobalOpenGL_debugAssertNoErrors();
2574         }
2575
2576         glDepthMask( GL_FALSE );
2577
2578         GlobalOpenGL_debugAssertNoErrors();
2579
2580         glLoadMatrixf( reinterpret_cast<const float*>( &m_modelview ) );
2581
2582         GlobalOpenGL_debugAssertNoErrors();
2583         glDisable( GL_LINE_STIPPLE );
2584         GlobalOpenGL_debugAssertNoErrors();
2585         glLineWidth( 1 );
2586         GlobalOpenGL_debugAssertNoErrors();
2587         if ( GlobalOpenGL().GL_1_3() ) {
2588                 glActiveTexture( GL_TEXTURE0 );
2589                 glClientActiveTexture( GL_TEXTURE0 );
2590         }
2591         glDisableClientState( GL_TEXTURE_COORD_ARRAY );
2592         GlobalOpenGL_debugAssertNoErrors();
2593         glDisableClientState( GL_NORMAL_ARRAY );
2594         GlobalOpenGL_debugAssertNoErrors();
2595         glDisableClientState( GL_COLOR_ARRAY );
2596         GlobalOpenGL_debugAssertNoErrors();
2597         glDisable( GL_TEXTURE_2D );
2598         GlobalOpenGL_debugAssertNoErrors();
2599         glDisable( GL_LIGHTING );
2600         GlobalOpenGL_debugAssertNoErrors();
2601         glDisable( GL_COLOR_MATERIAL );
2602         GlobalOpenGL_debugAssertNoErrors();
2603
2604         GlobalOpenGL_debugAssertNoErrors();
2605
2606
2607         // size info
2608         if ( g_xywindow_globals_private.m_bSizePaint && GlobalSelectionSystem().countSelected() != 0 ) {
2609                 Vector3 min, max;
2610                 Select_GetBounds( min, max );
2611                 PaintSizeInfo( nDim1, nDim2, min, max );
2612         }
2613
2614         if ( g_bCrossHairs ) {
2615                 glColor4f( 0.2f, 0.9f, 0.2f, 0.8f );
2616                 glBegin( GL_LINES );
2617                 if ( m_viewType == XY ) {
2618                         glVertex2f( 2.0f * g_MinWorldCoord, m_mousePosition[1] );
2619                         glVertex2f( 2.0f * g_MaxWorldCoord, m_mousePosition[1] );
2620                         glVertex2f( m_mousePosition[0], 2.0f * g_MinWorldCoord );
2621                         glVertex2f( m_mousePosition[0], 2.0f * g_MaxWorldCoord );
2622                 }
2623                 else if ( m_viewType == YZ ) {
2624                         glVertex3f( m_mousePosition[0], 2.0f * g_MinWorldCoord, m_mousePosition[2] );
2625                         glVertex3f( m_mousePosition[0], 2.0f * g_MaxWorldCoord, m_mousePosition[2] );
2626                         glVertex3f( m_mousePosition[0], m_mousePosition[1], 2.0f * g_MinWorldCoord );
2627                         glVertex3f( m_mousePosition[0], m_mousePosition[1], 2.0f * g_MaxWorldCoord );
2628                 }
2629                 else
2630                 {
2631                         glVertex3f( 2.0f * g_MinWorldCoord, m_mousePosition[1], m_mousePosition[2] );
2632                         glVertex3f( 2.0f * g_MaxWorldCoord, m_mousePosition[1], m_mousePosition[2] );
2633                         glVertex3f( m_mousePosition[0], m_mousePosition[1], 2.0f * g_MinWorldCoord );
2634                         glVertex3f( m_mousePosition[0], m_mousePosition[1], 2.0f * g_MaxWorldCoord );
2635                 }
2636                 glEnd();
2637         }
2638
2639         if ( ClipMode() ) {
2640                 GlobalClipPoints_Draw( m_fScale );
2641         }
2642
2643         GlobalOpenGL_debugAssertNoErrors();
2644
2645         // reset modelview
2646         glLoadIdentity();
2647         glScalef( m_fScale, m_fScale, 1 );
2648         glTranslatef( -m_vOrigin[nDim1], -m_vOrigin[nDim2], 0 );
2649
2650         glEnable( GL_BLEND );
2651         glBlendFunc( GL_ONE_MINUS_DST_COLOR, GL_ZERO );
2652         DrawCameraIcon( Camera_getOrigin( *g_pParentWnd->GetCamWnd() ), Camera_getAngles( *g_pParentWnd->GetCamWnd() ) );
2653         glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA );
2654         glDisable( GL_BLEND );
2655
2656         Feedback_draw2D( m_viewType );
2657
2658         if ( g_xywindow_globals_private.show_outline ) {
2659                 if ( Active() ) {
2660                         glMatrixMode( GL_PROJECTION );
2661                         glLoadIdentity();
2662                         glOrtho( 0, m_nWidth, 0, m_nHeight, 0, 1 );
2663
2664                         glMatrixMode( GL_MODELVIEW );
2665                         glLoadIdentity();
2666
2667                         // four view mode doesn't colorize
2668                         if ( g_pParentWnd->CurrentStyle() == MainFrame::eSplit ) {
2669                                 glColor3fv( vector3_to_array( g_xywindow_globals.color_viewname ) );
2670                         }
2671                         else
2672                         {
2673                                 switch ( m_viewType )
2674                                 {
2675                                 case YZ:
2676                                         glColor3fv( vector3_to_array( g_xywindow_globals.AxisColorX ) );
2677                                         break;
2678                                 case XZ:
2679                                         glColor3fv( vector3_to_array( g_xywindow_globals.AxisColorY ) );
2680                                         break;
2681                                 case XY:
2682                                         glColor3fv( vector3_to_array( g_xywindow_globals.AxisColorZ ) );
2683                                         break;
2684                                 }
2685                         }
2686                         glBegin( GL_LINE_LOOP );
2687                         glVertex2f( 0.5, 0.5 );
2688                         glVertex2f( m_nWidth - 0.5, 1 );
2689                         glVertex2f( m_nWidth - 0.5, m_nHeight - 0.5 );
2690                         glVertex2f( 0.5, m_nHeight - 0.5 );
2691                         glEnd();
2692                 }
2693         }
2694
2695         GlobalOpenGL_debugAssertNoErrors();
2696
2697         glFinish();
2698 }
2699
2700 void XYWnd_MouseToPoint( XYWnd* xywnd, int x, int y, Vector3& point ){
2701         xywnd->XY_ToPoint( x, y, point );
2702         xywnd->XY_SnapToGrid( point );
2703
2704         int nDim = ( xywnd->GetViewType() == XY ) ? 2 : ( xywnd->GetViewType() == YZ ) ? 0 : 1;
2705         float fWorkMid = float_mid( Select_getWorkZone().d_work_min[nDim], Select_getWorkZone().d_work_max[nDim] );
2706         point[nDim] = float_snapped( fWorkMid, GetGridSize() );
2707 }
2708
2709 void XYWnd::OnEntityCreate( const char* item ){
2710         StringOutputStream command;
2711         command << "entityCreate -class " << item;
2712         UndoableCommand undo( command.c_str() );
2713         Vector3 point;
2714         XYWnd_MouseToPoint( this, m_entityCreate_x, m_entityCreate_y, point );
2715         Entity_createFromSelection( item, point );
2716 }
2717
2718
2719
2720 void GetCenterPosition( Vector3& position ){
2721         if ( GlobalSelectionSystem().countSelected() != 0 ) {
2722                 Select_GetMid( position );
2723         }
2724         else
2725         {
2726                 position = Camera_getOrigin( *g_pParentWnd->GetCamWnd() );
2727         }
2728 }
2729
2730 void XYWnd_Centralize( XYWnd* xywnd ){
2731         Vector3 position;
2732         GetCenterPosition( position );
2733         xywnd->PositionView( position );
2734 }
2735
2736 void XY_Split_Centralize(){
2737         Vector3 position;
2738         GetCenterPosition( position );
2739         if ( g_pParentWnd->GetXYWnd() ) {
2740                 g_pParentWnd->GetXYWnd()->PositionView( position );
2741         }
2742         if ( g_pParentWnd->GetXZWnd() ) {
2743                 g_pParentWnd->GetXZWnd()->PositionView( position );
2744         }
2745         if ( g_pParentWnd->GetYZWnd() ) {
2746                 g_pParentWnd->GetYZWnd()->PositionView( position );
2747         }
2748 }
2749
2750 void XY_Centralize(){
2751         if ( g_pParentWnd->CurrentStyle() == MainFrame::eSplit || g_pParentWnd->CurrentStyle() == MainFrame::eFloating ) {
2752                 // centralize all
2753                 XY_Split_Centralize();
2754                 return;
2755         }
2756
2757         XYWnd* xywnd = g_pParentWnd->GetXYWnd();
2758         XYWnd_Centralize( xywnd );
2759 }
2760
2761
2762
2763 void GetSelectionBbox( AABB& bounds ){
2764         if ( GlobalSelectionSystem().countSelected() != 0 ) {
2765                 Scene_BoundsSelected( GlobalSceneGraph(), bounds );
2766         }
2767         else
2768         {
2769                 bounds = AABB( Camera_getOrigin( *g_pParentWnd->GetCamWnd() ), Vector3( 128.f, 128.f, 128.f ) );
2770         }
2771 }
2772
2773 void XYWnd_Focus( XYWnd* xywnd ){
2774         AABB bounds;
2775         GetSelectionBbox( bounds );
2776         xywnd->FocusOnBounds( bounds );
2777 }
2778
2779 void XY_Split_Focus(){
2780         AABB bounds;
2781         GetSelectionBbox( bounds );
2782         if ( g_pParentWnd->GetXYWnd() ) {
2783                 g_pParentWnd->GetXYWnd()->FocusOnBounds( bounds );
2784         }
2785         if ( g_pParentWnd->GetXZWnd() ) {
2786                 g_pParentWnd->GetXZWnd()->FocusOnBounds( bounds );
2787         }
2788         if ( g_pParentWnd->GetYZWnd() ) {
2789                 g_pParentWnd->GetYZWnd()->FocusOnBounds( bounds );
2790         }
2791 }
2792
2793 void XY_Focus(){
2794         if ( g_pParentWnd->CurrentStyle() == MainFrame::eSplit || g_pParentWnd->CurrentStyle() == MainFrame::eFloating ) {
2795                 // focus all
2796                 XY_Split_Focus();
2797                 return;
2798         }
2799
2800         XYWnd* xywnd = g_pParentWnd->GetXYWnd();
2801         XYWnd_Focus( xywnd );
2802 }
2803
2804
2805
2806 void XY_TopFrontSide( VIEWTYPE viewtype ){
2807         if ( g_pParentWnd->CurrentStyle() == MainFrame::eSplit ) {
2808                 // cannot do this in a split window
2809                 // do something else that the user may want here
2810                 XY_Split_Centralize();
2811                 return;
2812         }
2813         XYWnd* xywnd = g_pParentWnd->CurrentStyle() == MainFrame::eFloating ? g_pParentWnd->ActiveXY() : g_pParentWnd->GetXYWnd();
2814         xywnd->SetViewType( viewtype );
2815         XYWnd_Centralize( xywnd );
2816 }
2817
2818 void XY_Top(){
2819         XY_TopFrontSide( XY );
2820 }
2821
2822 void XY_Side(){
2823         XY_TopFrontSide( XZ );
2824 }
2825
2826 void XY_Front(){
2827         XY_TopFrontSide( YZ );
2828 }
2829
2830 void XY_NextView( XYWnd* xywnd ){
2831         if ( xywnd->GetViewType() == XY ) {
2832                 xywnd->SetViewType( XZ );
2833         }
2834         else if ( xywnd->GetViewType() ==  XZ ) {
2835                 xywnd->SetViewType( YZ );
2836         }
2837         else{
2838                 xywnd->SetViewType( XY );
2839         }
2840         XYWnd_Centralize( xywnd );
2841 }
2842
2843 void XY_Next(){
2844         if ( g_pParentWnd->CurrentStyle() == MainFrame::eSplit ) {
2845                 // cannot do this in a split window
2846                 // do something else that the user may want here
2847                 XY_Split_Centralize();
2848                 return;
2849         }
2850         XYWnd* xywnd = g_pParentWnd->CurrentStyle() == MainFrame::eFloating ? g_pParentWnd->ActiveXY() : g_pParentWnd->GetXYWnd();
2851         XY_NextView( xywnd );
2852 }
2853
2854 void XY_Zoom100(){
2855         if ( g_pParentWnd->GetXYWnd() ) {
2856                 g_pParentWnd->GetXYWnd()->SetScale( 1 );
2857         }
2858         if ( g_pParentWnd->GetXZWnd() ) {
2859                 g_pParentWnd->GetXZWnd()->SetScale( 1 );
2860         }
2861         if ( g_pParentWnd->GetYZWnd() ) {
2862                 g_pParentWnd->GetYZWnd()->SetScale( 1 );
2863         }
2864 }
2865
2866 void XY_ZoomIn(){
2867         g_pParentWnd->ActiveXY()->ZoomIn();
2868 }
2869
2870 // NOTE: the zoom out factor is 4/5, we could think about customizing it
2871 //  we don't go below a zoom factor corresponding to 10% of the max world size
2872 //  (this has to be computed against the window size)
2873 void XY_ZoomOut(){
2874         g_pParentWnd->ActiveXY()->ZoomOut();
2875 }
2876
2877
2878
2879 ToggleShown g_xy_top_shown( true );
2880
2881 void XY_Top_Shown_Construct( GtkWindow* parent ){
2882         g_xy_top_shown.connect( GTK_WIDGET( parent ) );
2883 }
2884
2885 ToggleShown g_yz_side_shown( false );
2886
2887 void YZ_Side_Shown_Construct( GtkWindow* parent ){
2888         g_yz_side_shown.connect( GTK_WIDGET( parent ) );
2889 }
2890
2891 ToggleShown g_xz_front_shown( false );
2892
2893 void XZ_Front_Shown_Construct( GtkWindow* parent ){
2894         g_xz_front_shown.connect( GTK_WIDGET( parent ) );
2895 }
2896
2897
2898 class EntityClassMenu : public ModuleObserver
2899 {
2900 std::size_t m_unrealised;
2901 public:
2902 EntityClassMenu() : m_unrealised( 1 ){
2903 }
2904 void realise(){
2905         if ( --m_unrealised == 0 ) {
2906         }
2907 }
2908 void unrealise(){
2909         if ( ++m_unrealised == 1 ) {
2910                 if ( XYWnd::m_mnuDrop != 0 ) {
2911                         gtk_widget_destroy( GTK_WIDGET( XYWnd::m_mnuDrop ) );
2912                         XYWnd::m_mnuDrop = 0;
2913                 }
2914         }
2915 }
2916 };
2917
2918 EntityClassMenu g_EntityClassMenu;
2919
2920
2921
2922
2923 void ShowNamesExport( const BoolImportCallback& importer ){
2924         importer( GlobalEntityCreator().getShowNames() );
2925 }
2926 typedef FreeCaller1<const BoolImportCallback&, ShowNamesExport> ShowNamesExportCaller;
2927 ShowNamesExportCaller g_show_names_caller;
2928 ToggleItem g_show_names( g_show_names_caller );
2929 void ShowNamesToggle(){
2930         GlobalEntityCreator().setShowNames( !GlobalEntityCreator().getShowNames() );
2931         g_show_names.update();
2932         XY_UpdateAllWindows();
2933 }
2934
2935 void ShowTargetNamesExport( const BoolImportCallback& importer ){
2936         importer( GlobalEntityCreator().getShowTargetNames() );
2937 }
2938 typedef FreeCaller1<const BoolImportCallback&, ShowTargetNamesExport> ShowTargetNamesExportCaller;
2939 ShowTargetNamesExportCaller g_show_targetnames_caller;
2940 ToggleItem g_show_targetnames( g_show_targetnames_caller );
2941 void ShowTargetNamesToggle(){
2942         GlobalEntityCreator().setShowTargetNames( !GlobalEntityCreator().getShowTargetNames() );
2943         g_show_targetnames.update();
2944         XY_UpdateAllWindows();
2945 }
2946
2947 void ShowAnglesExport( const BoolImportCallback& importer ){
2948         importer( GlobalEntityCreator().getShowAngles() );
2949 }
2950 typedef FreeCaller1<const BoolImportCallback&, ShowAnglesExport> ShowAnglesExportCaller;
2951 ShowAnglesExportCaller g_show_angles_caller;
2952 ToggleItem g_show_angles( g_show_angles_caller );
2953 void ShowAnglesToggle(){
2954         GlobalEntityCreator().setShowAngles( !GlobalEntityCreator().getShowAngles() );
2955         g_show_angles.update();
2956         XY_UpdateAllWindows();
2957 }
2958
2959 BoolExportCaller g_show_blocks_caller( g_xywindow_globals_private.show_blocks );
2960 ToggleItem g_show_blocks( g_show_blocks_caller );
2961 void ShowBlocksToggle(){
2962         g_xywindow_globals_private.show_blocks ^= 1;
2963         g_show_blocks.update();
2964         XY_UpdateAllWindows();
2965 }
2966
2967 BoolExportCaller g_show_coordinates_caller( g_xywindow_globals_private.show_coordinates );
2968 ToggleItem g_show_coordinates( g_show_coordinates_caller );
2969 void ShowCoordinatesToggle(){
2970         g_xywindow_globals_private.show_coordinates ^= 1;
2971         g_show_coordinates.update();
2972         XY_UpdateAllWindows();
2973 }
2974
2975 BoolExportCaller g_show_outline_caller( g_xywindow_globals_private.show_outline );
2976 ToggleItem g_show_outline( g_show_outline_caller );
2977 void ShowOutlineToggle(){
2978         g_xywindow_globals_private.show_outline ^= 1;
2979         g_show_outline.update();
2980         XY_UpdateAllWindows();
2981 }
2982
2983 BoolExportCaller g_show_axes_caller( g_xywindow_globals_private.show_axis );
2984 ToggleItem g_show_axes( g_show_axes_caller );
2985 void ShowAxesToggle(){
2986         g_xywindow_globals_private.show_axis ^= 1;
2987         g_show_axes.update();
2988         XY_UpdateAllWindows();
2989 }
2990
2991
2992 BoolExportCaller g_show_workzone_caller( g_xywindow_globals_private.d_show_work );
2993 ToggleItem g_show_workzone( g_show_workzone_caller );
2994 void ShowWorkzoneToggle(){
2995         g_xywindow_globals_private.d_show_work ^= 1;
2996         g_show_workzone.update();
2997         XY_UpdateAllWindows();
2998 }
2999
3000 /*
3001 void ShowAxesToggle(){
3002         g_xywindow_globals_private.show_axis ^= 1;
3003         XY_UpdateAllWindows();
3004 }
3005 typedef FreeCaller<ShowAxesToggle> ShowAxesToggleCaller;
3006 void ShowAxesExport( const BoolImportCallback& importer ){
3007         importer( g_xywindow_globals_private.show_axis );
3008 }
3009 typedef FreeCaller1<const BoolImportCallback&, ShowAxesExport> ShowAxesExportCaller;
3010
3011 ShowAxesExportCaller g_show_axes_caller;
3012 BoolExportCallback g_show_axes_callback( g_show_axes_caller );
3013 ToggleItem g_show_axes( g_show_axes_callback );
3014 */
3015
3016 /*
3017 BoolExportCaller g_texdef_movelock_caller( g_brush_texturelock_enabled );
3018 ToggleItem g_texdef_movelock_item( g_texdef_movelock_caller );
3019
3020 void Texdef_ToggleMoveLock(){
3021         g_brush_texturelock_enabled = !g_brush_texturelock_enabled;
3022         g_texdef_movelock_item.update();
3023 }
3024 */
3025
3026 BoolExportCaller g_show_size_caller( g_xywindow_globals_private.m_bSizePaint );
3027 ToggleItem g_show_size_item( g_show_size_caller );
3028 void ToggleShowSizeInfo(){
3029         g_xywindow_globals_private.m_bSizePaint = !g_xywindow_globals_private.m_bSizePaint;
3030         g_show_size_item.update();
3031         XY_UpdateAllWindows();
3032 }
3033
3034 BoolExportCaller g_show_crosshair_caller( g_bCrossHairs );
3035 ToggleItem g_show_crosshair_item( g_show_crosshair_caller );
3036 void ToggleShowCrosshair(){
3037         g_bCrossHairs ^= 1;
3038         g_show_crosshair_item.update();
3039         XY_UpdateAllWindows();
3040 }
3041
3042 BoolExportCaller g_show_grid_caller( g_xywindow_globals_private.d_showgrid );
3043 ToggleItem g_show_grid_item( g_show_grid_caller );
3044 void ToggleShowGrid(){
3045         g_xywindow_globals_private.d_showgrid = !g_xywindow_globals_private.d_showgrid;
3046         g_show_grid_item.update();
3047         XY_UpdateAllWindows();
3048 }
3049
3050
3051 void XYShow_registerCommands(){
3052         GlobalToggles_insert( "ToggleSizePaint", FreeCaller<ToggleShowSizeInfo>(), ToggleItem::AddCallbackCaller( g_show_size_item ), Accelerator( 'J' ) );
3053         GlobalToggles_insert( "ToggleCrosshairs", FreeCaller<ToggleShowCrosshair>(), ToggleItem::AddCallbackCaller( g_show_crosshair_item ), Accelerator( 'X', (GdkModifierType)GDK_SHIFT_MASK ) );
3054         GlobalToggles_insert( "ToggleGrid", FreeCaller<ToggleShowGrid>(), ToggleItem::AddCallbackCaller( g_show_grid_item ), Accelerator( '0' ) );
3055
3056         GlobalToggles_insert( "ShowAngles", FreeCaller<ShowAnglesToggle>(), ToggleItem::AddCallbackCaller( g_show_angles ) );
3057         GlobalToggles_insert( "ShowNames", FreeCaller<ShowNamesToggle>(), ToggleItem::AddCallbackCaller( g_show_names ) );
3058         GlobalToggles_insert( "ShowTargetNames", FreeCaller<ShowTargetNamesToggle>(), ToggleItem::AddCallbackCaller( g_show_targetnames ) );
3059         GlobalToggles_insert( "ShowBlocks", FreeCaller<ShowBlocksToggle>(), ToggleItem::AddCallbackCaller( g_show_blocks ) );
3060         GlobalToggles_insert( "ShowCoordinates", FreeCaller<ShowCoordinatesToggle>(), ToggleItem::AddCallbackCaller( g_show_coordinates ) );
3061         GlobalToggles_insert( "ShowWindowOutline", FreeCaller<ShowOutlineToggle>(), ToggleItem::AddCallbackCaller( g_show_outline ) );
3062         GlobalToggles_insert( "ShowAxes", FreeCaller<ShowAxesToggle>(), ToggleItem::AddCallbackCaller( g_show_axes ) );
3063         GlobalToggles_insert( "ShowWorkzone", FreeCaller<ShowWorkzoneToggle>(), ToggleItem::AddCallbackCaller( g_show_workzone ) );
3064 }
3065
3066 void XYWnd_registerShortcuts(){
3067         command_connect_accelerator( "ToggleCrosshairs" );
3068         command_connect_accelerator( "ToggleSizePaint" );
3069 }
3070
3071
3072
3073 void Orthographic_constructPreferences( PreferencesPage& page ){
3074         page.appendCheckBox( "", "Solid selection boxes ( no stipple )", g_xywindow_globals.m_bNoStipple );
3075         //page.appendCheckBox( "", "Display size info", g_xywindow_globals_private.m_bSizePaint );
3076         page.appendCheckBox( "", "Chase mouse during drags", g_xywindow_globals_private.m_bChaseMouse );
3077 //      page.appendCheckBox( "", "Update views on camera move", g_xywindow_globals_private.m_bCamXYUpdate );
3078         page.appendCheckBox( "", "Zoom In to Mouse pointer", g_xywindow_globals.m_bZoomInToPointer );
3079 }
3080 void Orthographic_constructPage( PreferenceGroup& group ){
3081         PreferencesPage page( group.createPage( "Orthographic", "Orthographic View Preferences" ) );
3082         Orthographic_constructPreferences( page );
3083 }
3084 void Orthographic_registerPreferencesPage(){
3085         PreferencesDialog_addSettingsPage( FreeCaller1<PreferenceGroup&, Orthographic_constructPage>() );
3086 }
3087
3088 void Clipper_constructPreferences( PreferencesPage& page ){
3089         page.appendCheckBox( "", "Clipper tool uses caulk", g_clip_useCaulk );
3090 }
3091 void Clipper_constructPage( PreferenceGroup& group ){
3092         PreferencesPage page( group.createPage( "Clipper", "Clipper Tool Settings" ) );
3093         Clipper_constructPreferences( page );
3094 }
3095 void Clipper_registerPreferencesPage(){
3096         PreferencesDialog_addSettingsPage( FreeCaller1<PreferenceGroup&, Clipper_constructPage>() );
3097 }
3098
3099
3100 #include "preferencesystem.h"
3101 #include "stringio.h"
3102
3103
3104
3105
3106 void ToggleShown_importBool( ToggleShown& self, bool value ){
3107         self.set( value );
3108 }
3109 typedef ReferenceCaller1<ToggleShown, bool, ToggleShown_importBool> ToggleShownImportBoolCaller;
3110 void ToggleShown_exportBool( const ToggleShown& self, const BoolImportCallback& importer ){
3111         importer( self.active() );
3112 }
3113 typedef ConstReferenceCaller1<ToggleShown, const BoolImportCallback&, ToggleShown_exportBool> ToggleShownExportBoolCaller;
3114
3115
3116 void XYWindow_Construct(){
3117 //      GlobalCommands_insert( "ToggleCrosshairs", FreeCaller<ToggleShowCrosshair>(), Accelerator( 'X', (GdkModifierType)GDK_SHIFT_MASK ) );
3118 //      GlobalCommands_insert( "ToggleSizePaint", FreeCaller<ToggleShowSizeInfo>(), Accelerator( 'J' ) );
3119 //      GlobalCommands_insert( "ToggleGrid", FreeCaller<ToggleShowGrid>(), Accelerator( '0' ) );
3120
3121         GlobalToggles_insert( "ToggleView", ToggleShown::ToggleCaller( g_xy_top_shown ), ToggleItem::AddCallbackCaller( g_xy_top_shown.m_item ), Accelerator( 'V', (GdkModifierType)( GDK_SHIFT_MASK | GDK_CONTROL_MASK ) ) );
3122         GlobalToggles_insert( "ToggleSideView", ToggleShown::ToggleCaller( g_yz_side_shown ), ToggleItem::AddCallbackCaller( g_yz_side_shown.m_item ) );
3123         GlobalToggles_insert( "ToggleFrontView", ToggleShown::ToggleCaller( g_xz_front_shown ), ToggleItem::AddCallbackCaller( g_xz_front_shown.m_item ) );
3124         GlobalCommands_insert( "NextView", FreeCaller<XY_Next>(), Accelerator( GDK_Tab, (GdkModifierType)GDK_CONTROL_MASK ) );
3125         GlobalCommands_insert( "ZoomIn", FreeCaller<XY_ZoomIn>(), Accelerator( GDK_Delete ) );
3126         GlobalCommands_insert( "ZoomOut", FreeCaller<XY_ZoomOut>(), Accelerator( GDK_Insert ) );
3127         GlobalCommands_insert( "ViewTop", FreeCaller<XY_Top>(), Accelerator( GDK_KP_Home ) );
3128         GlobalCommands_insert( "ViewSide", FreeCaller<XY_Side>(), Accelerator( GDK_KP_Page_Down ) );
3129         GlobalCommands_insert( "ViewFront", FreeCaller<XY_Front>(), Accelerator( GDK_KP_End ) );
3130         GlobalCommands_insert( "Zoom100", FreeCaller<XY_Zoom100>() );
3131         GlobalCommands_insert( "CenterXYView", FreeCaller<XY_Centralize>(), Accelerator( GDK_Tab, (GdkModifierType)( GDK_SHIFT_MASK | GDK_CONTROL_MASK ) ) );
3132         GlobalCommands_insert( "XYFocusOnSelected", FreeCaller<XY_Focus>(), Accelerator( GDK_grave ) );
3133
3134         GlobalPreferenceSystem().registerPreference( "ClipCaulk", BoolImportStringCaller( g_clip_useCaulk ), BoolExportStringCaller( g_clip_useCaulk ) );
3135
3136 //      GlobalPreferenceSystem().registerPreference( "NewRightClick", BoolImportStringCaller( g_xywindow_globals.m_bRightClick ), BoolExportStringCaller( g_xywindow_globals.m_bRightClick ) );
3137         GlobalPreferenceSystem().registerPreference( "2DZoomInToPointer", BoolImportStringCaller( g_xywindow_globals.m_bZoomInToPointer ), BoolExportStringCaller( g_xywindow_globals.m_bZoomInToPointer ) );
3138         GlobalPreferenceSystem().registerPreference( "ChaseMouse", BoolImportStringCaller( g_xywindow_globals_private.m_bChaseMouse ), BoolExportStringCaller( g_xywindow_globals_private.m_bChaseMouse ) );
3139         GlobalPreferenceSystem().registerPreference( "SizePainting", BoolImportStringCaller( g_xywindow_globals_private.m_bSizePaint ), BoolExportStringCaller( g_xywindow_globals_private.m_bSizePaint ) );
3140         GlobalPreferenceSystem().registerPreference( "ShowCrosshair", BoolImportStringCaller( g_bCrossHairs ), BoolExportStringCaller( g_bCrossHairs ) );
3141         GlobalPreferenceSystem().registerPreference( "NoStipple", BoolImportStringCaller( g_xywindow_globals.m_bNoStipple ), BoolExportStringCaller( g_xywindow_globals.m_bNoStipple ) );
3142         GlobalPreferenceSystem().registerPreference( "SI_ShowCoords", BoolImportStringCaller( g_xywindow_globals_private.show_coordinates ), BoolExportStringCaller( g_xywindow_globals_private.show_coordinates ) );
3143         GlobalPreferenceSystem().registerPreference( "SI_ShowOutlines", BoolImportStringCaller( g_xywindow_globals_private.show_outline ), BoolExportStringCaller( g_xywindow_globals_private.show_outline ) );
3144         GlobalPreferenceSystem().registerPreference( "SI_ShowAxis", BoolImportStringCaller( g_xywindow_globals_private.show_axis ), BoolExportStringCaller( g_xywindow_globals_private.show_axis ) );
3145 //      GlobalPreferenceSystem().registerPreference( "CamXYUpdate", BoolImportStringCaller( g_xywindow_globals_private.m_bCamXYUpdate ), BoolExportStringCaller( g_xywindow_globals_private.m_bCamXYUpdate ) );
3146         GlobalPreferenceSystem().registerPreference( "ShowWorkzone", BoolImportStringCaller( g_xywindow_globals_private.d_show_work ), BoolExportStringCaller( g_xywindow_globals_private.d_show_work ) );
3147
3148         GlobalPreferenceSystem().registerPreference( "SI_AxisColors0", Vector3ImportStringCaller( g_xywindow_globals.AxisColorX ), Vector3ExportStringCaller( g_xywindow_globals.AxisColorX ) );
3149         GlobalPreferenceSystem().registerPreference( "SI_AxisColors1", Vector3ImportStringCaller( g_xywindow_globals.AxisColorY ), Vector3ExportStringCaller( g_xywindow_globals.AxisColorY ) );
3150         GlobalPreferenceSystem().registerPreference( "SI_AxisColors2", Vector3ImportStringCaller( g_xywindow_globals.AxisColorZ ), Vector3ExportStringCaller( g_xywindow_globals.AxisColorZ ) );
3151         GlobalPreferenceSystem().registerPreference( "SI_Colors1", Vector3ImportStringCaller( g_xywindow_globals.color_gridback ), Vector3ExportStringCaller( g_xywindow_globals.color_gridback ) );
3152         GlobalPreferenceSystem().registerPreference( "SI_Colors2", Vector3ImportStringCaller( g_xywindow_globals.color_gridminor ), Vector3ExportStringCaller( g_xywindow_globals.color_gridminor ) );
3153         GlobalPreferenceSystem().registerPreference( "SI_Colors3", Vector3ImportStringCaller( g_xywindow_globals.color_gridmajor ), Vector3ExportStringCaller( g_xywindow_globals.color_gridmajor ) );
3154         GlobalPreferenceSystem().registerPreference( "SI_Colors6", Vector3ImportStringCaller( g_xywindow_globals.color_gridblock ), Vector3ExportStringCaller( g_xywindow_globals.color_gridblock ) );
3155         GlobalPreferenceSystem().registerPreference( "SI_Colors7", Vector3ImportStringCaller( g_xywindow_globals.color_gridtext ), Vector3ExportStringCaller( g_xywindow_globals.color_gridtext ) );
3156         GlobalPreferenceSystem().registerPreference( "SI_Colors8", Vector3ImportStringCaller( g_xywindow_globals.color_brushes ), Vector3ExportStringCaller( g_xywindow_globals.color_brushes ) );
3157         GlobalPreferenceSystem().registerPreference( "SI_Colors9", Vector3ImportStringCaller( g_xywindow_globals.color_viewname ), Vector3ExportStringCaller( g_xywindow_globals.color_viewname ) );
3158         GlobalPreferenceSystem().registerPreference( "SI_Colors10", Vector3ImportStringCaller( g_xywindow_globals.color_clipper ), Vector3ExportStringCaller( g_xywindow_globals.color_clipper ) );
3159         GlobalPreferenceSystem().registerPreference( "SI_Colors11", Vector3ImportStringCaller( g_xywindow_globals.color_selbrushes ), Vector3ExportStringCaller( g_xywindow_globals.color_selbrushes ) );
3160
3161
3162         GlobalPreferenceSystem().registerPreference( "XZVIS", makeBoolStringImportCallback( ToggleShownImportBoolCaller( g_xz_front_shown ) ), makeBoolStringExportCallback( ToggleShownExportBoolCaller( g_xz_front_shown ) ) );
3163         GlobalPreferenceSystem().registerPreference( "YZVIS", makeBoolStringImportCallback( ToggleShownImportBoolCaller( g_yz_side_shown ) ), makeBoolStringExportCallback( ToggleShownExportBoolCaller( g_yz_side_shown ) ) );
3164
3165         Orthographic_registerPreferencesPage();
3166         Clipper_registerPreferencesPage();
3167
3168         XYWnd::captureStates();
3169         GlobalEntityClassManager().attach( g_EntityClassMenu );
3170 }
3171
3172 void XYWindow_Destroy(){
3173         GlobalEntityClassManager().detach( g_EntityClassMenu );
3174         XYWnd::releaseStates();
3175 }