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