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