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