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