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