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