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