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